]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
Render cloud layers with face culling
[simgear.git] / simgear / scene / sky / cloud.cxx
1 // cloud.cxx -- model a single cloud layer
2 //
3 // Written by Curtis Olson, started June 2000.
4 //
5 // Copyright (C) 2000  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
11 //
12 // This library 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 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include <sstream>
30
31 #include <math.h>
32
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/CullFace>
36 #include <osg/Geode>
37 #include <osg/Geometry>
38 #include <osg/Material>
39 #include <osg/ShadeModel>
40 #include <osg/TexEnv>
41 #include <osg/TexEnvCombine>
42 #include <osg/Texture2D>
43 #include <osg/TextureCubeMap>
44 #include <osg/TexMat>
45 #include <osg/Fog>
46
47 #include <simgear/math/sg_random.h>
48 #include <simgear/misc/PathOptions.hxx>
49 #include <simgear/debug/logstream.hxx>
50 #include <simgear/scene/model/model.hxx>
51 #include <simgear/scene/util/RenderConstants.hxx>
52 #include <simgear/scene/util/StateAttributeFactory.hxx>
53 #include <simgear/math/polar3d.hxx>
54
55 #include "newcloud.hxx"
56 #include "cloudfield.hxx"
57 #include "cloud.hxx"
58
59 using namespace simgear;
60 using namespace osg;
61
62 #if defined(__MINGW32__)
63 #define isnan(x) _isnan(x)
64 #endif
65
66 // #if defined (__FreeBSD__)
67 // #  if __FreeBSD_version < 500000
68 //      extern "C" {
69 //        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
70 //      }
71 // #  endif
72 // #endif
73
74 #if defined (__CYGWIN__)
75 #include <ieeefp.h>
76 #endif
77
78 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
79 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
80 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
81 static bool state_initialized = false;
82 static bool bump_mapping = false;
83
84 bool SGCloudLayer::enable_bump_mapping = false;
85
86 // make an StateSet for a cloud layer given the named texture
87 static osg::StateSet*
88 SGMakeState(const SGPath &path, const char* colorTexture,
89             const char* normalTexture)
90 {
91     osg::StateSet *stateSet = new osg::StateSet;
92
93     osg::ref_ptr<osgDB::ReaderWriter::Options> options
94         = makeOptionsFromPath(path);
95     stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
96                                                      options.get()));
97     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
98     StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
99     stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
100     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
101     stateSet->setAttributeAndModes(attribFactory->getStandardAlphaFunc());
102     stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
103
104 //     osg::Material* material = new osg::Material;
105 //     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
106 //     material->setEmission(osg::Material::FRONT_AND_BACK,
107 //                           osg::Vec4(0.05, 0.05, 0.05, 0));
108 //     material->setSpecular(osg::Material::FRONT_AND_BACK,
109 //                           osg::Vec4(0, 0, 0, 1));
110 //     stateSet->setAttribute(material);
111
112     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
113
114     // OSGFIXME: invented by me ...
115 //     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
116 //     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
117
118 //     stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
119
120     // If the normal texture is given prepare a bumpmapping enabled state
121 //     if (normalTexture) {
122 //       SGPath normalPath(path);
123 //       normalPath.append(normalTexture);
124 //       stateSet->setTextureAttribute(2, SGLoadTexture2D(normalPath));
125 //       stateSet->setTextureMode(2, GL_TEXTURE_2D, osg::StateAttribute::ON);
126 //     }
127
128     return stateSet;
129 }
130
131 // Constructor
132 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
133     cloud_root(new osg::Switch),
134     layer_root(new osg::Switch),
135     group_top(new osg::Group),
136     group_bottom(new osg::Group),
137     layer_transform(new osg::MatrixTransform),
138     cloud_alpha(1.0),
139     texture_path(tex_path),
140     layer_span(0.0),
141     layer_asl(0.0),
142     layer_thickness(0.0),
143     layer_transition(0.0),
144     layer_coverage(SG_CLOUD_CLEAR),
145     scale(4000.0),
146     speed(0.0),
147     direction(0.0),
148     last_lon(0.0),
149     last_lat(0.0)
150 {
151     // XXX
152     // Render bottoms before the rest of transparent objects (rendered
153     // in bin 10), tops after. The negative numbers on the bottoms
154     // RenderBins and the positive numbers on the tops enforce this
155     // order.
156   cloud_root->addChild(layer_root.get(), true);
157   layer_root->addChild(group_bottom.get());
158   layer_root->addChild(group_top.get());
159   osg::StateSet *rootSet = layer_root->getOrCreateStateSet();
160   rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
161   rootSet->setTextureAttribute(0, new osg::TexMat);
162   rootSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
163   // Combiner for fog color and cloud alpha
164   osg::TexEnvCombine* combine0 = new osg::TexEnvCombine;
165   osg::TexEnvCombine* combine1 = new osg::TexEnvCombine;
166   combine0->setCombine_RGB(osg::TexEnvCombine::MODULATE);
167   combine0->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
168   combine0->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
169   combine0->setSource1_RGB(osg::TexEnvCombine::TEXTURE0);
170   combine0->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
171   combine0->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
172   combine0->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
173   combine0->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
174   combine0->setSource1_Alpha(osg::TexEnvCombine::TEXTURE0);
175   combine0->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
176
177   combine1->setCombine_RGB(osg::TexEnvCombine::MODULATE);
178   combine1->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
179   combine1->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
180   combine1->setSource1_RGB(osg::TexEnvCombine::CONSTANT);
181   combine1->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
182   combine1->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
183   combine1->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
184   combine1->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
185   combine1->setSource1_Alpha(osg::TexEnvCombine::CONSTANT);
186   combine1->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
187   combine1->setDataVariance(osg::Object::DYNAMIC);
188   rootSet->setTextureAttributeAndModes(0, combine0);
189   rootSet->setTextureAttributeAndModes(1, combine1);
190   rootSet->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON);
191   rootSet->setTextureAttributeAndModes(1, StateAttributeFactory::instance()
192                                        ->getWhiteTexture(),
193                                        osg::StateAttribute::ON);
194   rootSet->setDataVariance(osg::Object::DYNAMIC);
195
196   base = osg::Vec2(sg_random(), sg_random());
197   group_top->addChild(layer_transform.get());
198   group_bottom->addChild(layer_transform.get());
199
200   layer3D = new SGCloudField();
201   cloud_root->addChild(layer3D->getNode(), false);
202
203   rebuild();
204 }
205
206 // Destructor
207 SGCloudLayer::~SGCloudLayer()
208 {
209   delete layer3D;
210 }
211
212 float
213 SGCloudLayer::getSpan_m () const
214 {
215     return layer_span;
216 }
217
218 void
219 SGCloudLayer::setSpan_m (float span_m)
220 {
221     if (span_m != layer_span) {
222         layer_span = span_m;
223         rebuild();
224     }
225 }
226
227 float
228 SGCloudLayer::getElevation_m () const
229 {
230     return layer_asl;
231 }
232
233 void
234 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
235 {
236     layer_asl = elevation_m;
237
238     if (set_span) {
239         if (elevation_m > 4000)
240             setSpan_m(  elevation_m * 10 );
241         else
242             setSpan_m( 40000 );
243     }
244 }
245
246 float
247 SGCloudLayer::getThickness_m () const
248 {
249     return layer_thickness;
250 }
251
252 void
253 SGCloudLayer::setThickness_m (float thickness_m)
254 {
255     layer_thickness = thickness_m;
256 }
257
258 float
259 SGCloudLayer::getTransition_m () const
260 {
261     return layer_transition;
262 }
263
264 void
265 SGCloudLayer::setTransition_m (float transition_m)
266 {
267     layer_transition = transition_m;
268 }
269
270 SGCloudLayer::Coverage
271 SGCloudLayer::getCoverage () const
272 {
273     return layer_coverage;
274 }
275
276 void
277 SGCloudLayer::setCoverage (Coverage coverage)
278 {
279     if (coverage != layer_coverage) {
280         layer_coverage = coverage;
281         rebuild();
282         
283         double coverage_norm = 0.0;
284         if( coverage ==  SG_CLOUD_FEW)
285             coverage_norm = 2.0/8.0;    // <1-2
286         else if( coverage == SG_CLOUD_SCATTERED )
287             coverage_norm = 4.0/8.0;    // 3-4
288         else if( coverage == SG_CLOUD_BROKEN )
289             coverage_norm = 6.0/8.0;    // 5-7
290         else if( coverage == SG_CLOUD_OVERCAST )
291             coverage_norm = 8.0/8.0;    // 8
292         
293         layer3D->setCoverage(coverage_norm);
294         layer3D->applyCoverage();
295     }
296 }
297
298 void
299 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
300 {
301     osg::StateAttribute* attr = layer_root->getStateSet()
302         ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
303     osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
304     if (!texMat)
305         return;
306     texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
307 }
308
309 // colors for debugging the cloud layers
310 #ifdef CLOUD_DEBUG
311 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 0.0f, 0.0f),
312                       Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 0.0f, 1.0f)};
313 #else
314 Vec3 cloudColors[] = {Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f),
315                       Vec3(1.0f, 1.0f, 1.0f), Vec3(1.0f, 1.0f, 1.0f)};
316 #endif
317
318 // build the cloud object
319 void
320 SGCloudLayer::rebuild()
321 {
322     // Initialize states and sizes if necessary.
323     if ( !state_initialized ) { 
324         state_initialized = true;
325
326         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
327
328         osg::Texture::Extensions* extensions;
329         extensions = osg::Texture::getExtensions(0, true);
330         // OSGFIXME
331         bump_mapping = extensions->isMultiTexturingSupported() &&
332           (2 <= extensions->numTextureUnits()) &&
333           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
334           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
335
336         osg::TextureCubeMap::Extensions* extensions2;
337         extensions2 = osg::TextureCubeMap::getExtensions(0, true);
338         bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
339
340         // This bump mapping code was inspired by the tutorial available at 
341         // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
342         // and a NVidia white paper 
343         //  http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
344         // The normal map textures were generated by the normal map Gimp plugin :
345         //  http://nifelheim.dyndns.org/~cocidius/normalmap/
346         //
347         cubeMap = new osg::TextureCubeMap;
348         cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
349         cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
350         cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
351         cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
352         cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
353
354         const int size = 32;
355         const float half_size = 16.0f;
356         const float offset = 0.5f;
357         osg::Vec3 zero_normal(0.5, 0.5, 0.5);
358
359         osg::Image* image = new osg::Image;
360         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
361         unsigned char *ptr = image->data(0, 0);
362         for (int j = 0; j < size; j++ ) {
363           for (int i = 0; i < size; i++ ) {
364             osg::Vec3 tmp(half_size, -( j + offset - half_size ),
365                           -( i + offset - half_size ) );
366             tmp.normalize();
367             tmp = tmp*0.5 - zero_normal;
368             
369             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
370             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
371             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
372           }
373         }
374         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
375
376         image = new osg::Image;
377         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
378         ptr = image->data(0, 0);
379         for (int j = 0; j < size; j++ ) {
380           for (int i = 0; i < size; i++ ) {
381             osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
382                           ( i + offset - half_size ) );
383             tmp.normalize();
384             tmp = tmp*0.5 - zero_normal;
385             
386             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
387             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
388             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
389           }
390         }
391         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
392
393         image = new osg::Image;
394         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
395         ptr = image->data(0, 0);
396         for (int j = 0; j < size; j++ ) {
397           for (int i = 0; i < size; i++ ) {
398             osg::Vec3 tmp(( i + offset - half_size ), half_size,
399                           ( j + offset - half_size ) );
400             tmp.normalize();
401             tmp = tmp*0.5 - zero_normal;
402             
403             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
404             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
405             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
406           }
407         }
408         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
409
410         image = new osg::Image;
411         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
412         ptr = image->data(0, 0);
413         for (int j = 0; j < size; j++ ) {
414           for (int i = 0; i < size; i++ ) {
415             osg::Vec3 tmp(( i + offset - half_size ), -half_size,
416                           -( j + offset - half_size ) );
417             tmp.normalize();
418             tmp = tmp*0.5 - zero_normal;
419
420             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
421             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
422             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
423           }
424         }
425         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
426
427         image = new osg::Image;
428         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
429         ptr = image->data(0, 0);
430         for (int j = 0; j < size; j++ ) {
431           for (int i = 0; i < size; i++ ) {
432             osg::Vec3 tmp(( i + offset - half_size ),
433                           -( j + offset - half_size ), half_size );
434             tmp.normalize();
435             tmp = tmp*0.5 - zero_normal;
436             
437             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
438             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
439             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
440           }
441         }
442         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
443
444         image = new osg::Image;
445         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
446         ptr = image->data(0, 0);
447         for (int j = 0; j < size; j++ ) {
448           for (int i = 0; i < size; i++ ) {
449             osg::Vec3 tmp(-( i + offset - half_size ),
450                           -( j + offset - half_size ), -half_size );
451             tmp.normalize();
452             tmp = tmp*0.5 - zero_normal;
453             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
454             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
455             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
456           }
457         }
458         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
459
460         osg::StateSet* state;
461         state = SGMakeState(texture_path, "overcast.png", "overcast_n.png");
462         layer_states[SG_CLOUD_OVERCAST] = state;
463         state = SGMakeState(texture_path, "overcast_top.png", "overcast_top_n.png");
464         layer_states2[SG_CLOUD_OVERCAST] = state;
465         
466         state = SGMakeState(texture_path, "broken.png", "broken_n.png");
467         layer_states[SG_CLOUD_BROKEN] = state;
468         layer_states2[SG_CLOUD_BROKEN] = state;
469         
470         state = SGMakeState(texture_path, "scattered.png", "scattered_n.png");
471         layer_states[SG_CLOUD_SCATTERED] = state;
472         layer_states2[SG_CLOUD_SCATTERED] = state;
473         
474         state = SGMakeState(texture_path, "few.png", "few_n.png");
475         layer_states[SG_CLOUD_FEW] = state;
476         layer_states2[SG_CLOUD_FEW] = state;
477         
478         state = SGMakeState(texture_path, "cirrus.png", "cirrus_n.png");
479         layer_states[SG_CLOUD_CIRRUS] = state;
480         layer_states2[SG_CLOUD_CIRRUS] = state;
481         
482         layer_states[SG_CLOUD_CLEAR] = 0;
483         layer_states2[SG_CLOUD_CLEAR] = 0;
484         osg::CopyOp copyOp;
485         for (int i = 0; i < SG_MAX_CLOUD_COVERAGES; ++i) {
486             StateAttributeFactory *saf = StateAttributeFactory::instance();
487             if (layer_states[i].valid()) {
488                 if (layer_states[i] == layer_states2[i])
489                     layer_states2[i] = static_cast<osg::StateSet*>(layer_states[i]->clone(copyOp));
490                 layer_states[i]->setAttribute(saf ->getCullFaceFront());
491                 layer_states2[i]->setAttribute(saf ->getCullFaceBack());
492             }
493         }
494       // OSGFIXME
495 //              SGNewCloud::loadTextures(texture_path.str());
496 //              layer3D->buildTestLayer();
497     }
498
499     scale = 4000.0;
500     last_lon = last_lat = -999.0f;
501
502     setTextureOffset(base);
503     // build the cloud layer
504     const float layer_scale = layer_span / scale;
505     const float mpi = SG_PI/4;
506     
507     // caclculate the difference between a flat-earth model and 
508     // a round earth model given the span and altutude ASL of
509     // the cloud layer. This is the difference in altitude between
510     // the top of the inverted bowl and the edge of the bowl.
511     // const float alt_diff = layer_asl * 0.8;
512     const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
513     const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
514     const float border_to_core = layer_to_core * cos(layer_angle);
515     const float alt_diff = layer_to_core - border_to_core;
516     
517     for (int i = 0; i < 4; i++) {
518       if ( layer[i] != NULL ) {
519         layer_transform->removeChild(layer[i].get()); // automatic delete
520       }
521       
522       vl[i] = new osg::Vec3Array;
523       cl[i] = new osg::Vec4Array;
524       tl[i] = new osg::Vec2Array;
525       
526       
527       osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
528                        alt_diff * (sin(i*mpi) - 2));
529       osg::Vec2 tc(layer_scale * i/4, 0.0f);
530       osg::Vec4 color(cloudColors[0], (i == 0) ? 0.0f : 0.15f);
531       
532       cl[i]->push_back(color);
533       vl[i]->push_back(vertex);
534       tl[i]->push_back(tc);
535       
536       for (int j = 0; j < 4; j++) {
537         vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
538                            alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
539         tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
540         color = osg::Vec4(cloudColors[0],
541                           ( (j == 0) || (i == 3)) ?  
542                           ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
543         
544         cl[i]->push_back(color);
545         vl[i]->push_back(vertex);
546         tl[i]->push_back(tc);
547         
548         vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
549                            alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
550         tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
551         color = osg::Vec4(cloudColors[0],
552                           ((j == 3) || (i == 0)) ?
553                           ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
554         cl[i]->push_back(color);
555         vl[i]->push_back(vertex);
556         tl[i]->push_back(tc);
557       }
558       
559       vertex = osg::Vec3(layer_span*(i-1)/2, layer_span, 
560                          alt_diff * (sin((i+1)*mpi) - 2));
561       
562       tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
563       
564       color = osg::Vec4(cloudColors[0], (i == 3) ? 0.0f : 0.15f );
565       
566       cl[i]->push_back( color );
567       vl[i]->push_back( vertex );
568       tl[i]->push_back( tc );
569       
570       osg::Geometry* geometry = new osg::Geometry;
571       geometry->setUseDisplayList(false);
572       geometry->setVertexArray(vl[i].get());
573       geometry->setNormalBinding(osg::Geometry::BIND_OFF);
574       geometry->setColorArray(cl[i].get());
575       geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
576       geometry->setTexCoordArray(0, tl[i].get());
577       geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
578       layer[i] = new osg::Geode;
579       
580       std::stringstream sstr;
581       sstr << "Cloud Layer (" << i << ")";
582       geometry->setName(sstr.str());
583       layer[i]->setName(sstr.str());
584       layer[i]->addDrawable(geometry);
585       layer_transform->addChild(layer[i].get());
586     }
587     
588     //OSGFIXME: true
589     if ( layer_states[layer_coverage].valid() ) {
590       osg::CopyOp copyOp;    // shallow copy
591       // render bin will be set in reposition
592       osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
593       stateSet->setDataVariance(osg::Object::DYNAMIC);
594       group_top->setStateSet(stateSet);
595       stateSet = static_cast<osg::StateSet*>(layer_states[layer_coverage]->clone(copyOp));
596       stateSet->setDataVariance(osg::Object::DYNAMIC);
597       group_bottom->setStateSet(stateSet);
598     }
599 }
600
601 // repaint the cloud layer colors
602 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
603     osg::Vec4f combineColor(fog_color.osg(), cloud_alpha);
604     osg::TexEnvCombine* combiner
605         = dynamic_cast<osg::TexEnvCombine*>(layer_root->getStateSet()
606                                             ->getTextureAttribute(1, osg::StateAttribute::TEXENV));
607     combiner->setConstantColor(combineColor);
608
609     // Set the fog color for the 3D clouds too.
610     //cloud3dfog->setColor(combineColor);
611     return true;
612 }
613
614 // reposition the cloud layer at the specified origin and orientation
615 // lon specifies a rotation about the Z axis
616 // lat specifies a rotation about the new Y axis
617 // spin specifies a rotation about the new Z axis (and orients the
618 // sunrise/set effects
619 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
620                                double alt, double dt )
621 {
622     // combine p and asl (meters) to get translation offset
623     osg::Vec3 asl_offset(up.osg());
624     asl_offset.normalize();
625     if ( alt <= layer_asl ) {
626         asl_offset *= layer_asl;
627     } else {
628         asl_offset *= layer_asl + layer_thickness;
629     }
630
631     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
632     //      << "," << asl_offset[2] << endl;
633     asl_offset += p.osg();
634     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
635     //      << "," << asl_offset[2] << endl;
636
637     osg::Matrix T, LON, LAT;
638     // Translate to zero elevation
639     // Point3D zero_elev = current_view.get_cur_zero_elev();
640     T.makeTranslate( asl_offset );
641
642     // printf("  Translated to %.2f %.2f %.2f\n", 
643     //        zero_elev.x, zero_elev.y, zero_elev.z );
644
645     // Rotate to proper orientation
646     // printf("  lon = %.2f  lat = %.2f\n", 
647     //        lon * SGD_RADIANS_TO_DEGREES,
648     //        lat * SGD_RADIANS_TO_DEGREES);
649     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
650
651     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
652     //             0.0, 1.0, 0.0 );
653     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
654
655     layer_transform->setMatrix( LAT*LON*T );
656
657     // The layers need to be drawn in order because they are
658     // translucent, but OSG transparency sorting doesn't work because
659     // the cloud polys are huge. However, the ordering is simple: the
660     // bottom polys should be drawn from high altitude to low, and the
661     // top polygons from low to high. The altitude can be used
662     // directly to order the polygons!
663     group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
664                                                      "RenderBin");
665     group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
666                                                   "RenderBin");
667     if ( alt <= layer_asl ) {
668       layer_root->setSingleChildOn(0);
669     } else if ( alt >= layer_asl + layer_thickness ) {
670       layer_root->setSingleChildOn(1);
671     } else {
672       layer_root->setAllChildrenOff();
673     }
674         
675
676     // now calculate update texture coordinates
677     if ( last_lon < -900 ) {
678         last_lon = lon;
679         last_lat = lat;
680     }
681
682     double sp_dist = speed*dt;
683
684     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
685         Point3D start( last_lon, last_lat, 0.0 );
686         Point3D dest( lon, lat, 0.0 );
687         double course = 0.0, dist = 0.0;
688
689         calc_gc_course_dist( dest, start, &course, &dist );
690         // cout << "course = " << course << ", dist = " << dist << endl;
691
692         // if start and dest are too close together,
693         // calc_gc_course_dist() can return a course of "nan".  If
694         // this happens, lets just use the last known good course.
695         // This is a hack, and it would probably be better to make
696         // calc_gc_course_dist() more robust.
697         if ( isnan(course) ) {
698             course = last_course;
699         } else {
700             last_course = course;
701         }
702
703         // calculate cloud movement due to external forces
704         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
705
706         if (dist > 0.0) {
707             ax = cos(course) * dist;
708             ay = sin(course) * dist;
709         }
710
711         if (sp_dist > 0) {
712             bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
713             by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
714         }
715
716
717         double xoff = (ax + bx) / (2 * scale);
718         double yoff = (ay + by) / (2 * scale);
719
720         const float layer_scale = layer_span / scale;
721
722         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
723         base[0] += xoff;
724
725         // the while loops can lead to *long* pauses if base[0] comes
726         // with a bogus value.
727         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
728         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
729         if ( base[0] > -10.0 && base[0] < 10.0 ) {
730             base[0] -= (int)base[0];
731         } else {
732             SG_LOG(SG_ASTRO, SG_DEBUG,
733                 "Error: base = " << base[0] << "," << base[1] <<
734                 " course = " << course << " dist = " << dist );
735             base[0] = 0.0;
736         }
737
738         base[1] += yoff;
739         // the while loops can lead to *long* pauses if base[0] comes
740         // with a bogus value.
741         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
742         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
743         if ( base[1] > -10.0 && base[1] < 10.0 ) {
744             base[1] -= (int)base[1];
745         } else {
746             SG_LOG(SG_ASTRO, SG_DEBUG,
747                     "Error: base = " << base[0] << "," << base[1] <<
748                     " course = " << course << " dist = " << dist );
749             base[1] = 0.0;
750         }
751
752         // cout << "base = " << base[0] << "," << base[1] << endl;
753
754         setTextureOffset(base);
755         last_lon = lon;
756         last_lat = lat;
757     }
758
759     layer3D->reposition( p, up, lon, lat, dt, layer_asl);
760     return true;
761 }
762
763 void SGCloudLayer::set_enable3dClouds(bool enable) {
764      
765     if (layer3D->defined3D && enable) {
766         cloud_root->setChildValue(layer3D->getNode(), true);
767         cloud_root->setChildValue(layer_root.get(),   false);
768     } else {
769         cloud_root->setChildValue(layer3D->getNode(), false);
770         cloud_root->setChildValue(layer_root.get(),   true);
771     }
772 }