]> git.mxchange.org Git - flightgear.git/blob - src/Environment/fgclouds.cxx
5d7df98b072139e99d8b84f59ed05e0546cc81bc
[flightgear.git] / src / Environment / fgclouds.cxx
1 // Build a cloud layer based on metar
2 //
3 // Written by Harald JOHNSEN, started April 2005.
4 //
5 // Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program 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 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <Main/fg_props.hxx>
28
29 #include <simgear/constants.h>
30 #include <simgear/sound/soundmgr_openal.hxx>
31 #include <simgear/scene/sky/sky.hxx>
32 #include <simgear/environment/visual_enviro.hxx>
33 #include <simgear/scene/sky/cloudfield.hxx>
34 #include <simgear/scene/sky/newcloud.hxx>
35 #include <simgear/math/sg_random.h>
36 #include <simgear/props/props_io.hxx>
37
38 #include <Main/globals.hxx>
39 #include <Airports/simple.hxx>
40 #include <Main/util.hxx>
41
42 #include "environment_ctrl.hxx"
43 #include "environment_mgr.hxx"
44 #include "fgmetar.hxx"
45 #include "fgclouds.hxx"
46
47 extern SGSky *thesky;
48
49
50 FGClouds::FGClouds(FGEnvironmentCtrl * controller) :
51         station_elevation_ft(0.0),
52         _controller( controller ),
53         snd_lightning(NULL),
54     clouds_3d_enabled(false),
55     last_scenario( "unset" ),
56     last_env_config( new SGPropertyNode() ),
57     last_env_clouds( new SGPropertyNode() )
58 {
59         update_event = 0;
60 }
61
62 FGClouds::~FGClouds() {
63 }
64
65 int FGClouds::get_update_event(void) const {
66         return update_event;
67 }
68
69 void FGClouds::set_update_event(int count) {
70         update_event = count;
71         buildCloudLayers();
72 }
73
74 void FGClouds::init(void) {
75         if( snd_lightning == NULL ) {
76                 snd_lightning = new SGSoundSample(globals->get_fg_root().c_str(), "Sounds/thunder.wav");
77                 snd_lightning->set_max_dist(7000.0f);
78                 snd_lightning->set_reference_dist(3000.0f);
79                 SGSoundMgr *soundMgr = globals->get_soundmgr();
80                 soundMgr->add( snd_lightning, "thunder" );
81                 sgEnviro.set_soundMgr( soundMgr );
82         }
83 }
84
85 void FGClouds::buildCloud(SGPropertyNode *cloud_def_root, SGPropertyNode  *box_def_root, const string& name, sgVec3 pos, SGCloudField *layer) {
86         SGPropertyNode *box_def=NULL;
87         SGPropertyNode *cld_def=NULL;
88         
89         SGPath texture_root = globals->get_fg_root();
90         texture_root.append("Textures");
91         texture_root.append("Sky");
92
93         box_def = box_def_root->getChild(name.c_str());
94   
95         string base_name = name.substr(0,2);
96         if( !box_def ) {
97                 if( name[2] == '-' ) {
98                         box_def = box_def_root->getChild(base_name.c_str());
99                 }
100                 if( !box_def )
101                         return;
102         }
103         
104         for(int i = 0; i < box_def->nChildren() ; i++) {
105                 SGPropertyNode *abox = box_def->getChild(i);
106                 if( strcmp(abox->getName(), "box") == 0) {
107                         double x = abox->getDoubleValue("x") + pos[0];
108                         double y = abox->getDoubleValue("y") + pos[1];
109                         double z = abox->getDoubleValue("z") + pos[2];
110                         SGVec3f newpos = SGVec3f(x, z, y);
111                         
112                         string type = abox->getStringValue("type", "cu-small");
113                                
114                         cld_def = cloud_def_root->getChild(type.c_str());
115                         if ( !cld_def ) return;
116                         
117                         double min_width = cld_def->getDoubleValue("min-cloud-width-m", 500.0);
118                         double max_width = cld_def->getDoubleValue("max-cloud-width-m", 1000.0);
119                         double min_height = cld_def->getDoubleValue("min-cloud-height-m", min_width);
120                         double max_height = cld_def->getDoubleValue("max-cloud-height-m", max_width);
121                         double min_sprite_width = cld_def->getDoubleValue("min-sprite-width-m", 200.0);
122                         double max_sprite_width = cld_def->getDoubleValue("max-sprite-width-m", min_sprite_width);
123                         double min_sprite_height = cld_def->getDoubleValue("min-sprite-height-m", min_sprite_width);
124                         double max_sprite_height = cld_def->getDoubleValue("max-sprite-height-m", max_sprite_width);
125                         int num_sprites = cld_def->getIntValue("num-sprites", 20);
126                         int num_textures_x = cld_def->getIntValue("num-textures-x", 1);
127                         int num_textures_y = cld_def->getIntValue("num-textures-y", 1);
128                         double bottom_shade = cld_def->getDoubleValue("bottom-shade", 1.0);
129                         string texture = cld_def->getStringValue("texture", "cl_cumulus.rgb");
130           
131                         SGNewCloud *cld = 
132                                 new SGNewCloud(type,
133                                                texture_root, 
134                                                texture, 
135                                                min_width, 
136                                                max_width, 
137                                                min_height,
138                                                max_height,
139                                                min_sprite_width,
140                                                max_sprite_width,
141                                                min_sprite_height,
142                                                max_sprite_height,
143                                                bottom_shade,
144                                                num_sprites,
145                                                num_textures_x,
146                                                num_textures_y);
147                         layer->addCloud(newpos, cld);
148                 }
149         }
150 }
151
152 void FGClouds::buildLayer(int iLayer, const string& name, double alt, double coverage) {
153         struct {
154                 string name;
155                 double count;
156         } tCloudVariety[20];
157         int CloudVarietyCount = 0;
158         double totalCount = 0.0;
159         
160         SGPropertyNode *cloud_def_root = fgGetNode("/environment/cloudlayers/clouds", false);
161         SGPropertyNode *box_def_root   = fgGetNode("/environment/cloudlayers/boxes", false);
162         SGPropertyNode *layer_def_root = fgGetNode("/environment/cloudlayers/layers", false);
163         SGCloudField *layer = thesky->get_cloud_layer(iLayer)->get_layer3D();
164         layer->clear();
165         
166         // If we don't have the required properties, then render the cloud in 2D
167         if ((! clouds_3d_enabled) || coverage == 0.0 ||
168             layer_def_root == NULL || cloud_def_root == NULL || box_def_root == NULL)
169         {
170                 thesky->get_cloud_layer(iLayer)->set_enable3dClouds(false);
171                 return;
172         }
173         
174         // If we can't find a definition for this cloud type, then render the cloud in 2D
175         SGPropertyNode *layer_def=NULL;
176         layer_def = layer_def_root->getChild(name.c_str());
177         if( !layer_def ) {
178                 if( name[2] == '-' ) {
179                         string base_name = name.substr(0,2);
180                         layer_def = layer_def_root->getChild(base_name.c_str());
181                 }
182                 if( !layer_def )
183                 {
184                         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(false);
185                         return;
186                 }
187         }
188         
189         // At this point, we know we've got some 3D clouds to generate.
190         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(true);
191
192         double grid_x_size = layer_def->getDoubleValue("grid-x-size", 1000.0);
193         double grid_y_size = layer_def->getDoubleValue("grid-y-size", 1000.0);
194         double grid_x_rand = layer_def->getDoubleValue("grid-x-rand", grid_x_size);
195         double grid_y_rand = layer_def->getDoubleValue("grid-y-rand", grid_y_size);
196         double grid_z_rand = layer_def->getDoubleValue("grid-z-rand");
197
198         for(int i = 0; i < layer_def->nChildren() ; i++) {
199                 SGPropertyNode *acloud = layer_def->getChild(i);
200                 if( strcmp(acloud->getName(), "cloud") == 0) {
201                         string cloud_name = acloud->getStringValue("name");
202                         tCloudVariety[CloudVarietyCount].name = cloud_name;
203                         double count = acloud->getDoubleValue("count", 1.0);
204                         tCloudVariety[CloudVarietyCount].count = count;
205                         int variety = 0;
206                         cloud_name = cloud_name + "-%d";
207                         char variety_name[50];
208                         do {
209                                 variety++;
210                                 snprintf(variety_name, sizeof(variety_name), cloud_name.c_str(), variety);
211                         } while( box_def_root->getChild(variety_name, 0, false) );
212
213                         totalCount += count;
214                         if( CloudVarietyCount < 20 )
215                                 CloudVarietyCount++;
216                 }
217         }
218         totalCount = 1.0 / totalCount;
219         
220         for(double px = 0.0; px < SGCloudField::fieldSize; px += grid_x_size) {
221                 for(double py = 0.0; py < SGCloudField::fieldSize; py += grid_y_size) {
222                         double x = px + grid_x_rand * (sg_random() - 0.5) - (SGCloudField::fieldSize / 2.0);
223                         double y = py + grid_y_rand * (sg_random() - 0.5) - (SGCloudField::fieldSize / 2.0);
224                         double z = grid_z_rand * (sg_random() - 0.5);
225                         
226                         if (sg_random() < coverage)
227                         {
228                             double choice = sg_random();
229     
230                             for(int i = 0; i < CloudVarietyCount ; i ++) {
231                                     choice -= tCloudVariety[i].count * totalCount;
232                                     if( choice <= 0.0 ) {
233                                             sgVec3 pos={x,z,y};
234                                             
235                                             buildCloud(cloud_def_root, 
236                                                        box_def_root, 
237                                                        tCloudVariety[i].name, 
238                                                        pos, 
239                                                        layer);
240                                             break;
241                                     }
242                             }
243                         }
244                 }
245         }
246
247         // Now we've built any clouds, enable them and set the density (coverage)
248         //layer->setCoverage(coverage);
249         //layer->applyCoverage();
250         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(clouds_3d_enabled);
251 }
252
253 void FGClouds::buildCloudLayers(void) {
254         SGPropertyNode *metar_root = fgGetNode("/environment", true);
255         
256         double wind_speed_kt     = metar_root->getDoubleValue("wind-speed-kt");
257         double temperature_degc  = metar_root->getDoubleValue("temperature-sea-level-degc");
258         double dewpoint_degc     = metar_root->getDoubleValue("dewpoint-sea-level-degc");
259         double pressure_mb              = metar_root->getDoubleValue("pressure-sea-level-inhg") * SG_INHG_TO_PA / 100.0;
260
261         double dewp = pow(10.0, 7.5 * dewpoint_degc / (237.7 + dewpoint_degc));
262         double temp = pow(10.0, 7.5 * temperature_degc / (237.7 + temperature_degc));
263         double rel_humidity = dewp * 100 / temp;
264
265         // formule d'Epsy, base d'un cumulus
266         double cumulus_base = 122.0 * (temperature_degc - dewpoint_degc);
267         double stratus_base = 100.0 * (100.0 - rel_humidity) * SG_FEET_TO_METER;
268
269         bool cu_seen = false;
270
271         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
272                 SGPropertyNode *cloud_root = fgGetNode("/environment/clouds/layer", iLayer, true);
273
274                 double alt_ft = cloud_root->getDoubleValue("elevation-ft");
275                 double alt_m = alt_ft * SG_FEET_TO_METER;
276                 string coverage = cloud_root->getStringValue("coverage");
277                 
278                 
279                 double coverage_norm = 0.0;
280                 if( coverage == "few" )
281                         coverage_norm = 2.0/8.0;        // <1-2
282                 else if( coverage == "scattered" )
283                         coverage_norm = 4.0/8.0;        // 3-4
284                 else if( coverage == "broken" )
285                         coverage_norm = 6.0/8.0;        // 5-7
286                 else if( coverage == "overcast" )
287                         coverage_norm = 8.0/8.0;        // 8
288
289                 string layer_type = "nn";
290                 if( coverage == "cirrus" ) {
291                         layer_type = "ci";
292                 } else if( alt_ft > 16500 ) {
293 //                      layer_type = "ci|cs|cc";
294                         layer_type = "ci";
295                 } else if( alt_ft > 6500 ) {
296 //                      layer_type = "as|ac|ns";
297                         layer_type = "ac";
298                         if( pressure_mb < 1005.0 && coverage_norm >= 0.5 )
299                                 layer_type = "ns";
300                 } else {
301 //                      layer_type = "st|cu|cb|sc";
302                         if( cumulus_base * 0.80 < alt_m && cumulus_base * 1.20 > alt_m ) {
303                                 // +/- 20% from cumulus probable base
304                                 layer_type = "cu";
305                         } else if( stratus_base * 0.80 < alt_m && stratus_base * 1.40 > alt_m ) {
306                                 // +/- 20% from stratus probable base
307                                 layer_type = "st";
308                         } else {
309                                 // above formulae is far from perfect
310                                 if ( alt_ft < 2000 )
311                                         layer_type = "st";
312                                 else if( alt_ft < 4500 )
313                                         layer_type = "cu";
314                                 else
315                                         layer_type = "sc";
316                         }
317                 }
318                 
319                 buildLayer(iLayer, layer_type, alt_m, coverage_norm);
320         }
321 }
322
323 // copy from FGMetarEnvironmentCtrl until better
324 void
325 FGClouds::update_metar_properties( const FGMetar *m )
326 {
327     int i;
328     int j;
329     double d;
330     char s[128];
331
332     fgSetString("/environment/metar/station-id", m->getId());
333     fgSetDouble("/environment/metar/min-visibility-m",
334                 m->getMinVisibility().getVisibility_m() );
335     fgSetDouble("/environment/metar/max-visibility-m",
336                 m->getMaxVisibility().getVisibility_m() );
337
338     const SGMetarVisibility *dirvis = m->getDirVisibility();
339     for (i = 0; i < 8; i++, dirvis++) {
340         const char *min = "/environment/metar/visibility[%d]/min-m";
341         const char *max = "/environment/metar/visibility[%d]/max-m";
342
343         d = dirvis->getVisibility_m();
344
345         snprintf(s, 128, min, i);
346         fgSetDouble(s, d);
347         snprintf(s, 128, max, i);
348         fgSetDouble(s, d);
349     }
350
351     fgSetInt("/environment/metar/base-wind-range-from",
352              m->getWindRangeFrom() );
353     fgSetInt("/environment/metar/base-wind-range-to",
354              m->getWindRangeTo() );
355     fgSetDouble("/environment/metar/base-wind-speed-kt",
356                 m->getWindSpeed_kt() );
357     fgSetDouble("/environment/metar/gust-wind-speed-kt",
358                 m->getGustSpeed_kt() );
359     fgSetDouble("/environment/metar/temperature-degc",
360                 m->getTemperature_C() );
361     fgSetDouble("/environment/metar/dewpoint-degc",
362                 m->getDewpoint_C() );
363     fgSetDouble("/environment/metar/rel-humidity-norm",
364                 m->getRelHumidity() );
365     fgSetDouble("/environment/metar/pressure-inhg",
366                 m->getPressure_inHg() );
367
368     vector<SGMetarCloud> cv = m->getClouds();
369     vector<SGMetarCloud>::const_iterator cloud;
370
371     // Load into both the METAR and environment properties to stop interpolation
372     const char *cl[] = {"/environment/metar/clouds/layer[%i]",
373                         "/environment/clouds/layer[%i]"};
374
375     for (j = 0; j < 2; j++)
376     {
377         for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
378             const char *coverage_string[5] = 
379                 { "clear", "few", "scattered", "broken", "overcast" };
380             const double thickness[5] = { 0, 65, 600,750, 1000};
381             int q;
382     
383             snprintf(s, 128, cl[j], i);
384             strncat(s, "/coverage", 128);
385             q = cloud->getCoverage();
386             fgSetString(s, coverage_string[q] );
387             
388             snprintf(s, 128, cl[j], i);
389             strncat(s, "/elevation-ft", 128);
390             fgSetDouble(s, cloud->getAltitude_ft() + station_elevation_ft);
391             
392             snprintf(s, 128, cl[j], i);
393             strncat(s, "/thickness-ft", 128);
394             fgSetDouble(s, thickness[q]);
395             
396             snprintf(s, 128, cl[j], i);
397             strncat(s, "/span-m", 128);
398             fgSetDouble(s, 40000.0);
399         }
400     
401         for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
402             
403             
404             snprintf(s, 128, cl[j], i);
405             strncat(s, "/coverage", 128);
406             fgSetString(s, "clear");
407     
408             snprintf(s, 128, cl[j], i);
409             strncat(s, "/elevation-ft", 128);
410             fgSetDouble(s, -9999);
411     
412             snprintf(s, 128, cl[j], i);
413             strncat(s, "/thickness-ft", 128);
414             fgSetDouble(s, 0);
415     
416             snprintf(s, 128, cl[j], i);
417             strncat(s, "/span-m", 128);
418             fgSetDouble(s, 40000.0);
419         }
420     }
421
422     fgSetDouble("/environment/metar/rain-norm", m->getRain());
423     fgSetDouble("/environment/metar/hail-norm", m->getHail());
424     fgSetDouble("/environment/metar/snow-norm", m->getSnow());
425     fgSetBool("/environment/metar/snow-cover", m->getSnowCover());
426 }
427
428 void
429 FGClouds::update_env_config ()
430 {
431     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
432                  fgGetDouble("/environment/metar/base-wind-range-to"),
433                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
434                  fgGetDouble("/environment/metar/gust-wind-speed-kt") );
435
436     fgDefaultWeatherValue( "visibility-m",
437                            fgGetDouble("/environment/metar/min-visibility-m") );
438 #if 0
439     set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
440                           station_elevation_ft );
441     set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
442                               station_elevation_ft );
443 #endif
444     fgDefaultWeatherValue( "pressure-sea-level-inhg",
445                            fgGetDouble("/environment/metar/pressure-inhg") );
446 }
447
448 void FGClouds::setLayer( int iLayer, float alt_ft, const string& coverage, const string& layer_type ) {
449         double coverage_norm = 0.0;
450         if( coverage == "few" )
451                 coverage_norm = 2.0/8.0;        // <1-2
452         else if( coverage == "scattered" )
453                 coverage_norm = 4.0/8.0;        // 3-4
454         else if( coverage == "broken" )
455                 coverage_norm = 6.0/8.0;        // 5-7
456         else if( coverage == "overcast" )
457                 coverage_norm = 8.0/8.0;        // 8
458
459         buildLayer(iLayer, layer_type, station_elevation_ft + alt_ft * SG_FEET_TO_METER, coverage_norm);
460 }
461
462 void FGClouds::buildScenario( const string& scenario ) {
463         string fakeMetar="";
464         string station = fgGetString("/environment/metar/station-id", "XXXX");
465         
466         // fetch station elevation if exists
467         if( station == "XXXX" )
468             station_elevation_ft = fgGetDouble("/position/ground-elev-m", 0.0);
469         else {
470             const FGAirport* a = FGAirport::findByIdent(station);
471             station_elevation_ft = (a ? a->getElevation() : 0.0);
472         }
473
474         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
475             thesky->get_cloud_layer(iLayer)
476                 ->setCoverage(SGCloudLayer::SG_CLOUD_CLEAR);
477             thesky->get_cloud_layer(iLayer)->get_layer3D()->clear();
478         }
479
480         station += " 011000Z ";
481         if( scenario == "Fair weather" ) {
482                 fakeMetar = "15003KT 12SM SCT041 FEW200 20/08 Q1015 NOSIG";
483                 //setLayer(0, 3300.0, "scattered", "cu");
484         } else if( scenario == "Thunderstorm" ) {
485                 fakeMetar = "15012KT 08SM TSRA SCT040 BKN070 20/12 Q0995";
486                 setLayer(0, 4000.0, "scattered", "cb");
487                 setLayer(1, 7000.0, "scattered", "ns");
488         } else 
489                 return;
490         FGMetar *m = new FGMetar( station + fakeMetar );
491         update_metar_properties( m );
492         update_env_config();
493         // propagate aloft tables
494         //_controller->reinit();
495
496         fgSetString("/environment/metar/last-metar", m->getData());
497         // TODO:de-activate real metar updates
498         if( scenario == "Fair weather" ) {
499                 fgSetString("/environment/clouds/layer[1]/coverage", "cirrus");
500         }
501 }
502
503 void FGClouds::set_scenario(const char * sc) {
504
505         scenario = string(sc);
506         
507 //        if(!rebuild_required && (scenario == last_scenario))
508 //            return;
509         
510         if( last_scenario == "none" ) {
511         // save clouds and weather conditions
512             SGPropertyNode *param = fgGetNode("/environment/config", true);
513             copyProperties( param, last_env_config );
514             param = fgGetNode("/environment/clouds", true);
515             copyProperties( param, last_env_clouds );
516         }
517                 
518         if( scenario == "METAR" ) {
519             string realMetar = fgGetString("/environment/metar/real-metar", "");
520
521             if( realMetar != "" ) {
522                 fgSetString("/environment/metar/last-metar", realMetar.c_str());
523                 FGMetar *m = new FGMetar( realMetar );
524                 update_metar_properties( m );
525                 update_env_config();
526                         // propagate aloft tables
527                 _controller->reinit();
528                 buildCloudLayers();
529             }
530         }
531         else if( scenario == "none" ) {
532         // restore clouds and weather conditions
533             SGPropertyNode *param = fgGetNode("/environment/config", true);
534             copyProperties( last_env_config, param );
535             param = fgGetNode("/environment/clouds", true);
536             copyProperties( last_env_clouds, param );
537             fgSetDouble("/environment/metar/rain-norm", 0.0);
538             fgSetDouble("/environment/metar/snow-norm", 0.0);
539 //          update_env_config();
540             // propagate aloft tables
541             _controller->reinit();
542             buildCloudLayers();
543         }
544         else {
545             buildScenario( scenario );
546             _controller->reinit();
547             buildCloudLayers();
548         }
549         
550         last_scenario = scenario;
551
552         if( snd_lightning == NULL )
553             init();
554 }
555
556 const char * FGClouds::get_scenario(void) const
557 {
558     return scenario.c_str();
559 }
560
561 void FGClouds::set_3dClouds(bool enable)
562 {
563     if (enable != clouds_3d_enabled) {
564         clouds_3d_enabled = enable;
565         buildCloudLayers();
566     }
567 }
568
569 bool FGClouds::get_3dClouds() const {
570     return clouds_3d_enabled;
571 }
572