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