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