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