]> git.mxchange.org Git - flightgear.git/blob - src/Environment/fgclouds.cxx
James Turner: Improved runway management code:
[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     last_scenario( "none" ),
55     last_env_config( new SGPropertyNode() ),
56     last_env_clouds( new SGPropertyNode() )
57 {
58         update_event = 0;
59         fgSetString("/environment/weather-scenario", last_scenario.c_str());
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         build();
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 SGNewCloud *FGClouds::buildCloud(SGPropertyNode *cloud_def_root, const string& name) {
84         SGPropertyNode *cld_def=NULL;
85
86         cld_def = cloud_def_root->getChild(name.c_str());
87         string base_name = name.substr(0,2);
88         if( !cld_def ) {
89                 if( name[2] == '-' ) {
90                         cld_def = cloud_def_root->getChild(base_name.c_str());
91                 }
92                 if( !cld_def )
93                         return NULL;
94         }
95         string familly = cld_def->getStringValue("familly", base_name.c_str());
96         SGNewCloud *cld = new SGNewCloud(familly);
97         for(int i = 0; i < cld_def->nChildren() ; i++) {
98                 SGPropertyNode *abox = cld_def->getChild(i);
99                 if( strcmp(abox->getName(), "box") == 0) {
100                         double x = abox->getDoubleValue("x");
101                         double y = abox->getDoubleValue("y");
102                         double z = abox->getDoubleValue("z");
103                         double size = abox->getDoubleValue("size");
104                         int type = abox->getIntValue("type", SGNewCloud::CLbox_standard);
105                         cld->addContainer(x, y, z, size, (SGNewCloud::CLbox_type) type);
106                 }
107         }
108         cld->genSprites();
109         return cld;
110 }
111
112 void FGClouds::buildLayer(SGCloudField *layer, const string& name, double alt, double coverage) {
113         struct {
114                 string name;
115                 double count;
116         } tCloudVariety[20];
117         int CloudVarietyCount = 0;
118         double totalCount = 0.0;
119
120         SGPropertyNode *cloud_def_root = fgGetNode("/environment/cloudlayers/clouds", false);
121         SGPropertyNode *layer_def_root = fgGetNode("/environment/cloudlayers/layers", false);
122
123         layer->clear();
124         // when we don't generate clouds the layer is rendered in 2D
125         if( coverage == 0.0 )
126                 return;
127         if( layer_def_root == NULL || cloud_def_root == NULL)
128                 return;
129         if( name == "ci" || name == "sc" || name == "st")
130                 return;
131
132         SGPropertyNode *layer_def=NULL;
133
134         layer_def = layer_def_root->getChild(name.c_str());
135         if( !layer_def ) {
136                 if( name[2] == '-' ) {
137                         string base_name = name.substr(0,2);
138                         layer_def = layer_def_root->getChild(base_name.c_str());
139                 }
140                 if( !layer_def )
141                         return;
142         }
143
144         double grid_x_size = layer_def->getDoubleValue("grid-x-size", 1000.0);
145         double grid_y_size = layer_def->getDoubleValue("grid-y-size", 1000.0);
146         double grid_x_rand = layer_def->getDoubleValue("grid-x-rand", grid_x_size);
147         double grid_y_rand = layer_def->getDoubleValue("grid-y-rand", grid_y_size);
148         double grid_z_rand = layer_def->getDoubleValue("grid-z-rand");
149
150         for(int i = 0; i < layer_def->nChildren() ; i++) {
151                 SGPropertyNode *acloud = layer_def->getChild(i);
152                 if( strcmp(acloud->getName(), "cloud") == 0) {
153                         string cloud_name = acloud->getStringValue("name");
154                         tCloudVariety[CloudVarietyCount].name = cloud_name;
155                         double count = acloud->getDoubleValue("count", 1.0);
156                         tCloudVariety[CloudVarietyCount].count = count;
157                         int variety = 0;
158                         cloud_name = cloud_name + "-%d";
159                         char variety_name[50];
160                         do {
161                                 variety++;
162                                 snprintf(variety_name, sizeof(variety_name), cloud_name.c_str(), variety);
163                         } while( cloud_def_root->getChild(variety_name, 0, false) );
164
165                         totalCount += count;
166                         if( CloudVarietyCount < 20 )
167                                 CloudVarietyCount++;
168                 }
169         }
170         totalCount = 1.0 / totalCount;
171         double currCoverage = 0.0;
172
173         for(double px = 0.0; px < SGCloudField::fieldSize; px += grid_x_size) {
174                 for(double py = 0.0; py < SGCloudField::fieldSize; py += grid_y_size) {
175                         double x = px + grid_x_rand * (sg_random() - 0.5);
176                         double y = py + grid_y_rand * (sg_random() - 0.5);
177                         double z = alt + grid_z_rand * (sg_random() - 0.5);
178                         double choice = sg_random();
179                         currCoverage += coverage;
180                         if( currCoverage < 1.0 )
181                                 continue;
182                         currCoverage -= 1.0;
183
184                         for(int i = 0; i < CloudVarietyCount ; i ++) {
185                                 choice -= tCloudVariety[i].count * totalCount;
186                                 if( choice <= 0.0 ) {
187                                         SGNewCloud *cld = buildCloud(cloud_def_root, tCloudVariety[i].name);
188                                         sgVec3 pos={x,z,y};
189                                         if( cld )
190                                                 layer->addCloud(pos, cld);
191
192                                         break;
193                                 }
194                         }
195                 }
196         }
197
198 }
199
200 // TODO:call this after real metar updates
201 void FGClouds::buildMETAR(void) {
202         SGPropertyNode *metar_root = fgGetNode("/environment", true);
203
204         double wind_speed_kt     = metar_root->getDoubleValue("wind-speed-kt");
205         double temperature_degc  = metar_root->getDoubleValue("temperature-sea-level-degc");
206         double dewpoint_degc     = metar_root->getDoubleValue("dewpoint-sea-level-degc");
207         double pressure_mb              = metar_root->getDoubleValue("pressure-sea-level-inhg") * SG_INHG_TO_PA / 100.0;
208
209         double dewp = pow(10.0, 7.5 * dewpoint_degc / (237.7 + dewpoint_degc));
210         double temp = pow(10.0, 7.5 * temperature_degc / (237.7 + temperature_degc));
211         double rel_humidity = dewp * 100 / temp;
212
213         // formule d'Epsy, base d'un cumulus
214         double cumulus_base = 122.0 * (temperature_degc - dewpoint_degc);
215         double stratus_base = 100.0 * (100.0 - rel_humidity) * SG_FEET_TO_METER;
216
217         bool cu_seen = false;
218
219         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
220                 SGPropertyNode *cloud_root = fgGetNode("/environment/clouds/layer", iLayer, true);
221
222                 double alt_ft = cloud_root->getDoubleValue("elevation-ft");
223                 double alt_m = alt_ft * SG_FEET_TO_METER;
224                 string coverage = cloud_root->getStringValue("coverage");
225                 double coverage_norm = 0.0;
226                 if( coverage == "few" )
227                         coverage_norm = 2.0/8.0;        // <1-2
228                 else if( coverage == "scattered" )
229                         coverage_norm = 4.0/8.0;        // 3-4
230                 else if( coverage == "broken" )
231                         coverage_norm = 6.0/8.0;        // 5-7
232                 else if( coverage == "overcast" )
233                         coverage_norm = 8.0/8.0;        // 8
234
235                 string layer_type = "nn";
236                 if( coverage == "cirrus" ) {
237                         layer_type = "ci";
238                 } else if( alt_ft > 16500 ) {
239 //                      layer_type = "ci|cs|cc";
240                         layer_type = "ci";
241                 } else if( alt_ft > 6500 ) {
242 //                      layer_type = "as|ac|ns";
243                         layer_type = "ac";
244                         if( pressure_mb < 1005.0 && coverage_norm >= 5.5 )
245                                 layer_type = "ns";
246                 } else {
247 //                      layer_type = "st|cu|cb|sc";
248                         // +/- 20% from stratus probable base
249                         if( stratus_base * 0.80 < alt_m && stratus_base * 1.40 > alt_m )
250                                 layer_type = "st";
251                         // +/- 20% from cumulus probable base
252                         else if( cumulus_base * 0.80 < alt_m && cumulus_base * 1.20 > alt_m )
253                                 layer_type = "cu";
254                         else {
255                                 // above formulae is far from perfect
256                                 if ( alt_ft < 2000 )
257                                         layer_type = "st";
258                                 else if( alt_ft < 4500 )
259                                         layer_type = "cu";
260                                 else
261                                         layer_type = "sc";
262                         }
263                 }
264
265                 SGCloudField *layer3D = thesky->get_cloud_layer(iLayer)->get_layer3D();
266                 buildLayer(layer3D, layer_type, alt_m, coverage_norm);
267         }
268 }
269
270 // copy from FGMetarEnvironmentCtrl until better
271 void
272 FGClouds::update_metar_properties( const FGMetar *m )
273 {
274     int i;
275     double d;
276     char s[128];
277
278     fgSetString("/environment/metar/station-id", m->getId());
279     fgSetDouble("/environment/metar/min-visibility-m",
280                 m->getMinVisibility().getVisibility_m() );
281     fgSetDouble("/environment/metar/max-visibility-m",
282                 m->getMaxVisibility().getVisibility_m() );
283
284     const SGMetarVisibility *dirvis = m->getDirVisibility();
285     for (i = 0; i < 8; i++, dirvis++) {
286         const char *min = "/environment/metar/visibility[%d]/min-m";
287         const char *max = "/environment/metar/visibility[%d]/max-m";
288
289         d = dirvis->getVisibility_m();
290
291         snprintf(s, 128, min, i);
292         fgSetDouble(s, d);
293         snprintf(s, 128, max, i);
294         fgSetDouble(s, d);
295     }
296
297     fgSetInt("/environment/metar/base-wind-range-from",
298              m->getWindRangeFrom() );
299     fgSetInt("/environment/metar/base-wind-range-to",
300              m->getWindRangeTo() );
301     fgSetDouble("/environment/metar/base-wind-speed-kt",
302                 m->getWindSpeed_kt() );
303     fgSetDouble("/environment/metar/gust-wind-speed-kt",
304                 m->getGustSpeed_kt() );
305     fgSetDouble("/environment/metar/temperature-degc",
306                 m->getTemperature_C() );
307     fgSetDouble("/environment/metar/dewpoint-degc",
308                 m->getDewpoint_C() );
309     fgSetDouble("/environment/metar/rel-humidity-norm",
310                 m->getRelHumidity() );
311     fgSetDouble("/environment/metar/pressure-inhg",
312                 m->getPressure_inHg() );
313
314     vector<SGMetarCloud> cv = m->getClouds();
315     vector<SGMetarCloud>::const_iterator cloud;
316
317     const char *cl = "/environment/clouds/layer[%i]";
318     for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
319         const char *coverage_string[5] = 
320             { "clear", "few", "scattered", "broken", "overcast" };
321         const double thickness[5] = { 0, 65, 600,750, 1000};
322         int q;
323
324         snprintf(s, 128, cl, i);
325         strncat(s, "/coverage", 128);
326         q = cloud->getCoverage();
327         fgSetString(s, coverage_string[q] );
328
329         snprintf(s, 128, cl, i);
330         strncat(s, "/elevation-ft", 128);
331         fgSetDouble(s, cloud->getAltitude_ft() + station_elevation_ft);
332
333         snprintf(s, 128, cl, i);
334         strncat(s, "/thickness-ft", 128);
335         fgSetDouble(s, thickness[q]);
336
337         snprintf(s, 128, cl, i);
338         strncat(s, "/span-m", 128);
339         fgSetDouble(s, 40000.0);
340     }
341
342     for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
343         snprintf(s, 128, cl, i);
344         strncat(s, "/coverage", 128);
345         fgSetString(s, "clear");
346
347         snprintf(s, 128, cl, i);
348         strncat(s, "/elevation-ft", 128);
349         fgSetDouble(s, -9999);
350
351         snprintf(s, 128, cl, i);
352         strncat(s, "/thickness-ft", 128);
353         fgSetDouble(s, 0);
354
355         snprintf(s, 128, cl, i);
356         strncat(s, "/span-m", 128);
357         fgSetDouble(s, 40000.0);
358     }
359
360     fgSetDouble("/environment/metar/rain-norm", m->getRain());
361     fgSetDouble("/environment/metar/hail-norm", m->getHail());
362     fgSetDouble("/environment/metar/snow-norm", m->getSnow());
363     fgSetBool("/environment/metar/snow-cover", m->getSnowCover());
364 }
365
366 void
367 FGClouds::update_env_config ()
368 {
369     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
370                  fgGetDouble("/environment/metar/base-wind-range-to"),
371                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
372                  fgGetDouble("/environment/metar/gust-wind-speed-kt") );
373
374     fgDefaultWeatherValue( "visibility-m",
375                            fgGetDouble("/environment/metar/min-visibility-m") );
376 #if 0
377     set_temp_at_altitude( fgGetDouble("/environment/metar/temperature-degc"),
378                           station_elevation_ft );
379     set_dewpoint_at_altitude( fgGetDouble("/environment/metar/dewpoint-degc"),
380                               station_elevation_ft );
381 #endif
382     fgDefaultWeatherValue( "pressure-sea-level-inhg",
383                            fgGetDouble("/environment/metar/pressure-inhg") );
384 }
385
386
387 void FGClouds::setLayer( int iLayer, float alt_ft, const string& coverage, const string& layer_type ) {
388         double coverage_norm = 0.0;
389         if( coverage == "few" )
390                 coverage_norm = 2.0/8.0;        // <1-2
391         else if( coverage == "scattered" )
392                 coverage_norm = 4.0/8.0;        // 3-4
393         else if( coverage == "broken" )
394                 coverage_norm = 6.0/8.0;        // 5-7
395         else if( coverage == "overcast" )
396                 coverage_norm = 8.0/8.0;        // 8
397
398         SGCloudField *layer3D = thesky->get_cloud_layer(iLayer)->get_layer3D();
399         buildLayer(layer3D, layer_type, station_elevation_ft + alt_ft * SG_FEET_TO_METER, coverage_norm);
400 }
401
402 void FGClouds::buildScenario( const string& scenario ) {
403         string fakeMetar="";
404         string station = fgGetString("/environment/metar/station-id", "XXXX");
405
406         // fetch station elevation if exists
407     if( station == "XXXX" )
408         station_elevation_ft = fgGetDouble("/position/ground-elev-m", 0.0);
409     else {
410         const FGAirport* a = globals->get_airports()->search( station );
411         station_elevation_ft = (a ? a->getElevation() : 0.0);
412     }
413
414         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
415             thesky->get_cloud_layer(iLayer)
416                 ->setCoverage(SGCloudLayer::SG_CLOUD_CLEAR);
417             thesky->get_cloud_layer(iLayer)->get_layer3D()->clear();
418         }
419
420         station += " 011000Z ";
421         if( scenario == "Fair weather" ) {
422                 fakeMetar = "15003KT 12SM SCT033 FEW200 20/08 Q1015 NOSIG";
423                 setLayer(0, 3300.0, "scattered", "cu");
424         } else if( scenario == "Thunderstorm" ) {
425                 fakeMetar = "15012KT 08SM TSRA SCT040 BKN070 20/12 Q0995";
426                 setLayer(0, 4000.0, "scattered", "cb");
427                 setLayer(1, 7000.0, "scattered", "ns");
428         } else 
429                 return;
430         FGMetar *m = new FGMetar( station + fakeMetar );
431         update_metar_properties( m );
432         update_env_config();
433         // propagate aloft tables
434         _controller->reinit();
435
436         fgSetString("/environment/metar/last-metar", m->getData());
437         // TODO:desactivate real metar updates
438         if( scenario == "Fair weather" ) {
439                 fgSetString("/environment/clouds/layer[1]/coverage", "cirrus");
440         }
441 }
442
443
444 void FGClouds::build(void) {
445         string scenario = fgGetString("/environment/weather-scenario", "METAR");
446
447     if( scenario == last_scenario)
448         return;
449     if( last_scenario == "none" ) {
450         // save clouds and weather conditions
451         SGPropertyNode *param = fgGetNode("/environment/config", true);
452         copyProperties( param, last_env_config );
453         param = fgGetNode("/environment/clouds", true);
454         copyProperties( param, last_env_clouds );
455     }
456         if( scenario == "METAR" ) {
457                 string realMetar = fgGetString("/environment/metar/real-metar", "");
458                 if( realMetar != "" ) {
459                         fgSetString("/environment/metar/last-metar", realMetar.c_str());
460                         FGMetar *m = new FGMetar( realMetar );
461                         update_metar_properties( m );
462                         update_env_config();
463                         // propagate aloft tables
464                         _controller->reinit();
465                 }
466                 buildMETAR();
467         }
468     else if( scenario == "none" ) {
469         // restore clouds and weather conditions
470         SGPropertyNode *param = fgGetNode("/environment/config", true);
471         copyProperties( last_env_config, param );
472         param = fgGetNode("/environment/clouds", true);
473         copyProperties( last_env_clouds, param );
474         fgSetDouble("/environment/metar/rain-norm", 0.0);
475         fgSetDouble("/environment/metar/snow-norm", 0.0);
476 //          update_env_config();
477             // propagate aloft tables
478             _controller->reinit();
479                 buildMETAR();
480     }
481         else
482                 buildScenario( scenario );
483     last_scenario = scenario;
484
485         // ...
486         if( snd_lightning == NULL )
487                 init();
488 }