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