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