]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/newcloud.cxx
Stuart Buchanan:
[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/Depth>
29 #include <osg/Program>
30 #include <osg/Uniform>
31 #include <osg/ref_ptr>
32 #include <osg/Texture2D>
33 #include <osg/NodeVisitor>
34 #include <osg/PositionAttitudeTransform>
35 #include <osg/Material>
36 #include <osgUtil/UpdateVisitor>
37 #include <osgDB/ReadFile>
38 #include <osgDB/FileUtils>
39
40
41 #include <simgear/compiler.h>
42
43 #include <plib/sg.h>
44 #include <simgear/math/sg_random.h>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/misc/PathOptions.hxx>
47 #include <simgear/scene/model/model.hxx>
48 #include <simgear/scene/util/StateAttributeFactory.hxx>
49 #include <simgear/scene/util/SGUpdateVisitor.hxx>
50
51 #include <algorithm>
52 #include <osg/BlendFunc>
53 #include <osg/GLU>
54 #include <osg/ShadeModel>
55
56 #include "cloudfield.hxx"
57 #include "newcloud.hxx"
58 #include "CloudShaderGeometry.hxx"
59
60 using namespace simgear;
61 using namespace osg;
62
63 typedef std::map<std::string, osg::ref_ptr<osg::StateSet> > StateSetMap;
64
65 StateSetMap cloudTextureMap;
66 double SGNewCloud::sprite_density = 1.0;
67
68 static char vertexShaderSource[] = 
69     "#version 120\n"
70     "\n"
71     "varying float fogFactor;\n"
72     "attribute vec3 usrAttr1;\n"
73     "attribute vec3 usrAttr2;\n"
74     "float textureIndexX = usrAttr1.r;\n"
75     "float textureIndexY = usrAttr1.g;\n"
76     "float wScale = usrAttr1.b;\n"
77     "float hScale = usrAttr2.r;\n"
78     "float shade = usrAttr2.g;\n"
79     "float cloud_height = usrAttr2.b;\n"
80     "void main(void)\n"
81     "{\n"
82     "  gl_TexCoord[0] = gl_MultiTexCoord0 + vec4(textureIndexX, textureIndexY, 0.0, 0.0);\n"
83     "  vec4 ep = gl_ModelViewMatrixInverse * vec4(0.0,0.0,0.0,1.0);\n"
84     "  vec4 l  = gl_ModelViewMatrixInverse * vec4(0.0,0.0,1.0,1.0);\n"
85     "  vec3 u = normalize(ep.xyz - l.xyz);\n"
86 // Find a rotation matrix that rotates 1,0,0 into u. u, r and w are
87 // the columns of that matrix.
88     "  vec3 absu = abs(u);\n"
89     "  vec3 r = normalize(vec3(-u.y, u.x, 0));\n"
90     "  vec3 w = cross(u, r);\n"
91 // Do the matrix multiplication by [ u r w pos]. Assume no
92 // scaling in the homogeneous component of pos.
93     "  gl_Position = vec4(0.0, 0.0, 0.0, 1.0);\n"
94     "  gl_Position.xyz = gl_Vertex.x * u;\n"
95     "  gl_Position.xyz += gl_Vertex.y * r * wScale;\n"
96     "  gl_Position.xyz += gl_Vertex.z * w * hScale;\n"
97     "  gl_Position.xyz += gl_Color.xyz;\n"
98 // Determine a lighting normal based on the vertex position from the
99 // center of the cloud, so that sprite on the opposite side of the cloud to the sun are darker.
100     "  float n = dot(normalize(- gl_LightSource[0].position.xyz), normalize(mat3x3(gl_ModelViewMatrix) * (- gl_Position.xyz)));\n"
101 // Determine the position - used for fog and shading calculations        
102     "  vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Position);\n"
103     "  float fogCoord = abs(ecPosition.z);\n"
104     "  float fract = smoothstep(0.0, cloud_height, gl_Position.z + cloud_height);\n"
105 // Final position of the sprite
106     "  gl_Position = gl_ModelViewProjectionMatrix * gl_Position;\n"
107 // Determine the shading of the sprite based on its vertical position and position relative to the sun.
108     "  n = min(smoothstep(-0.5, 0.0, n), fract);\n"
109 // Determine the shading based on a mixture from the backlight to the front
110     "  vec4 backlight = gl_LightSource[0].diffuse * shade;\n"
111     "  gl_FrontColor = mix(backlight, gl_LightSource[0].diffuse, n);\n"
112     "  gl_FrontColor += gl_FrontLightModelProduct.sceneColor;\n"
113 // As we get within 100m of the sprite, it is faded out. Equally at large distances it also fades out.
114     "  gl_FrontColor.a = min(smoothstep(10.0, 100.0, fogCoord), 1 - smoothstep(15000.0, 20000.0, fogCoord));\n"
115     "  gl_BackColor = gl_FrontColor;\n"
116 // Fog doesn't affect clouds as much as other objects.        
117     "  fogFactor = exp( -gl_Fog.density * fogCoord * 0.5);\n"
118     "  fogFactor = clamp(fogFactor, 0.0, 1.0);\n"
119     "}\n";
120
121 static char fragmentShaderSource[] = 
122     "uniform sampler2D baseTexture; \n"
123     "varying float fogFactor;\n"
124     "\n"
125     "void main(void)\n"
126     "{\n"
127     "  vec4 base = texture2D( baseTexture, gl_TexCoord[0].st);\n"
128     "  vec4 finalColor = base * gl_Color;\n"
129     "  gl_FragColor.rgb = mix(gl_Fog.color.rgb, finalColor.rgb, fogFactor );\n"
130     "  gl_FragColor.a = mix(0.0, finalColor.a, fogFactor);\n"
131     "}\n";
132
133 SGNewCloud::SGNewCloud(string type,
134                        const SGPath &tex_path, 
135                        string tex,
136                        double min_w,
137                        double max_w,
138                        double min_h,
139                        double max_h,
140                        double min_sprite_w,
141                        double max_sprite_w,
142                        double min_sprite_h,
143                        double max_sprite_h,
144                        double b,
145                        int n,
146                        int nt_x,
147                        int nt_y) :
148         min_width(min_w),
149         max_width(max_w),
150         min_height(min_h),
151         max_height(max_h),
152         min_sprite_width(min_sprite_w),
153         max_sprite_width(max_sprite_w),
154         min_sprite_height(min_sprite_h),
155         max_sprite_height(max_sprite_h),
156         bottom_shade(b),
157         num_sprites(n),
158         num_textures_x(nt_x),
159         num_textures_y(nt_y),
160         texture(tex),
161         name(type)
162 {
163     // Create a new StateSet for the texture, if required.
164     StateSetMap::iterator iter = SGCloudField::cloudTextureMap.find(texture);
165
166     if (iter == SGCloudField::cloudTextureMap.end()) {
167         stateSet = new osg::StateSet;
168                 
169         osg::ref_ptr<osgDB::ReaderWriter::Options> options = makeOptionsFromPath(tex_path);
170                 
171         osg::Texture2D *tex = new osg::Texture2D;
172         tex->setWrap( osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP );
173         tex->setWrap( osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP );
174         tex->setImage(osgDB::readImageFile(texture, options.get()));
175                 
176         StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
177         
178         stateSet->setMode(GL_LIGHTING,  osg::StateAttribute::ON);
179         stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
180         
181         // Fog handling
182         stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
183         stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
184
185         stateSet->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON );
186         stateSet->setRenderBinDetails(osg::StateSet::TRANSPARENT_BIN, "DepthSortedBin");
187         // Turn off z buffer writes. Standard hack for
188         // semi-transparent geometry to avoid sorting / flickering
189         // artifacts.
190         stateSet->setAttributeAndModes(attribFactory->getDepthWritesDisabled());
191         static ref_ptr<AlphaFunc> alphaFunc;
192         static ref_ptr<Program> program;
193         static ref_ptr<Uniform> baseTextureSampler;
194         static ref_ptr<Material> material;
195                   
196         // Generate the shader etc, if we don't already have one.
197         if (!program.valid()) {
198             alphaFunc = new AlphaFunc;
199             alphaFunc->setFunction(AlphaFunc::GREATER,0.01f);
200             program  = new Program;
201             baseTextureSampler = new osg::Uniform("baseTexture", 0);
202             Shader* vertex_shader = new Shader(Shader::VERTEX, vertexShaderSource);
203             program->addShader(vertex_shader);
204             program->addBindAttribLocation("usrAttr1", CloudShaderGeometry::USR_ATTR_1);
205             program->addBindAttribLocation("usrAttr2", CloudShaderGeometry::USR_ATTR_2);
206             Shader* fragment_shader = new Shader(Shader::FRAGMENT, fragmentShaderSource);
207             program->addShader(fragment_shader);
208             material = new Material;
209             // DonĀ“t track vertex color
210             material->setColorMode(Material::OFF);
211             
212             // We don't actually use the material information either - see shader.
213             material->setAmbient(Material::FRONT_AND_BACK,
214                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
215             material->setDiffuse(Material::FRONT_AND_BACK,
216                                  Vec4(0.5f, 0.5f, 0.5f, 1.0f));
217         }
218                   
219         stateSet->setAttributeAndModes(alphaFunc.get());
220         stateSet->setAttribute(program.get());
221         stateSet->addUniform(baseTextureSampler.get());
222         stateSet->setMode(GL_VERTEX_PROGRAM_TWO_SIDE, StateAttribute::ON);
223         stateSet->setAttribute(material.get());
224                 
225         // Add the newly created texture to the map for use later.
226         SGCloudField::cloudTextureMap.insert(StateSetMap::value_type(texture,  stateSet));
227     } else {
228         stateSet = iter->second.get();
229     }
230     
231     quad = createOrthQuad(min_sprite_width, min_sprite_height, num_textures_x, num_textures_y);
232 }
233
234 SGNewCloud::~SGNewCloud() {
235 }
236
237 osg::Geometry* SGNewCloud::createOrthQuad(float w, float h, int varieties_x, int varieties_y)
238 {
239     // Create front and back polygons so we don't need to screw around
240     // with two-sided lighting in the shader.
241     osg::Vec3Array& v = *(new osg::Vec3Array(4));
242     osg::Vec3Array& n = *(new osg::Vec3Array(4));
243     osg::Vec2Array& t = *(new osg::Vec2Array(4));
244     
245     float cw = w*0.5f;
246
247     v[0].set(0.0f, -cw, 0.0f);
248     v[1].set(0.0f,  cw, 0.0f);
249     v[2].set(0.0f,  cw, h);
250     v[3].set(0.0f, -cw, h);
251     
252     // The texture coordinate range is not the
253     // entire coordinate space - as the texture
254     // has a number of different clouds on it.
255     float tx = 1.0f/varieties_x;
256     float ty = 1.0f/varieties_y;
257
258     t[0].set(0.0f, 0.0f);
259     t[1].set(  tx, 0.0f);
260     t[2].set(  tx, ty);
261     t[3].set(0.0f, ty);
262
263     // The normal isn't actually use in lighting.
264     n[0].set(1.0f, -1.0f, -1.0f);
265     n[1].set(1.0f,  1.0f, -1.0f);
266     n[2].set(1.0f,  1.0f,  1.0f);
267     n[3].set(1.0f, -1.0f,  1.0f);
268
269     osg::Geometry *geom = new osg::Geometry;
270
271     geom->setVertexArray(&v);
272     geom->setTexCoordArray(0, &t);
273     geom->setNormalArray(&n);
274     geom->setNormalBinding(Geometry::BIND_PER_VERTEX);
275     // No color for now; that's used to pass the position.
276     geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,4));
277
278     return geom;
279 }
280
281 #if 0
282 // return a random number between -n/2 and n/2, tending to 0
283 static float Rnd(float n) {
284     return n * (-0.5f + (sg_random() + sg_random()) / 2.0f);
285 }
286 #endif
287
288 osg::ref_ptr<Geode> SGNewCloud::genCloud() {
289     
290     osg::ref_ptr<osg::Geode> geode = new Geode;
291         
292     CloudShaderGeometry* sg = new CloudShaderGeometry(num_textures_x, num_textures_y, max_width, max_height);
293     
294     // Determine how big this specific cloud instance is. Note that we subtract
295     // the sprite size because the width/height is used to define the limits of
296     // the center of the sprites, not their edges.
297     float width = min_width + sg_random() * (max_width - min_width) - min_sprite_width;
298     float height = min_height + sg_random() * (max_height - min_height) - min_sprite_height;
299     
300     // Determine the cull distance. This is used to remove sprites that are too close together.
301     // The value is squared as we use vector calculations.
302     float cull_distance_squared = min_sprite_height * min_sprite_height * 0.1f;
303     
304     // The number of sprites we actually use is a function of the (user-controlled) density
305     int n_sprites = num_sprites * sprite_density * (0.5 + sg_random());
306     
307     for (int i = 0; i < n_sprites; i++)
308     {
309         // Determine the position of the sprite. Rather than being completely random,
310         // we place them on the surface of a distorted sphere. However, we place
311         // the first sprite in the center of the sphere (and at maximum size) to
312         // ensure good coverage and reduce the chance of there being "holes" in our
313
314         float x, y, z;
315
316         if (i == 0) {
317             x = 0;
318             y = 0;
319             z = 0;
320         } else {
321             double theta = sg_random() * SGD_2PI;
322             double elev  = sg_random() * SGD_PI;
323             x = width * cos(theta) * 0.5f * sin(elev);
324             y = width * sin(theta) * 0.5f * sin(elev);
325             z = height * cos(elev) * 0.5f;
326         }
327         
328         SGVec3f *pos = new SGVec3f(x, y, z); 
329
330         // Determine the height and width as scaling factors on the minimum size (used to create the quad).
331         float sprite_width = 1.0f + sg_random() * (max_sprite_width - min_sprite_width) / min_sprite_width;
332         float sprite_height = 1.0f + sg_random() * (max_sprite_height - min_sprite_height) / min_sprite_height;
333
334         // Sprites are never taller than square.
335         if (sprite_height * min_sprite_height > sprite_width * min_sprite_width)
336         {
337             sprite_height = sprite_width * min_sprite_width / min_sprite_height;
338         }
339
340         if (i == 0) {
341             // The center sprite is always maximum size to fill up any holes.
342             sprite_width = 1.0f + (max_sprite_width - min_sprite_width) / min_sprite_width;
343             sprite_height = 1.0f + (max_sprite_height - min_sprite_height) / min_sprite_height;
344         }
345
346         // Determine the sprite texture indexes.
347         int index_x = (int) floor(sg_random() * num_textures_x);
348         if (index_x == num_textures_x) { index_x--; }
349
350         // The y index depends on the positing of the sprite within the cloud.
351         // This allows cloud designers to have particular sprites for the base
352         // and tops of the cloud.
353         int index_y = (int) floor((z / height + 0.5f) * num_textures_y);
354         if (index_y == num_textures_y) { index_y--; }
355         
356         sg->addSprite(*pos, 
357                     index_x, 
358                     index_y, 
359                     sprite_width, 
360                     sprite_height, 
361                     bottom_shade, 
362                     cull_distance_squared, 
363                     height * 0.5f);
364     }
365     
366     sg->setGeometry(quad);
367     geode->addDrawable(sg);
368     geode->setName("3D cloud");
369     geode->setStateSet(stateSet.get());
370     
371     return geode;
372 }
373