]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/newcloud.cxx
3D clouds from Stuart Buchanan. Need a recent driver update, --enable-clouds3d option...
[simgear.git] / simgear / scene / sky / newcloud.cxx
1 // 3D cloud class
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <osg/AlphaFunc>
28 #include <osg/Program>
29 #include <osg/Uniform>
30 #include <osg/ref_ptr>
31 #include <osg/Texture2D>
32 #include <osg/NodeVisitor>
33 #include <osg/PositionAttitudeTransform>
34 #include <osg/Material>
35 #include <osgUtil/UpdateVisitor>
36 #include <osgDB/ReadFile>
37 #include <osgDB/FileUtils>
38
39
40 #include <simgear/compiler.h>
41
42 #include <plib/sg.h>
43 #include <simgear/math/sg_random.h>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/misc/PathOptions.hxx>
46 #include <simgear/scene/model/model.hxx>
47 #include <simgear/scene/util/StateAttributeFactory.hxx>
48 #include <simgear/scene/util/SGUpdateVisitor.hxx>
49
50 #include <algorithm>
51 #include <osg/GLU>
52
53 #include "cloudfield.hxx"
54 #include "newcloud.hxx"
55 #include "CloudShaderGeometry.hxx"
56
57 using namespace simgear;
58 using namespace osg;
59
60 typedef std::map<std::string, osg::ref_ptr<osg::StateSet> > StateSetMap;
61
62 static StateSetMap cloudTextureMap;
63
64 static char vertexShaderSource[] = 
65     "#version 120\n"
66     "\n"
67     "varying float fogFactor;\n"
68     "varying float alphaBlend;\n"
69     "attribute float textureIndexX;\n"
70     "attribute float textureIndexY;\n"
71     "attribute float wScale;\n"
72     "attribute float hScale;\n"
73     "attribute float shade;\n"
74     "void main(void)\n"
75     "{\n"
76     "  gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndexX, textureIndexY, 0.0, 0.0);\n"
77     "  vec4 ep = gl_ModelViewMatrixInverse * vec4(0.0,0.0,0.0,1.0);\n"
78     "  vec4 l  = gl_ModelViewMatrixInverse * vec4(0.0,0.0,1.0,1.0);\n"
79     "  vec3 u = normalize(ep.xyz - l.xyz);\n"
80 // Find a rotation matrix that rotates 1,0,0 into u. u, r and w are
81 // the columns of that matrix.
82     "  vec3 absu = abs(u);\n"
83     "  vec3 r = normalize(vec3(-u.y, u.x, 0));\n"
84     "  vec3 w = cross(u, r);\n"
85 // Do the matrix multiplication by [ u r w pos]. Assume no
86 // scaling in the homogeneous component of pos.
87     "  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
88     "  gl_Position.xyz = gl_Vertex.x * u * wScale;\n"
89     "  gl_Position.xyz += gl_Vertex.y * r * hScale;\n"
90     "  gl_Position.xyz += gl_Vertex.z * w;\n"
91     "  gl_Position.xyz += gl_Color.xyz;\n"
92 // Determine a lighting normal based on the sprites position from the
93 // center of the cloud. 
94     "  float n = dot(normalize(gl_LightSource[0].position.xyz), normalize(mat3x3(gl_ModelViewMatrix) * gl_Position.xyz));\n"
95 // Determine the position - used for fog and shading calculations        
96     "  vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Position);\n"
97     "  float fogCoord = abs(ecPosition.z);\n"
98 // Final position of the sprite
99     "  gl_Position = gl_ModelViewProjectionMatrix * gl_Position;\n"
100 // Limit the normal range from [0,1.0], and apply the shading (vertical factor)
101     "  n = min(smoothstep(-0.5, 0.5, n), shade);\n"
102 // This lighting normal is then used to mix between almost pure ambient (0) and diffuse (1.0) light
103     "  vec4 backlight = 0.8 * gl_LightSource[0].ambient + 0.2 * gl_LightSource[0].diffuse;\n"
104     "  gl_FrontColor = mix(backlight, gl_LightSource[0].diffuse, n);\n"
105     "  gl_FrontColor += gl_FrontLightModelProduct.sceneColor;\n"
106     "  gl_FrontColor.a = smoothstep(10.0, 100.0, fogCoord);\n"
107     "  gl_BackColor = gl_FrontColor;\n"
108 // Fog doesn't affect clouds as much as other objects.        
109     "  fogFactor = exp( -gl_Fog.density * fogCoord);\n"
110     "  fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
111 // As we get within 100m of the sprite, it is faded out
112     "  alphaBlend = smoothstep(10.0, 100.0, fogCoord);\n"
113     "}\n";
114
115 static char fragmentShaderSource[] = 
116     "uniform sampler2D baseTexture; \n"
117     "varying float fogFactor;\n"
118     "varying float alphaBlend;\n"
119     "\n"
120     "void main(void)\n"
121     "{\n"
122     "  vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
123     "  vec4 finalColor = base * gl_Color;\n"
124 //    "  finalColor.a = min(alphaBlend, finalColor.a);\n"
125     "  gl_FragColor = mix(gl_Fog.color, finalColor, fogFactor );\n"
126     "}\n";
127
128 class SGCloudFogUpdateCallback : public osg::StateAttribute::Callback {
129     public:
130         virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
131         {
132             SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
133             osg::Fog* fog = static_cast<osg::Fog*>(sa);
134             fog->setMode(osg::Fog::EXP);
135             fog->setColor(updateVisitor->getFogColor().osg());
136             fog->setDensity(updateVisitor->getFogExpDensity());
137         }
138 };
139
140 SGNewCloud::SGNewCloud(const SGPath &tex_path, 
141                        string tex,
142                        double min_w,
143                        double max_w,
144                        double min_h,
145                        double max_h,
146                        double min_sprite_w,
147                        double max_sprite_w,
148                        double min_sprite_h,
149                        double max_sprite_h,
150                        double b,
151                        int n,
152                        int nt_x,
153                        int nt_y) :
154         min_width(min_w),
155         max_width(max_w),
156         min_height(min_h),
157         max_height(max_h),
158         min_sprite_width(min_sprite_w),
159         max_sprite_width(max_sprite_w),
160         min_sprite_height(min_sprite_h),
161         max_sprite_height(max_sprite_h),
162         bottom_shade(b),
163         num_sprites(n),
164         num_textures_x(nt_x),
165         num_textures_y(nt_y),
166         texture(tex)
167 {
168     // Create a new StateSet for the texture, if required.
169     StateSetMap::iterator iter = cloudTextureMap.find(texture);
170
171     if (iter == cloudTextureMap.end()) {
172         stateSet = new osg::StateSet;
173                 
174         osg::ref_ptr<osgDB::ReaderWriter::Options> options = makeOptionsFromPath(tex_path);
175                 
176         osg::Texture2D *tex = new osg::Texture2D;
177         tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
178         tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
179         tex->setImage(osgDB::readImageFile(texture, options.get()));
180                 
181         StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
182         
183         stateSet->setMode(GL_LIGHTING,  osg::StateAttribute::ON);
184         stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
185         
186         // Fog handling
187         osg::Fog* fog = new osg::Fog;
188         fog->setUpdateCallback(new SGCloudFogUpdateCallback);
189         stateSet->setAttributeAndModes(fog);
190         stateSet->setDataVariance(osg::Object::DYNAMIC);
191         
192         stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
193         stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
194
195         stateSet->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
196         stateSet->setRenderBinDetails(osg::StateSet::TRANSPARENT_BIN, "DepthSortedBin");
197                 
198         static ref_ptr<AlphaFunc> alphaFunc;
199         static ref_ptr<Program> program;
200         static ref_ptr<Uniform> baseTextureSampler;
201         static ref_ptr<Material> material;
202                   
203         // Generate the shader etc, if we don't already have one.
204         if (!program.valid()) {
205             alphaFunc = new AlphaFunc;
206             alphaFunc->setFunction(AlphaFunc::GREATER,0.002f);
207             program  = new Program;
208             baseTextureSampler = new osg::Uniform("baseTexture", 0);
209             Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
210             program->addShader(vertex_shader);
211             program->addBindAttribLocation("textureIndexX", CloudShaderGeometry::TEXTURE_INDEX_X);
212             program->addBindAttribLocation("textureIndexY", CloudShaderGeometry::TEXTURE_INDEX_Y);
213             program->addBindAttribLocation("wScale", CloudShaderGeometry::WIDTH);
214             program->addBindAttribLocation("hScale", CloudShaderGeometry::HEIGHT);
215             program->addBindAttribLocation("shade", CloudShaderGeometry::SHADE);
216                   
217             Shader* fragment_shader = new Shader(Shader::FRAGMENT, fragmentShaderSource);
218             program->addShader(fragment_shader);
219             material = new Material;
220             // DonĀ“t track vertex color
221             material->setColorMode(Material::OFF);
222             
223             // We don't actually use the material information either - see shader.
224             material->setAmbient(Material::FRONT_AND_BACK,
225                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
226             material->setDiffuse(Material::FRONT_AND_BACK,
227                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
228         }
229                   
230         stateSet->setAttributeAndModes(alphaFunc.get());
231         stateSet->setAttribute(program.get());
232         stateSet->addUniform(baseTextureSampler.get());
233         stateSet->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
234         stateSet->setAttribute(material.get());
235                 
236         // Add the newly created texture to the map for use later.
237         cloudTextureMap.insert(StateSetMap::value_type(texture,  stateSet));
238     } else {
239         stateSet = iter->second.get();
240     }
241 }
242
243 SGNewCloud::~SGNewCloud() {
244 }
245
246 osg::Geometry* createOrthQuad(float w, float h, int varieties_x, int varieties_y)
247 {
248     // Create front and back polygons so we don't need to screw around
249     // with two-sided lighting in the shader.
250     osg::Vec3Array& v = *(new osg::Vec3Array(4));
251     osg::Vec3Array& n = *(new osg::Vec3Array(4));
252     osg::Vec2Array& t = *(new osg::Vec2Array(4));
253     
254     float cw = w*0.5f;
255
256     v[0].set(0.0f, -cw, 0.0f);
257     v[1].set(0.0f,  cw, 0.0f);
258     v[2].set(0.0f,  cw, h);
259     v[3].set(0.0f, -cw, h);
260     
261     // The texture coordinate range is not the
262     // entire coordinate space - as the texture
263     // has a number of different clouds on it.
264     float tx = 1.0f/varieties_x;
265     float ty = 1.0f/varieties_y;
266
267     t[0].set(0.0f, 0.0f);
268     t[1].set(  tx, 0.0f);
269     t[2].set(  tx, ty);
270     t[3].set(0.0f, ty);
271
272     // The normal isn't actually use in lighting.
273     n[0].set(1.0f, -1.0f, -1.0f);
274     n[1].set(1.0f,  1.0f, -1.0f);
275     n[2].set(1.0f,  1.0f,  1.0f);
276     n[3].set(1.0f, -1.0f,  1.0f);
277
278     osg::Geometry *geom = new osg::Geometry;
279
280     geom->setVertexArray(&v);
281     geom->setTexCoordArray(0, &t);
282     geom->setNormalArray(&n);
283     geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
284     // No color for now; that's used to pass the position.
285     geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
286
287     return geom;
288 }
289
290 // return a random number between -n/2 and n/2, tending to 0
291 static float Rnd(float n) {
292     return n * (-0.5f + (sg_random() + sg_random()) / 2.0f);
293 }
294
295 osg::ref_ptr<LOD> SGNewCloud::genCloud() {
296     LOD* result = new LOD;
297     Geode* geode = new Geode;
298     CloudShaderGeometry* sg = new CloudShaderGeometry(num_textures_x, num_textures_y);
299     
300     Geometry* quad = createOrthQuad(min_sprite_width, min_sprite_height, num_textures_x, num_textures_y);
301     
302     // Determine how big this specific cloud instance is.
303     float width = min_width + sg_random() * (max_width - min_width);
304     float height = min_height + sg_random() * (max_height - min_height);
305     
306     // Determine the cull distance. This is used to remove sprites that are too close together.
307     // The value is squared as we use vector calculations.
308     float cull_distance_squared = min_sprite_height * min_sprite_height * 0.1f;
309     
310     for (int i = 0; i < num_sprites; i++)
311     {
312         // Determine the position of the sprite.
313         SGVec3f *pos = new SGVec3f(Rnd(width),
314                                    Rnd(width),
315                                    Rnd(height));
316
317         // Determine the height and width as scaling factors on the minimum size (used to create the quad)
318         float sprite_width = 1.0f + sg_random() * (max_sprite_width - min_sprite_width) / min_sprite_width;
319         float sprite_height = 1.0f + sg_random() * (max_sprite_height - min_sprite_height) / min_sprite_height;
320         
321         // The shade varies from bottom_shade to 1.0 non-linearly
322         float shade;
323         if (pos->z() > 0.0f) { 
324             shade = 1.0f; 
325         } else {
326             shade = ((2 * pos->z() + height) / height) * (1 - bottom_shade) + bottom_shade;
327         }
328         
329         // Determine the sprite texture indexes;
330         int index_x = (int) floor(sg_random() * num_textures_x);
331         if (index_x == num_textures_x) { index_x--; }
332         
333         int index_y = (int) floor(sg_random() * num_textures_y);
334         if (index_y == num_textures_y) { index_y--; }
335         
336         sg->addSprite(*pos, index_x, index_y, sprite_width, sprite_height, shade, cull_distance_squared);
337     }
338     
339     sg->setGeometry(quad);
340     geode->addDrawable(sg);
341     geode->setName("3D cloud");
342     geode->setStateSet(stateSet.get());
343     result->addChild(geode, 0, 20000);
344     return result;
345 }