]> git.mxchange.org Git - simgear.git/blob - simgear/scene/sky/cloud.cxx
Frederic: The state selector was not referenced and got deleted as soon as the sky...
[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  - curt@flightgear.org
6 //
7 // This program is distributed in the hope that it will be useful, but
8 // WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // General Public License for more details.
11 //
12 // You should have received a copy of the GNU General Public License
13 // along with this program; if not, write to the Free Software
14 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 //
16 // $Id$
17
18
19 #include <simgear/compiler.h>
20
21 // #include <stdio.h>
22 #include <math.h>
23
24 // #if defined (__APPLE__) 
25 // // any C++ header file undefines isinf and isnan
26 // // so this should be included before <iostream>
27 // inline int (isinf)(double r) { return isinf(r); }
28 // inline int (isnan)(double r) { return isnan(r); } 
29 // #endif
30
31 // #include STL_IOSTREAM
32
33 #include <plib/sg.h>
34 #include <plib/ssg.h>
35
36 #include <simgear/math/point3d.hxx>
37 #include <simgear/math/polar3d.hxx>
38 #include <simgear/math/sg_random.h>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/misc/sg_path.hxx>
41
42 #include "cloud.hxx"
43
44
45 static ssgStateSelector *layer_states[SGCloudLayer::SG_MAX_CLOUD_COVERAGES];
46 static bool state_initialized = false;
47
48
49 // Constructor
50 SGCloudLayer::SGCloudLayer( const string &tex_path ) :
51     layer_root(new ssgRoot),
52     layer_transform(new ssgTransform),
53     state_sel(0),
54     texture_path(tex_path),
55     layer_span(0.0),
56     layer_asl(0.0),
57     layer_thickness(0.0),
58     layer_transition(0.0),
59     layer_coverage(SG_CLOUD_CLEAR),
60     scale(4000.0),
61     speed(0.0),
62     direction(0.0),
63     last_lon(0.0),
64     last_lat(0.0)
65 {
66     cl[0] = cl[1] = cl[2] = cl[3] = NULL;
67     vl[0] = vl[1] = vl[2] = vl[3] = NULL;
68     tl[0] = tl[1] = tl[2] = tl[3] = NULL;
69     layer[0] = layer[1] = layer[2] = layer[3] = NULL;
70
71     layer_root->addKid(layer_transform);
72     rebuild();
73 }
74
75 // Destructor
76 SGCloudLayer::~SGCloudLayer()
77 {
78     delete layer_root;          // deletes layer_transform and layer as well
79 }
80
81 float
82 SGCloudLayer::getSpan_m () const
83 {
84     return layer_span;
85 }
86
87 void
88 SGCloudLayer::setSpan_m (float span_m)
89 {
90     if (span_m != layer_span) {
91         layer_span = span_m;
92         rebuild();
93     }
94 }
95
96 float
97 SGCloudLayer::getElevation_m () const
98 {
99     return layer_asl;
100 }
101
102 void
103 SGCloudLayer::setElevation_m (float elevation_m, bool set_span)
104 {
105     layer_asl = elevation_m;
106
107     if (set_span) {
108         if (elevation_m > 4000)
109             setSpan_m(  elevation_m * 10 );
110         else
111             setSpan_m( 40000 );
112     }
113 }
114
115 float
116 SGCloudLayer::getThickness_m () const
117 {
118     return layer_thickness;
119 }
120
121 void
122 SGCloudLayer::setThickness_m (float thickness_m)
123 {
124     layer_thickness = thickness_m;
125 }
126
127 float
128 SGCloudLayer::getTransition_m () const
129 {
130     return layer_transition;
131 }
132
133 void
134 SGCloudLayer::setTransition_m (float transition_m)
135 {
136     layer_transition = transition_m;
137 }
138
139 SGCloudLayer::Coverage
140 SGCloudLayer::getCoverage () const
141 {
142     return layer_coverage;
143 }
144
145 void
146 SGCloudLayer::setCoverage (Coverage coverage)
147 {
148     if (coverage != layer_coverage) {
149         layer_coverage = coverage;
150         rebuild();
151     }
152 }
153
154
155 // build the cloud object
156 void
157 SGCloudLayer::rebuild()
158 {
159     // Initialize states and sizes if necessary.
160     if ( !state_initialized ) { 
161         state_initialized = true;
162
163         SG_LOG(SG_ASTRO, SG_INFO, "initializing cloud layers");
164
165         SGPath cloud_path;
166         ssgStateSelector *state_sel;
167         ssgSimpleState *state;
168
169         state_sel = new ssgStateSelector( 2 );
170         state_sel->ref();
171         cloud_path.set(texture_path.str());
172         cloud_path.append("overcast.rgb");
173         state_sel->setStep( 0, sgCloudMakeState(cloud_path.str()) );
174         cloud_path.set(texture_path.str());
175         cloud_path.append("overcast_top.rgb");
176         state_sel->setStep( 1, sgCloudMakeState(cloud_path.str()) );
177         layer_states[SG_CLOUD_OVERCAST] = state_sel;
178
179         state_sel = new ssgStateSelector( 2 );
180         state_sel->ref();
181         cloud_path.set(texture_path.str());
182         cloud_path.append("broken.rgba");
183         state = sgCloudMakeState(cloud_path.str());
184         state_sel->setStep( 0, state );
185         state_sel->setStep( 1, state );
186         layer_states[SG_CLOUD_BROKEN] = state_sel;
187
188         state_sel = new ssgStateSelector( 2 );
189         state_sel->ref();
190         cloud_path.set(texture_path.str());
191         cloud_path.append("scattered.rgba");
192         state = sgCloudMakeState(cloud_path.str());
193         state_sel->setStep( 0, state );
194         state_sel->setStep( 1, state );
195         layer_states[SG_CLOUD_SCATTERED] = state_sel;
196
197         state_sel = new ssgStateSelector( 2 );
198         state_sel->ref();
199         cloud_path.set(texture_path.str());
200         cloud_path.append("few.rgba");
201         state = sgCloudMakeState(cloud_path.str());
202         state_sel->setStep( 0, state );
203         state_sel->setStep( 1, state );
204         layer_states[SG_CLOUD_FEW] = state_sel;
205
206         state_sel = new ssgStateSelector( 2 );
207         state_sel->ref();
208         cloud_path.set(texture_path.str());
209         cloud_path.append("cirrus.rgba");
210         state = sgCloudMakeState(cloud_path.str());
211         state_sel->setStep( 0, state );
212         state_sel->setStep( 1, state );
213         layer_states[SG_CLOUD_CIRRUS] = state_sel;
214
215         layer_states[SG_CLOUD_CLEAR] = 0;
216     }
217
218     scale = 4000.0;
219     last_lon = last_lat = -999.0f;
220
221     sgVec2 base;
222     sgSetVec2( base, sg_random(), sg_random() );
223
224     // build the cloud layer
225     sgVec4 color;
226     sgVec3 vertex;
227     sgVec2 tc;
228
229     const float layer_scale = layer_span / scale;
230     const float mpi = SG_PI/4;
231
232     // caclculate the difference between a flat-earth model and 
233     // a round earth model given the span and altutude ASL of
234     // the cloud layer. This is the difference in altitude between
235     // the top of the inverted bowl and the edge of the bowl.
236     // const float alt_diff = layer_asl * 0.8;
237     const float layer_to_core = (SG_EARTH_RAD * 1000 + layer_asl);
238     const float layer_angle = acos( 0.5*layer_span / layer_to_core);
239     const float border_to_core = layer_to_core * sin(layer_angle);
240     const float alt_diff = layer_to_core - border_to_core;
241
242     for (int i = 0; i < 4; i++)
243     {
244         if ( layer[i] != NULL ) {
245             layer_transform->removeKid(layer[i]); // automatic delete
246         }
247
248         vl[i] = new ssgVertexArray( 10 );
249         cl[i] = new ssgColourArray( 10 );
250         tl[i] = new ssgTexCoordArray( 10 );
251
252
253         sgSetVec3( vertex, layer_span*(i-2)/2, -layer_span,
254                            alt_diff * (sin(i*mpi) - 2) );
255
256         sgSetVec2( tc, base[0] + layer_scale * i/4, base[1] );
257
258         sgSetVec4( color, 1.0f, 1.0f, 1.0f, (i == 0) ? 0.0f : 0.15f );
259
260         cl[i]->add( color );
261         vl[i]->add( vertex );
262         tl[i]->add( tc );
263
264         for (int j = 0; j < 4; j++)
265         {
266             sgSetVec3( vertex, layer_span*(i-1)/2, layer_span*(j-2)/2,
267                                alt_diff * (sin((i+1)*mpi) + sin(j*mpi) - 2) );
268
269             sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
270                            base[1] + layer_scale * j/4 );
271
272             sgSetVec4( color, 1.0f, 1.0f, 1.0f,
273                               ( (j == 0) || (i == 3)) ?  
274                               ( (j == 0) && (i == 3)) ? 0.0f : 0.15f : 1.0f );
275
276             cl[i]->add( color );
277             vl[i]->add( vertex );
278             tl[i]->add( tc );
279
280
281             sgSetVec3( vertex, layer_span*(i-2)/2, layer_span*(j-1)/2,
282                                alt_diff * (sin(i*mpi) + sin((j+1)*mpi) - 2) );
283
284             sgSetVec2( tc, base[0] + layer_scale * i/4,
285                            base[1] + layer_scale * (j+1)/4 );
286
287             sgSetVec4( color, 1.0f, 1.0f, 1.0f,
288                               ((j == 3) || (i == 0)) ?
289                               ((j == 3) && (i == 0)) ? 0.0f : 0.15f : 1.0f );
290             cl[i]->add( color );
291             vl[i]->add( vertex );
292             tl[i]->add( tc );
293         }
294
295         sgSetVec3( vertex, layer_span*(i-1)/2, layer_span, 
296                            alt_diff * (sin((i+1)*mpi) - 2) );
297
298         sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
299                        base[1] + layer_scale );
300
301         sgSetVec4( color, 1.0f, 1.0f, 1.0f, (i == 3) ? 0.0f : 0.15f );
302
303         cl[i]->add( color );
304         vl[i]->add( vertex );
305         tl[i]->add( tc );
306
307         layer[i] = new ssgVtxTable(GL_TRIANGLE_STRIP, vl[i], NULL, tl[i], cl[i]);
308         layer_transform->addKid( layer[i] );
309
310         if ( layer_states[layer_coverage] != NULL ) {
311             layer[i]->setState( layer_states[layer_coverage] );
312         }
313         state_sel = layer_states[layer_coverage];
314     }
315
316     // force a repaint of the sky colors with arbitrary defaults
317     repaint( color );
318
319 }
320
321
322 // repaint the cloud layer colors
323 bool SGCloudLayer::repaint( sgVec3 fog_color ) {
324     float *color;
325
326     for ( int i = 0; i < 4; i++ )
327         for ( int j = 0; j < 10; ++j ) {
328             color = cl[i]->get( j );
329             sgCopyVec3( color, fog_color );
330         }
331
332     return true;
333 }
334
335
336 // reposition the cloud layer at the specified origin and orientation
337 // lon specifies a rotation about the Z axis
338 // lat specifies a rotation about the new Y axis
339 // spin specifies a rotation about the new Z axis (and orients the
340 // sunrise/set effects
341 bool SGCloudLayer::reposition( sgVec3 p, sgVec3 up, double lon, double lat,
342                                double alt, double dt )
343 {
344     sgMat4 T1, LON, LAT;
345     sgVec3 axis;
346
347     // combine p and asl (meters) to get translation offset
348     sgVec3 asl_offset;
349     sgCopyVec3( asl_offset, up );
350     sgNormalizeVec3( asl_offset );
351     if ( alt <= layer_asl ) {
352         sgScaleVec3( asl_offset, layer_asl );
353     } else {
354         sgScaleVec3( asl_offset, layer_asl + layer_thickness );
355     }
356     // cout << "asl_offset = " << asl_offset[0] << "," << asl_offset[1]
357     //      << "," << asl_offset[2] << endl;
358     sgAddVec3( asl_offset, p );
359     // cout << "  asl_offset = " << asl_offset[0] << "," << asl_offset[1]
360     //      << "," << asl_offset[2] << endl;
361
362     // Translate to zero elevation
363     // Point3D zero_elev = current_view.get_cur_zero_elev();
364     // xglTranslatef( zero_elev.x(), zero_elev.y(), zero_elev.z() );
365     sgMakeTransMat4( T1, asl_offset );
366
367     // printf("  Translated to %.2f %.2f %.2f\n", 
368     //        zero_elev.x, zero_elev.y, zero_elev.z );
369
370     // Rotate to proper orientation
371     // printf("  lon = %.2f  lat = %.2f\n", 
372     //        lon * SGD_RADIANS_TO_DEGREES,
373     //        lat * SGD_RADIANS_TO_DEGREES);
374     // xglRotatef( lon * SGD_RADIANS_TO_DEGREES, 0.0, 0.0, 1.0 );
375     sgSetVec3( axis, 0.0, 0.0, 1.0 );
376     sgMakeRotMat4( LON, lon * SGD_RADIANS_TO_DEGREES, axis );
377
378     // xglRotatef( 90.0 - f->get_Latitude() * SGD_RADIANS_TO_DEGREES,
379     //             0.0, 1.0, 0.0 );
380     sgSetVec3( axis, 0.0, 1.0, 0.0 );
381     sgMakeRotMat4( LAT, 90.0 - lat * SGD_RADIANS_TO_DEGREES, axis );
382
383     sgMat4 TRANSFORM;
384
385     sgCopyMat4( TRANSFORM, T1 );
386     sgPreMultMat4( TRANSFORM, LON );
387     sgPreMultMat4( TRANSFORM, LAT );
388
389     sgCoord layerpos;
390     sgSetCoord( &layerpos, TRANSFORM );
391
392     layer_transform->setTransform( &layerpos );
393
394     // now calculate update texture coordinates
395     if ( last_lon < -900 ) {
396         last_lon = lon;
397         last_lat = lat;
398     }
399
400     double sp_dist = speed*dt;
401
402     if ( lon != last_lon || lat != last_lat || sp_dist != 0 ) {
403         Point3D start( last_lon, last_lat, 0.0 );
404         Point3D dest( lon, lat, 0.0 );
405         double course = 0.0, dist = 0.0;
406
407         calc_gc_course_dist( dest, start, &course, &dist );
408         // cout << "course = " << course << ", dist = " << dist << endl;
409
410         // if start and dest are too close together,
411         // calc_gc_course_dist() can return a course of "nan".  If
412         // this happens, lets just use the last known good course.
413         // This is a hack, and it would probably be better to make
414         // calc_gc_course_dist() more robust.
415         if ( isnan(course) ) {
416             course = last_course;
417         } else {
418             last_course = course;
419         }
420
421         // calculate cloud movement due to external forces
422         double ax = 0.0, ay = 0.0, bx = 0.0, by = 0.0;
423
424         if (dist > 0.0) {
425             ax = cos(course) * dist;
426             ay = sin(course) * dist;
427         }
428
429         if (sp_dist > 0) {
430             bx = cos(-direction * SGD_DEGREES_TO_RADIANS) * sp_dist;
431             by = sin(-direction * SGD_DEGREES_TO_RADIANS) * sp_dist;
432         }
433
434
435         double xoff = (ax + bx) / (2 * scale);
436         double yoff = (ay + by) / (2 * scale);
437
438         const float layer_scale = layer_span / scale;
439
440         // cout << "xoff = " << xoff << ", yoff = " << yoff << endl;
441
442         float *base, *tc;
443
444         base = tl[0]->get( 0 );
445         base[0] += xoff;
446
447         // the while loops can lead to *long* pauses if base[0] comes
448         // with a bogus value.
449         // while ( base[0] > 1.0 ) { base[0] -= 1.0; }
450         // while ( base[0] < 0.0 ) { base[0] += 1.0; }
451         if ( base[0] > -10.0 && base[0] < 10.0 ) {
452             base[0] -= (int)base[0];
453         } else {
454             SG_LOG(SG_ASTRO, SG_DEBUG,
455                    "Error: base = " << base[0] << "," << base[1] <<
456                    " course = " << course << " dist = " << dist );
457             base[0] = 0.0;
458         }
459
460         base[1] += yoff;
461         // the while loops can lead to *long* pauses if base[0] comes
462         // with a bogus value.
463         // while ( base[1] > 1.0 ) { base[1] -= 1.0; }
464         // while ( base[1] < 0.0 ) { base[1] += 1.0; }
465         if ( base[1] > -10.0 && base[1] < 10.0 ) {
466            base[1] -= (int)base[1];
467         } else {
468            SG_LOG(SG_ASTRO, SG_ALERT,
469                   "Error: base = " << base[0] << "," << base[1] <<
470                   " course = " << course << " dist = " << dist );
471            base[1] = 0.0;
472         }
473
474         // cout << "base = " << base[0] << "," << base[1] << endl;
475
476         for (int i = 0; i < 4; i++)
477         {
478             tc = tl[i]->get( 0 );
479             sgSetVec2( tc, base[0] + layer_scale * i/4, base[1] );
480             
481             for (int j = 0; j < 4; j++)
482             {
483                 tc = tl[i]->get( j*2+1 );
484                 sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
485                                base[1] + layer_scale * j/4 );
486  
487                 tc = tl[i]->get( (j+1)*2 );
488                 sgSetVec2( tc, base[0] + layer_scale * i/4,
489                                base[1] + layer_scale * (j+1)/4 );
490             }
491  
492             tc = tl[i]->get( 9 );
493             sgSetVec2( tc, base[0] + layer_scale * (i+1)/4,
494                            base[1] + layer_scale );
495         }
496  
497         last_lon = lon;
498         last_lat = lat;
499     }
500
501     return true;
502 }
503
504
505 void SGCloudLayer::draw( bool top ) {
506     if ( layer_coverage != SG_CLOUD_CLEAR ) {
507         state_sel->selectStep( top ? 1 : 0 );
508         ssgCullAndDraw( layer_root );
509     }
510 }
511
512
513 // make an ssgSimpleState for a cloud layer given the named texture
514 ssgSimpleState *sgCloudMakeState( const string &path ) {
515     ssgSimpleState *state = new ssgSimpleState();
516
517     SG_LOG(SG_ASTRO, SG_INFO, " texture = ");
518
519     state->setTexture( (char *)path.c_str() );
520     state->setShadeModel( GL_SMOOTH );
521     state->disable( GL_LIGHTING );
522     state->disable( GL_CULL_FACE );
523     state->enable( GL_TEXTURE_2D );
524     state->enable( GL_COLOR_MATERIAL );
525     state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
526     state->setMaterial( GL_EMISSION, 0.05, 0.05, 0.05, 0.0 );
527     state->setMaterial( GL_AMBIENT, 0.2, 0.2, 0.2, 0.0 );
528     state->setMaterial( GL_DIFFUSE, 0.5, 0.5, 0.5, 0.0 );
529     state->setMaterial( GL_SPECULAR, 0.0, 0.0, 0.0, 0.0 );
530     state->enable( GL_BLEND );
531     state->enable( GL_ALPHA_TEST );
532     state->setAlphaClamp( 0.01 );
533
534     return state;
535 }