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