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