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