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