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