]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
4a8c1aea3b0279e2b1cf1117b51e98d152e27839
[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
45 #include <simgear/math/sg_random.h>
46 #include <simgear/misc/PathOptions.hxx>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/scene/model/model.hxx>
49 #include <simgear/scene/util/RenderConstants.hxx>
50 #include <simgear/scene/util/StateAttributeFactory.hxx>
51 #include <simgear/math/polar3d.hxx>
52
53 #include "newcloud.hxx"
54 #include "cloudfield.hxx"
55 #include "cloud.hxx"
56
57 using namespace simgear;
58 #if defined(__MINGW32__)
59 #define isnan(x) _isnan(x)
60 #endif
61
62 // #if defined (__FreeBSD__)
63 // #  if __FreeBSD_version < 500000
64 //      extern "C" {
65 //        inline int isnan(double r) { return !(r <= 0 || r >= 0); }
66 //      }
67 // #  endif
68 // #endif
69
70 #if defined (__CYGWIN__)
71 #include <ieeefp.h>
72 #endif
73
74 static osg::ref_ptr<osg::StateSet> layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
75 static osg::ref_ptr<osg::StateSet> layer_states2[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
76 static osg::ref_ptr<osg::TextureCubeMap> cubeMap;
77 static bool state_initialized = false;
78 static bool bump_mapping = false;
79
80 bool SGCloudLayer::enable_bump_mapping = false;
81
82 // make an StateSet for a cloud layer given the named texture
83 static osg::StateSet*
84 SGMakeState(const SGPath &path, const char* colorTexture,
85             const char* normalTexture)
86 {
87     osg::StateSet *stateSet = new osg::StateSet;
88
89     osg::ref_ptr<osgDB::ReaderWriter::Options> options
90         = makeOptionsFromPath(path);
91     stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
92                                                      options.get()));
93     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
94     StateAttributeFactory* attribFactory = StateAttributeFactory::instance();
95     stateSet->setAttributeAndModes(attribFactory->getSmoothShadeModel());
96     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
97     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
98     stateSet->setAttributeAndModes(attribFactory->getStandardAlphaFunc());
99     stateSet->setAttributeAndModes(attribFactory->getStandardBlendFunc());
100
101 //     osg::Material* material = new osg::Material;
102 //     material->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
103 //     material->setEmission(osg::Material::FRONT_AND_BACK,
104 //                           osg::Vec4(0.05, 0.05, 0.05, 0));
105 //     material->setSpecular(osg::Material::FRONT_AND_BACK,
106 //                           osg::Vec4(0, 0, 0, 1));
107 //     stateSet->setAttribute(material);
108
109     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
110
111     // OSGFIXME: invented by me ...
112 //     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
113 //     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
114
115 //     stateSet->setMode(GL_LIGHT0, osg::StateAttribute::OFF);
116
117     // If the normal texture is given prepare a bumpmapping enabled state
118 //     if (normalTexture) {
119 //       SGPath normalPath(path);
120 //       normalPath.append(normalTexture);
121 //       stateSet->setTextureAttribute(2, SGLoadTexture2D(normalPath));
122 //       stateSet->setTextureMode(2, GL_TEXTURE_2D, osg::StateAttribute::ON);
123 //     }
124
125     return stateSet;
126 }
127
128 // Constructor
129 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
130     layer_root(new osg::Switch),
131     group_top(new osg::Group),
132     group_bottom(new osg::Group),
133     layer_transform(new osg::MatrixTransform),
134     cloud_alpha(1.0),
135     texture_path(tex_path),
136     layer_span(0.0),
137     layer_asl(0.0),
138     layer_thickness(0.0),
139     layer_transition(0.0),
140     layer_coverage(SG_CLOUD_CLEAR),
141     scale(4000.0),
142     speed(0.0),
143     direction(0.0),
144     last_lon(0.0),
145     last_lat(0.0)
146 {
147     // XXX
148     // Render bottoms before the rest of transparent objects (rendered
149     // in bin 10), tops after. The negative numbers on the bottoms
150     // RenderBins and the positive numbers on the tops enforce this
151     // order.
152   layer_root->addChild(group_bottom.get());
153   layer_root->addChild(group_top.get());
154   osg::StateSet *rootSet = layer_root->getOrCreateStateSet();
155   rootSet->setRenderBinDetails(CLOUDS_BIN, "DepthSortedBin");
156   rootSet->setTextureAttribute(0, new osg::TexMat);
157   // Combiner for fog color and cloud alpha
158   osg::TexEnvCombine* combine0 = new osg::TexEnvCombine;
159   osg::TexEnvCombine* combine1 = new osg::TexEnvCombine;
160   combine0->setCombine_RGB(osg::TexEnvCombine::MODULATE);
161   combine0->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
162   combine0->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
163   combine0->setSource1_RGB(osg::TexEnvCombine::TEXTURE0);
164   combine0->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
165   combine0->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
166   combine0->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
167   combine0->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
168   combine0->setSource1_Alpha(osg::TexEnvCombine::TEXTURE0);
169   combine0->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
170
171   combine1->setCombine_RGB(osg::TexEnvCombine::MODULATE);
172   combine1->setSource0_RGB(osg::TexEnvCombine::PREVIOUS);
173   combine1->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
174   combine1->setSource1_RGB(osg::TexEnvCombine::CONSTANT);
175   combine1->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
176   combine1->setCombine_Alpha(osg::TexEnvCombine::MODULATE);
177   combine1->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
178   combine1->setOperand0_Alpha(osg::TexEnvCombine::SRC_ALPHA);
179   combine1->setSource1_Alpha(osg::TexEnvCombine::CONSTANT);
180   combine1->setOperand1_Alpha(osg::TexEnvCombine::SRC_ALPHA);
181   combine1->setDataVariance(osg::Object::DYNAMIC);
182   rootSet->setTextureAttributeAndModes(0, combine0);
183   rootSet->setTextureAttributeAndModes(1, combine1);
184   rootSet->setTextureMode(1, GL_TEXTURE_2D, osg::StateAttribute::ON);
185   rootSet->setTextureAttributeAndModes(1, StateAttributeFactory::instance()
186                                        ->getWhiteTexture(),
187                                        osg::StateAttribute::ON);
188   rootSet->setDataVariance(osg::Object::DYNAMIC);
189
190   base = osg::Vec2(sg_random(), sg_random());
191
192   group_top->addChild(layer_transform.get());
193   group_bottom->addChild(layer_transform.get());
194
195   layer3D = new SGCloudField;
196   rebuild();
197 }
198
199 // Destructor
200 SGCloudLayer::~SGCloudLayer()
201 {
202   delete layer3D;
203 }
204
205 float
206 SGCloudLayer::getSpan_m () const
207 {
208     return layer_span;
209 }
210
211 void
212 SGCloudLayer::setSpan_m (float span_m)
213 {
214     if (span_m != layer_span) {
215         layer_span = span_m;
216         rebuild();
217     }
218 }
219
220 float
221 SGCloudLayer::getElevation_m () const
222 {
223     return layer_asl;
224 }
225
226 void
227 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
228 {
229     layer_asl = elevation_m;
230
231     if (set_span) {
232         if (elevation_m > 4000)
233             setSpan_m(  elevation_m * 10 );
234         else
235             setSpan_m( 40000 );
236     }
237 }
238
239 float
240 SGCloudLayer::getThickness_m () const
241 {
242     return layer_thickness;
243 }
244
245 void
246 SGCloudLayer::setThickness_m (float thickness_m)
247 {
248     layer_thickness = thickness_m;
249 }
250
251 float
252 SGCloudLayer::getTransition_m () const
253 {
254     return layer_transition;
255 }
256
257 void
258 SGCloudLayer::setTransition_m (float transition_m)
259 {
260     layer_transition = transition_m;
261 }
262
263 SGCloudLayer::Coverage
264 SGCloudLayer::getCoverage () const
265 {
266     return layer_coverage;
267 }
268
269 void
270 SGCloudLayer::setCoverage (Coverage coverage)
271 {
272     if (coverage != layer_coverage) {
273         layer_coverage = coverage;
274         rebuild();
275     }
276 }
277
278 void
279 SGCloudLayer::setTextureOffset(const osg::Vec2& offset)
280 {
281     osg::StateAttribute* attr = layer_root->getStateSet()
282         ->getTextureAttribute(0, osg::StateAttribute::TEXMAT);
283     osg::TexMat* texMat = dynamic_cast<osg::TexMat*>(attr);
284     if (!texMat)
285         return;
286     texMat->setMatrix(osg::Matrix::translate(offset[0], offset[1], 0.0));
287 }
288
289 // build the cloud object
290 void
291 SGCloudLayer::rebuild()
292 {
293     // Initialize states and sizes if necessary.
294     if ( !state_initialized ) { 
295         state_initialized = true;
296
297         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
298
299         osg::Texture::Extensions* extensions;
300         extensions = osg::Texture::getExtensions(0, true);
301         // OSGFIXME
302         bump_mapping = extensions->isMultiTexturingSupported() &&
303           (2 <= extensions->numTextureUnits()) &&
304           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_combine") &&
305           SGIsOpenGLExtensionSupported("GL_ARB_texture_env_dot3");
306
307         osg::TextureCubeMap::Extensions* extensions2;
308         extensions2 = osg::TextureCubeMap::getExtensions(0, true);
309         bump_mapping = bump_mapping && extensions2->isCubeMapSupported();
310
311         // This bump mapping code was inspired by the tutorial available at 
312         // http://www.paulsprojects.net/tutorials/simplebump/simplebump.html
313         // and a NVidia white paper 
314         //  http://developer.nvidia.com/object/bumpmappingwithregistercombiners.html
315         // The normal map textures were generated by the normal map Gimp plugin :
316         //  http://nifelheim.dyndns.org/~cocidius/normalmap/
317         //
318         cubeMap = new osg::TextureCubeMap;
319         cubeMap->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR);
320         cubeMap->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
321         cubeMap->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
322         cubeMap->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
323         cubeMap->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
324
325         const int size = 32;
326         const float half_size = 16.0f;
327         const float offset = 0.5f;
328         osg::Vec3 zero_normal(0.5, 0.5, 0.5);
329
330         osg::Image* image = new osg::Image;
331         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
332         unsigned char *ptr = image->data(0, 0);
333         for (int j = 0; j < size; j++ ) {
334           for (int i = 0; i < size; i++ ) {
335             osg::Vec3 tmp(half_size, -( j + offset - half_size ),
336                           -( i + offset - half_size ) );
337             tmp.normalize();
338             tmp = tmp*0.5 - zero_normal;
339             
340             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
341             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
342             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
343           }
344         }
345         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_X, image);
346
347         image = new osg::Image;
348         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
349         ptr = image->data(0, 0);
350         for (int j = 0; j < size; j++ ) {
351           for (int i = 0; i < size; i++ ) {
352             osg::Vec3 tmp(-half_size, -( j + offset - half_size ),
353                           ( i + offset - half_size ) );
354             tmp.normalize();
355             tmp = tmp*0.5 - zero_normal;
356             
357             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
358             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
359             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
360           }
361         }
362         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
363
364         image = new osg::Image;
365         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
366         ptr = image->data(0, 0);
367         for (int j = 0; j < size; j++ ) {
368           for (int i = 0; i < size; i++ ) {
369             osg::Vec3 tmp(( i + offset - half_size ), half_size,
370                           ( j + offset - half_size ) );
371             tmp.normalize();
372             tmp = tmp*0.5 - zero_normal;
373             
374             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
375             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
376             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
377           }
378         }
379         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
380
381         image = new osg::Image;
382         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
383         ptr = image->data(0, 0);
384         for (int j = 0; j < size; j++ ) {
385           for (int i = 0; i < size; i++ ) {
386             osg::Vec3 tmp(( i + offset - half_size ), -half_size,
387                           -( j + offset - half_size ) );
388             tmp.normalize();
389             tmp = tmp*0.5 - zero_normal;
390
391             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
392             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
393             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
394           }
395         }
396         cubeMap->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
397
398         image = new osg::Image;
399         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
400         ptr = image->data(0, 0);
401         for (int j = 0; j < size; j++ ) {
402           for (int i = 0; i < size; i++ ) {
403             osg::Vec3 tmp(( i + offset - half_size ),
404                           -( j + offset - half_size ), half_size );
405             tmp.normalize();
406             tmp = tmp*0.5 - zero_normal;
407             
408             *ptr++ = (unsigned char)( tmp[ 0 ] * 255 );
409             *ptr++ = (unsigned char)( tmp[ 1 ] * 255 );
410             *ptr++ = (unsigned char)( tmp[ 2 ] * 255 );
411           }
412         }
413         cubeMap->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
414
415         image = new osg::Image;
416         image->allocateImage(size, size, 1, GL_RGB, GL_UNSIGNED_BYTE);
417         ptr = image->data(0, 0);
418         for (int j = 0; j < size; j++ ) {
419           for (int i = 0; i < size; i++ ) {
420             osg::Vec3 tmp(-( i + offset - half_size ),
421                           -( j + offset - half_size ), -half_size );
422             tmp.normalize();
423             tmp = tmp*0.5 - zero_normal;
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::NEGATIVE_Z, image);
430
431         osg::StateSet* state;
432         state = SGMakeState(texture_path, "overcast.png", "overcast_n.png");
433         layer_states[SG_CLOUD_OVERCAST] = state;
434         state = SGMakeState(texture_path, "overcast_top.png", "overcast_top_n.png");
435         layer_states2[SG_CLOUD_OVERCAST] = state;
436         
437         state = SGMakeState(texture_path, "broken.png", "broken_n.png");
438         layer_states[SG_CLOUD_BROKEN] = state;
439         layer_states2[SG_CLOUD_BROKEN] = state;
440         
441         state = SGMakeState(texture_path, "scattered.png", "scattered_n.png");
442         layer_states[SG_CLOUD_SCATTERED] = state;
443         layer_states2[SG_CLOUD_SCATTERED] = state;
444         
445         state = SGMakeState(texture_path, "few.png", "few_n.png");
446         layer_states[SG_CLOUD_FEW] = state;
447         layer_states2[SG_CLOUD_FEW] = state;
448         
449         state = SGMakeState(texture_path, "cirrus.png", "cirrus_n.png");
450         layer_states[SG_CLOUD_CIRRUS] = state;
451         layer_states2[SG_CLOUD_CIRRUS] = state;
452         
453         layer_states[SG_CLOUD_CLEAR] = 0;
454         layer_states2[SG_CLOUD_CLEAR] = 0;
455
456       // OSGFIXME
457 //              SGNewCloud::loadTextures(texture_path.str());
458 //              layer3D->buildTestLayer();
459     }
460
461     scale = 4000.0;
462     last_lon = last_lat = -999.0f;
463
464     setTextureOffset(base);
465     // build the cloud layer
466     const float layer_scale = layer_span / scale;
467     const float mpi = SG_PI/4;
468     
469     // caclculate the difference between a flat-earth model and 
470     // a round earth model given the span and altutude ASL of
471     // the cloud layer. This is the difference in altitude between
472     // the top of the inverted bowl and the edge of the bowl.
473     // const float alt_diff = layer_asl * 0.8;
474     const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
475     const float layer_angle = 0.5*layer_span / layer_to_core; // The angle is half the span
476     const float border_to_core = layer_to_core * cos(layer_angle);
477     const float alt_diff = layer_to_core - border_to_core;
478     
479     for (int i = 0; i < 4; i++) {
480       if ( layer[i] != NULL ) {
481         layer_transform->removeChild(layer[i].get()); // automatic delete
482       }
483       
484       vl[i] = new osg::Vec3Array;
485       cl[i] = new osg::Vec4Array;
486       tl[i] = new osg::Vec2Array;
487       
488       
489       osg::Vec3 vertex(layer_span*(i-2)/2, -layer_span,
490                        alt_diff * (sin(i*mpi) - 2));
491       osg::Vec2 tc(layer_scale * i/4, 0.0f);
492       osg::Vec4 color(1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f);
493       
494       cl[i]->push_back(color);
495       vl[i]->push_back(vertex);
496       tl[i]->push_back(tc);
497       
498       for (int j = 0; j < 4; j++) {
499         vertex = osg::Vec3(layer_span*(i-1)/2, layer_span*(j-2)/2,
500                            alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2));
501         tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale * j/4);
502         color = osg::Vec4(1.0f, 1.0f, 1.0f,
503                           ( (j == 0) || (i == 3)) ?  
504                           ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
505         
506         cl[i]->push_back(color);
507         vl[i]->push_back(vertex);
508         tl[i]->push_back(tc);
509         
510         vertex = osg::Vec3(layer_span*(i-2)/2, layer_span*(j-1)/2,
511                            alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
512         tc = osg::Vec2(layer_scale * i/4, layer_scale * (j+1)/4 );
513         color = osg::Vec4(1.0f, 1.0f, 1.0f,
514                           ((j == 3) || (i == 0)) ?
515                           ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
516         cl[i]->push_back(color);
517         vl[i]->push_back(vertex);
518         tl[i]->push_back(tc);
519       }
520       
521       vertex = osg::Vec3(layer_span*(i-1)/2, layer_span, 
522                          alt_diff * (sin((i+1)*mpi) - 2));
523       
524       tc = osg::Vec2(layer_scale * (i+1)/4, layer_scale);
525       
526       color = osg::Vec4(1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
527       
528       cl[i]->push_back( color );
529       vl[i]->push_back( vertex );
530       tl[i]->push_back( tc );
531       
532       osg::Geometry* geometry = new osg::Geometry;
533       geometry->setUseDisplayList(false);
534       geometry->setVertexArray(vl[i].get());
535       geometry->setNormalBinding(osg::Geometry::BIND_OFF);
536       geometry->setColorArray(cl[i].get());
537       geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
538       geometry->setTexCoordArray(0, tl[i].get());
539       geometry->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, vl[i]->size()));
540       layer[i] = new osg::Geode;
541       
542       std::stringstream sstr;
543       sstr << "Cloud Layer (" << i << ")";
544       geometry->setName(sstr.str());
545       layer[i]->setName(sstr.str());
546       layer[i]->addDrawable(geometry);
547       layer_transform->addChild(layer[i].get());
548     }
549     
550     //OSGFIXME: true
551     if ( layer_states[layer_coverage].valid() ) {
552       osg::CopyOp copyOp;    // shallow copy
553       // render bin will be set in reposition
554       osg::StateSet* stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
555       stateSet->setDataVariance(osg::Object::DYNAMIC);
556       group_top->setStateSet(stateSet);
557       stateSet = static_cast<osg::StateSet*>(layer_states2[layer_coverage]->clone(copyOp));
558       stateSet->setDataVariance(osg::Object::DYNAMIC);
559       group_bottom->setStateSet(stateSet);
560     }
561 }
562
563 #if 0
564             sgMat4 modelview,
565                    tmp,
566                    transform;
567             ssgGetModelviewMatrix( modelview );
568             layer_transform->getTransform( transform );
569
570             sgTransposeNegateMat4( tmp, transform );
571
572             sgPostMultMat4( transform, modelview );
573             ssgLoadModelviewMatrix( transform );
574
575             sgVec3 lightVec;
576             ssgGetLight( 0 )->getPosition( lightVec );
577             sgNegateVec3( lightVec );
578             sgXformVec3( lightVec, tmp );
579
580             for ( int i = 0; i < 25; i++ ) {
581                 CloudVertex &v = vertices[ i ];
582                 sgSetVec3( v.tangentSpLight,
583                            sgScalarProductVec3( v.sTangent, lightVec ),
584                            sgScalarProductVec3( v.tTangent, lightVec ),
585                            sgScalarProductVec3( v.normal, lightVec ) );
586             }
587
588             ssgTexture *decal = color_map[ layer_coverage ][ top ? 1 : 0 ];
589             if ( top && decal == 0 ) {
590                 decal = color_map[ layer_coverage ][ 0 ];
591             }
592             ssgTexture *normal = normal_map[ layer_coverage ][ top ? 1 : 0 ];
593             if ( top && normal == 0 ) {
594                 normal = normal_map[ layer_coverage ][ 0 ];
595             }
596
597             glDisable( GL_LIGHTING );
598             glDisable( GL_CULL_FACE );
599 //            glDisable( GL_ALPHA_TEST );
600             if ( layer_coverage == SG_CLOUD_FEW ) {
601                 glEnable( GL_ALPHA_TEST );
602                 glAlphaFunc ( GL_GREATER, 0.01 );
603             }
604             glEnable( GL_BLEND ); 
605             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
606
607             glShadeModel( GL_SMOOTH );
608             glEnable( GL_COLOR_MATERIAL ); 
609             sgVec4 color;
610             float emis = 0.05;
611             if ( 1 ) {
612                 ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
613                 emis = ( color[0]+color[1]+color[2] ) / 3.0;
614                 if ( emis < 0.05 )
615                     emis = 0.05;
616             }
617             sgSetVec4( color, emis, emis, emis, 0.0 );
618             glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, color );
619             sgSetVec4( color, 1.0f, 1.0f, 1.0f, 0.0 );
620             glMaterialfv( GL_FRONT_AND_BACK, GL_AMBIENT, color );
621             sgSetVec4( color, 1.0, 1.0, 1.0, 0.0 );
622             glMaterialfv( GL_FRONT_AND_BACK, GL_DIFFUSE, color );
623             sgSetVec4( color, 0.0, 0.0, 0.0, 0.0 );
624             glMaterialfv( GL_FRONT_AND_BACK, GL_SPECULAR, color );
625
626             glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
627
628             glActiveTexturePtr( GL_TEXTURE0_ARB );
629             glBindTexture( GL_TEXTURE_2D, normal->getHandle() );
630             glEnable( GL_TEXTURE_2D );
631
632             //Bind normalisation cube map to texture unit 1
633             glActiveTexturePtr( GL_TEXTURE1_ARB );
634             glBindTexture( GL_TEXTURE_CUBE_MAP_ARB, normalization_cube_map );
635             glEnable( GL_TEXTURE_CUBE_MAP_ARB );
636             glActiveTexturePtr( GL_TEXTURE0_ARB );
637
638             //Set vertex arrays for cloud
639             glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
640             glEnableClientState( GL_VERTEX_ARRAY );
641 /*
642             if ( nb_texture_unit >= 3 ) {
643                 glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
644                 glEnableClientState( GL_COLOR_ARRAY );
645             }
646 */
647             //Send texture coords for normal map to unit 0
648             glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
649             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
650
651             //Send tangent space light vectors for normalisation to unit 1
652             glClientActiveTexturePtr( GL_TEXTURE1_ARB );
653             glTexCoordPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].tangentSpLight );
654             glEnableClientState( GL_TEXTURE_COORD_ARRAY );
655
656             //Set up texture environment to do (tex0 dot tex1)*color
657             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
658             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
659             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_REPLACE );
660             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE );
661             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
662
663 // use TexEnvCombine to add the highlights to the original lighting
664 osg::TexEnvCombine *te = new osg::TexEnvCombine;    
665 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
666 te->setCombine_RGB(osg::TexEnvCombine::REPLACE);
667 te->setSource0_Alpha(osg::TexEnvCombine::TEXTURE);
668 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
669 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
670
671
672             glActiveTexturePtr( GL_TEXTURE1_ARB );
673
674             glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
675             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
676             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_DOT3_RGB_ARB );
677             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
678             glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PREVIOUS_ARB );
679             glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_REPLACE );
680
681 osg::TexEnvCombine *te = new osg::TexEnvCombine;    
682 te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
683 te->setCombine_RGB(osg::TexEnvCombine::DOT3_RGB);
684 te->setSource1_RGB(osg::TexEnvCombine::PREVIOUS);
685 te->setSource0_Alpha(osg::TexEnvCombine::PREVIOUS);
686 te->setCombine_Alpha(osg::TexEnvCombine::REPLACE);
687 ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
688
689
690             if ( nb_texture_unit >= 3 ) {
691                 glActiveTexturePtr( GL_TEXTURE2_ARB );
692                 glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
693
694                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
695                 glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
696                 glEnableClientState( GL_TEXTURE_COORD_ARRAY );
697
698                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB );
699                 glTexEnvi( GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_ADD );
700                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE );
701                 glTexEnvi( GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB );
702
703                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
704                 glActiveTexturePtr( GL_TEXTURE0_ARB );
705
706                 //Draw cloud layer
707                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
708                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
709                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
710                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
711
712                 glDisable( GL_TEXTURE_2D );
713                 glActiveTexturePtr( GL_TEXTURE1_ARB );
714                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
715                 glActiveTexturePtr( GL_TEXTURE2_ARB );
716                 glDisable( GL_TEXTURE_2D );
717                 glActiveTexturePtr( GL_TEXTURE0_ARB );
718
719                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
720                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
721                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
722                 glClientActiveTexturePtr( GL_TEXTURE2_ARB );
723                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
724                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
725
726                 glDisableClientState( GL_COLOR_ARRAY );
727                 glEnable( GL_LIGHTING );
728
729                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
730
731             } else {
732                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
733                 glActiveTexturePtr( GL_TEXTURE0_ARB );
734
735                 //Draw cloud layer
736                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
737                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
738                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
739                 glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
740
741                 //Disable textures
742                 glDisable( GL_TEXTURE_2D );
743
744                 glActiveTexturePtr( GL_TEXTURE1_ARB );
745                 glDisable( GL_TEXTURE_CUBE_MAP_ARB );
746                 glActiveTexturePtr( GL_TEXTURE0_ARB );
747
748                 //disable vertex arrays
749                 glDisableClientState( GL_VERTEX_ARRAY );
750
751                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
752                 glClientActiveTexturePtr( GL_TEXTURE1_ARB );
753                 glDisableClientState( GL_TEXTURE_COORD_ARRAY );
754                 glClientActiveTexturePtr( GL_TEXTURE0_ARB );
755
756                 //Return to standard modulate texenv
757                 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
758
759                 if ( layer_coverage == SG_CLOUD_OVERCAST ) {
760                     glDepthFunc(GL_LEQUAL);
761
762                     glEnable( GL_LIGHTING );
763                     sgVec4 color;
764                     ssgGetLight( 0 )->getColour( GL_DIFFUSE, color );
765                     float average = ( color[0] + color[1] + color[2] ) / 3.0f;
766                     average = 0.15 + average/10;
767                     sgVec4 averageColor;
768                     sgSetVec4( averageColor, average, average, average, 1.0f );
769                     ssgGetLight( 0 )->setColour( GL_DIFFUSE, averageColor );
770
771                     glBlendColorPtr( average, average, average, 1.0f );
772                     glBlendFunc( GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_COLOR );
773
774                     //Perform a second pass to color the torus
775                     //Bind decal texture
776                     glBindTexture( GL_TEXTURE_2D, decal->getHandle() );
777                     glEnable(GL_TEXTURE_2D);
778
779                     //Set vertex arrays for torus
780                     glVertexPointer( 3, GL_FLOAT, sizeof(CloudVertex), &vertices[0].position );
781                     glEnableClientState( GL_VERTEX_ARRAY );
782
783                     //glColorPointer( 4, GL_FLOAT, sizeof(CloudVertex), &vertices[0].color );
784                     //glEnableClientState( GL_COLOR_ARRAY );
785
786                     glNormalPointer( GL_FLOAT, sizeof(CloudVertex), &vertices[0].normal );
787                     glEnableClientState( GL_NORMAL_ARRAY );
788
789                     glTexCoordPointer( 2, GL_FLOAT, sizeof(CloudVertex), &vertices[0].texCoord );
790                     glEnableClientState( GL_TEXTURE_COORD_ARRAY );
791
792                     //Draw cloud layer
793                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[0] );
794                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[10] );
795                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[20] );
796                     glDrawElements( GL_TRIANGLE_STRIP, 10, GL_UNSIGNED_INT, &indices[30] );
797
798                     ssgGetLight( 0 )->setColour( GL_DIFFUSE, color );
799
800                     glDisableClientState( GL_TEXTURE_COORD_ARRAY );
801                 }
802             }
803             //Disable texture
804             glDisable( GL_TEXTURE_2D );
805
806             glDisableClientState( GL_VERTEX_ARRAY );
807             glDisableClientState( GL_NORMAL_ARRAY );
808
809             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
810             glEnable( GL_CULL_FACE );
811             glDepthFunc(GL_LESS);
812
813             ssgLoadModelviewMatrix( modelview );
814 #endif
815
816 // repaint the cloud layer colors
817 bool SGCloudLayer::repaint( const SGVec3f& fog_color ) {
818     osg::Vec4f combineColor(fog_color.osg(), cloud_alpha);
819     osg::TexEnvCombine* combiner
820         = dynamic_cast<osg::TexEnvCombine*>(layer_root->getStateSet()
821                                             ->getTextureAttribute(1, osg::StateAttribute::TEXENV));
822     combiner->setConstantColor(combineColor);
823     return true;
824 }
825
826 // reposition the cloud layer at the specified origin and orientation
827 // lon specifies a rotation about the Z axis
828 // lat specifies a rotation about the new Y axis
829 // spin specifies a rotation about the new Z axis (and orients the
830 // sunrise/set effects
831 bool SGCloudLayer::reposition( const SGVec3f& p, const SGVec3f& up, double lon, double lat,
832                                double alt, double dt )
833 {
834     // combine p and asl (meters) to get translation offset
835     osg::Vec3 asl_offset(up.osg());
836     asl_offset.normalize();
837     if ( alt <= layer_asl ) {
838         asl_offset *= layer_asl;
839     } else {
840         asl_offset *= layer_asl + layer_thickness;
841     }
842
843     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
844     //      << "," << asl_offset[2] << endl;
845     asl_offset += p.osg();
846     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
847     //      << "," << asl_offset[2] << endl;
848
849     osg::Matrix T, LON, LAT;
850     // Translate to zero elevation
851     // Point3D zero_elev = current_view.get_cur_zero_elev();
852     T.makeTranslate( asl_offset );
853
854     // printf("  Translated to %.2f %.2f %.2f\n", 
855     //        zero_elev.x, zero_elev.y, zero_elev.z );
856
857     // Rotate to proper orientation
858     // printf("  lon = %.2f  lat = %.2f\n", 
859     //        lon * SGD_RADIANS_TO_DEGREES,
860     //        lat * SGD_RADIANS_TO_DEGREES);
861     LON.makeRotate(lon, osg::Vec3(0, 0, 1));
862
863     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
864     //             0.0, 1.0, 0.0 );
865     LAT.makeRotate(90.0 * SGD_DEGREES_TO_RADIANS - lat, osg::Vec3(0, 1, 0));
866
867     layer_transform->setMatrix( LAT*LON*T );
868     // The layers need to be drawn in order because they are
869     // translucent, but OSG transparency sorting doesn't work because
870     // the cloud polys are huge. However, the ordering is simple: the
871     // bottom polys should be drawn from high altitude to low, and the
872     // top polygons from low to high. The altitude can be used
873     // directly to order the polygons!
874     group_bottom->getStateSet()->setRenderBinDetails(-(int)layer_asl,
875                                                      "RenderBin");
876     group_top->getStateSet()->setRenderBinDetails((int)layer_asl,
877                                                   "RenderBin");
878     if ( alt <= layer_asl ) {
879       layer_root->setSingleChildOn(0);
880     } else if ( alt >= layer_asl + layer_thickness ) {
881       layer_root->setSingleChildOn(1);
882     } else {
883       layer_root->setAllChildrenOff();
884     }
885         
886
887     // now calculate update texture coordinates
888     if ( last_lon < -900 ) {
889         last_lon = lon;
890         last_lat = lat;
891     }
892
893     double sp_dist = speed*dt;
894
895     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
896         Point3D start( last_lon, last_lat, 0.0 );
897         Point3D dest( lon, lat, 0.0 );
898         double course = 0.0, dist = 0.0;
899
900         calc_gc_course_dist( dest, start, &course, &dist );
901         // cout << "course = " << course << ", dist = " << dist << endl;
902
903         // if start and dest are too close together,
904         // calc_gc_course_dist() can return a course of "nan".  If
905         // this happens, lets just use the last known good course.
906         // This is a hack, and it would probably be better to make
907         // calc_gc_course_dist() more robust.
908         if ( isnan(course) ) {
909             course = last_course;
910         } else {
911             last_course = course;
912         }
913
914         // calculate cloud movement due to external forces
915         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
916
917         if (dist > 0.0) {
918             ax = cos(course) * dist;
919             ay = sin(course) * dist;
920         }
921
922         if (sp_dist > 0) {
923             bx = cos((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
924             by = sin((180.0-direction) * SGD_DEGREES_TO_RADIANS) * sp_dist;
925         }
926
927
928         double xoff = (ax + bx) / (2 * scale);
929         double yoff = (ay + by) / (2 * scale);
930
931         const float layer_scale = layer_span / scale;
932
933         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
934         base[0] += xoff;
935
936         // the while loops can lead to *long* pauses if base[0] comes
937         // with a bogus value.
938         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
939         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
940         if ( base[0] > -10.0 && base[0] < 10.0 ) {
941             base[0] -= (int)base[0];
942         } else {
943             SG_LOG(SG_ASTRO, SG_DEBUG,
944                 "Error: base = " << base[0] << "," << base[1] <<
945                 " course = " << course << " dist = " << dist );
946             base[0] = 0.0;
947         }
948
949         base[1] += yoff;
950         // the while loops can lead to *long* pauses if base[0] comes
951         // with a bogus value.
952         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
953         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
954         if ( base[1] > -10.0 && base[1] < 10.0 ) {
955             base[1] -= (int)base[1];
956         } else {
957             SG_LOG(SG_ASTRO, SG_DEBUG,
958                     "Error: base = " << base[0] << "," << base[1] <<
959                     " course = " << course << " dist = " << dist );
960             base[1] = 0.0;
961         }
962
963         // cout << "base = " << base[0] << "," << base[1] << endl;
964
965         setTextureOffset(base);
966         last_lon = lon;
967         last_lat = lat;
968     }
969
970 //      layer3D->reposition( p, up, lon, lat, alt, dt, direction, speed);
971     return true;
972 }