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