]> git.mxchange.org Git - flightgear.git/blob - src/Environment/fgclouds.cxx
Generate RNG at start of day, and pass down the stack for cloud generation.
[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 <cstring>
28 #include <Main/fg_props.hxx>
29
30 #include <simgear/constants.h>
31 #include <simgear/sound/soundmgr_openal.hxx>
32 #include <simgear/scene/sky/sky.hxx>
33 //#include <simgear/environment/visual_enviro.hxx>
34 #include <simgear/scene/sky/cloudfield.hxx>
35 #include <simgear/scene/sky/newcloud.hxx>
36 #include <simgear/structure/commands.hxx>
37 #include <simgear/props/props_io.hxx>
38
39 #include <Main/globals.hxx>
40 #include <Main/util.hxx>
41 #include <Viewer/renderer.hxx>
42 #include <Airports/simple.hxx>
43
44 #include "fgclouds.hxx"
45
46 static bool do_delete_3Dcloud (const SGPropertyNode *arg);
47 static bool do_move_3Dcloud (const SGPropertyNode *arg);
48 static bool do_add_3Dcloud (const SGPropertyNode *arg);
49
50 // RNG seed to ensure cloud synchronization across multi-process
51 // deployments
52 static mt seed;
53
54 FGClouds::FGClouds() :
55 #if 0
56     snd_lightning(0),
57 #endif
58     clouds_3d_enabled(false),
59     index(0)
60 {
61         update_event = 0;
62 }
63
64 FGClouds::~FGClouds()
65 {
66 }
67
68 int FGClouds::get_update_event(void) const {
69         return update_event;
70 }
71
72 void FGClouds::set_update_event(int count) {
73         update_event = count;
74         buildCloudLayers();
75 }
76
77 void FGClouds::Init(void) {
78 #if 0
79         if( snd_lightning == NULL ) {
80                 snd_lightning = new SGSoundSample("Sounds/thunder.wav", SGPath());
81                 snd_lightning->set_max_dist(7000.0f);
82                 snd_lightning->set_reference_dist(3000.0f);
83                 SGSoundMgr *smgr = globals->get_soundmgr();
84                 SGSampleGroup *sgr = smgr->find("weather", true);
85                 sgr->add( snd_lightning, "thunder" );
86         }
87 #endif
88
89         mt_init_time_10(&seed);
90
91         globals->get_commands()->addCommand("add-cloud", do_add_3Dcloud);
92         globals->get_commands()->addCommand("del-cloud", do_delete_3Dcloud);
93         globals->get_commands()->addCommand("move-cloud", do_move_3Dcloud);
94 }
95
96 // Build an invidual cloud. Returns the extents of the cloud for coverage calculations
97 double FGClouds::buildCloud(SGPropertyNode *cloud_def_root, SGPropertyNode *box_def_root, const string& name, double grid_z_rand, SGCloudField *layer) {
98         SGPropertyNode *box_def=NULL;
99         SGPropertyNode *cld_def=NULL;
100         double extent = 0.0;
101
102         SGPath texture_root = globals->get_fg_root();
103         texture_root.append("Textures");
104         texture_root.append("Sky");
105
106         box_def = box_def_root->getChild(name.c_str());
107
108         string base_name = name.substr(0,2);
109         if( !box_def ) {
110                 if( name[2] == '-' ) {
111                         box_def = box_def_root->getChild(base_name.c_str());
112                 }
113                 if( !box_def )
114                         return 0.0;
115         }
116
117         double x = mt_rand(&seed) * SGCloudField::fieldSize - (SGCloudField::fieldSize / 2.0);
118         double y = mt_rand(&seed) * SGCloudField::fieldSize - (SGCloudField::fieldSize / 2.0);
119         double z = grid_z_rand * (mt_rand(&seed) - 0.5);
120
121         float lon = fgGetNode("/position/longitude-deg", false)->getFloatValue();
122         float lat = fgGetNode("/position/latitude-deg", false)->getFloatValue();
123
124         SGVec3f pos(x,y,z);
125
126         for(int i = 0; i < box_def->nChildren() ; i++) {
127                 SGPropertyNode *abox = box_def->getChild(i);
128                 if( strcmp(abox->getName(), "box") == 0) {
129
130                         string type = abox->getStringValue("type", "cu-small");
131                         cld_def = cloud_def_root->getChild(type.c_str());
132                         if ( !cld_def ) return 0.0;
133
134                         double w = abox->getDoubleValue("width", 1000.0);
135                         double h = abox->getDoubleValue("height", 1000.0);
136                         int hdist = abox->getIntValue("hdist", 1);
137                         int vdist = abox->getIntValue("vdist", 1);
138
139                         double c = abox->getDoubleValue("count", 5);
140                         int count = (int) (c + (mt_rand(&seed) - 0.5) * c);
141
142                         extent = std::max(w*w, extent);
143
144                         for (int j = 0; j < count; j++) {
145
146                                 // Locate the clouds randomly in the defined space. The hdist and
147                                 // vdist values control the horizontal and vertical distribution
148                                 // by simply summing random components.
149                                 double x = 0.0;
150                                 double y = 0.0;
151                                 double z = 0.0;
152
153                                 for (int k = 0; k < hdist; k++)
154                                 {
155                                         x += (mt_rand(&seed) / hdist);
156                                         y += (mt_rand(&seed) / hdist);
157                                 }
158
159                                 for (int k = 0; k < vdist; k++)
160                                 {
161                                         z += (mt_rand(&seed) / vdist);
162                                 }
163
164                                 x = w * (x - 0.5) + pos[0]; // N/S
165                                 y = w * (y - 0.5) + pos[1]; // E/W
166                                 z = h * z + pos[2]; // Up/Down. pos[2] is the cloudbase
167
168                                 //SGVec3f newpos = SGVec3f(x, y, z);
169                                 SGNewCloud cld(texture_root, cld_def, &seed);
170
171                                 //layer->addCloud(newpos, cld.genCloud());
172                                 layer->addCloud(lon, lat, z, x, y, index++, cld.genCloud());
173                         }
174                 }
175         }
176
177         // Return the maximum extent of the cloud
178         return extent;
179 }
180
181 void FGClouds::buildLayer(int iLayer, const string& name, double coverage) {
182         struct {
183                 string name;
184                 double count;
185         } tCloudVariety[20];
186         int CloudVarietyCount = 0;
187         double totalCount = 0.0;
188
189     SGSky* thesky = globals->get_renderer()->getSky();
190     
191         SGPropertyNode *cloud_def_root = fgGetNode("/environment/cloudlayers/clouds", false);
192         SGPropertyNode *box_def_root   = fgGetNode("/environment/cloudlayers/boxes", false);
193         SGPropertyNode *layer_def_root = fgGetNode("/environment/cloudlayers/layers", false);
194         SGCloudField *layer = thesky->get_cloud_layer(iLayer)->get_layer3D();
195         layer->clear();
196
197         // If we don't have the required properties, then render the cloud in 2D
198         if ((! clouds_3d_enabled) || coverage == 0.0 ||
199                 layer_def_root == NULL || cloud_def_root == NULL || box_def_root == NULL) {
200                         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(false);
201                         return;
202         }
203
204         // If we can't find a definition for this cloud type, then render the cloud in 2D
205         SGPropertyNode *layer_def=NULL;
206         layer_def = layer_def_root->getChild(name.c_str());
207         if( !layer_def ) {
208                 if( name[2] == '-' ) {
209                         string base_name = name.substr(0,2);
210                         layer_def = layer_def_root->getChild(base_name.c_str());
211                 }
212                 if( !layer_def ) {
213                         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(false);
214                         return;
215                 }
216         }
217
218         // At this point, we know we've got some 3D clouds to generate.
219         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(true);
220
221         double grid_z_rand = layer_def->getDoubleValue("grid-z-rand");
222
223         for(int i = 0; i < layer_def->nChildren() ; i++) {
224                 SGPropertyNode *acloud = layer_def->getChild(i);
225                 if( strcmp(acloud->getName(), "cloud") == 0) {
226                         string cloud_name = acloud->getStringValue("name");
227                         tCloudVariety[CloudVarietyCount].name = cloud_name;
228                         double count = acloud->getDoubleValue("count", 1.0);
229                         tCloudVariety[CloudVarietyCount].count = count;
230                         int variety = 0;
231                         cloud_name = cloud_name + "-%d";
232                         char variety_name[50];
233                         do {
234                                 variety++;
235                                 snprintf(variety_name, sizeof(variety_name) - 1, cloud_name.c_str(), variety);
236                         } while( box_def_root->getChild(variety_name, 0, false) );
237
238                         totalCount += count;
239                         if( CloudVarietyCount < 20 )
240                                 CloudVarietyCount++;
241                 }
242         }
243         totalCount = 1.0 / totalCount;
244
245         // Determine how much cloud coverage we need in m^2.
246         double cov = coverage * SGCloudField::fieldSize * SGCloudField::fieldSize;
247
248         while (cov > 0.0f) {
249                 double choice = mt_rand(&seed);
250
251                 for(int i = 0; i < CloudVarietyCount ; i ++) {
252                         choice -= tCloudVariety[i].count * totalCount;
253                         if( choice <= 0.0 ) {
254                                 cov -= buildCloud(cloud_def_root,
255                                                 box_def_root,
256                                                 tCloudVariety[i].name,
257                                                 grid_z_rand,
258                                                 layer);
259                                 break;
260                         }
261                 }
262         }
263
264         // Now we've built any clouds, enable them and set the density (coverage)
265         //layer->setCoverage(coverage);
266         //layer->applyCoverage();
267         thesky->get_cloud_layer(iLayer)->set_enable3dClouds(clouds_3d_enabled);
268 }
269
270 void FGClouds::buildCloudLayers(void) {
271         SGPropertyNode *metar_root = fgGetNode("/environment", true);
272
273         //double wind_speed_kt   = metar_root->getDoubleValue("wind-speed-kt");
274         double temperature_degc  = metar_root->getDoubleValue("temperature-sea-level-degc");
275         double dewpoint_degc     = metar_root->getDoubleValue("dewpoint-sea-level-degc");
276         double pressure_mb       = metar_root->getDoubleValue("pressure-sea-level-inhg") * SG_INHG_TO_PA / 100.0;
277         double rel_humidity      = metar_root->getDoubleValue("relative-humidity");
278
279         // formule d'Epsy, base d'un cumulus
280         double cumulus_base = 122.0 * (temperature_degc - dewpoint_degc);
281         double stratus_base = 100.0 * (100.0 - rel_humidity) * SG_FEET_TO_METER;
282
283     SGSky* thesky = globals->get_renderer()->getSky();
284         for(int iLayer = 0 ; iLayer < thesky->get_cloud_layer_count(); iLayer++) {
285                 SGPropertyNode *cloud_root = fgGetNode("/environment/clouds/layer", iLayer, true);
286
287                 double alt_ft = cloud_root->getDoubleValue("elevation-ft");
288                 double alt_m = alt_ft * SG_FEET_TO_METER;
289                 string coverage = cloud_root->getStringValue("coverage");
290
291                 double coverage_norm = 0.0;
292                 if( coverage == "few" )
293                         coverage_norm = 2.0/8.0;        // <1-2
294                 else if( coverage == "scattered" )
295                         coverage_norm = 4.0/8.0;        // 3-4
296                 else if( coverage == "broken" )
297                         coverage_norm = 6.0/8.0;        // 5-7
298                 else if( coverage == "overcast" )
299                         coverage_norm = 8.0/8.0;        // 8
300
301                 string layer_type = "nn";
302
303                 if( coverage == "cirrus" ) {
304                         layer_type = "ci";
305                 } else if( alt_ft > 16500 ) {
306 //                      layer_type = "ci|cs|cc";
307                         layer_type = "ci";
308                 } else if( alt_ft > 6500 ) {
309 //                      layer_type = "as|ac|ns";
310                         layer_type = "ac";
311                         if( pressure_mb < 1005.0 && coverage_norm >= 0.5 )
312                                 layer_type = "ns";
313                 } else {
314 //                      layer_type = "st|cu|cb|sc";
315                         if( cumulus_base * 0.80 < alt_m && cumulus_base * 1.20 > alt_m ) {
316                                 // +/- 20% from cumulus probable base
317                                 layer_type = "cu";
318                         } else if( stratus_base * 0.80 < alt_m && stratus_base * 1.40 > alt_m ) {
319                                 // +/- 20% from stratus probable base
320                                 layer_type = "st";
321                         } else {
322                                 // above formulae is far from perfect
323                                 if ( alt_ft < 2000 )
324                                         layer_type = "st";
325                                 else if( alt_ft < 4500 )
326                                         layer_type = "cu";
327                                 else
328                                         layer_type = "sc";
329                         }
330                 }
331
332                 cloud_root->setStringValue("layer-type",layer_type);
333                 buildLayer(iLayer, layer_type, coverage_norm);
334         }
335 }
336
337 void FGClouds::set_3dClouds(bool enable)
338 {
339         if (enable != clouds_3d_enabled) {
340                 clouds_3d_enabled = enable;
341                 buildCloudLayers();
342         }
343 }
344
345 bool FGClouds::get_3dClouds() const
346 {
347         return clouds_3d_enabled;
348 }
349
350 /**
351  * Adds a 3D cloud to a cloud layer.
352  *
353  * Property arguments
354  * layer - the layer index to add this cloud to. (Defaults to 0)
355  * index - the index for this cloud (to be used later)
356  * lon/lat/alt - the position for the cloud
357  * (Various) - cloud definition properties. See README.3DClouds
358  *
359  */
360  static bool
361  do_add_3Dcloud (const SGPropertyNode *arg)
362  {
363    int l = arg->getIntValue("layer", 0);
364    int index = arg->getIntValue("index", 0);
365
366    SGPath texture_root = globals->get_fg_root();
367          texture_root.append("Textures");
368          texture_root.append("Sky");
369
370          float lon = arg->getFloatValue("lon-deg", 0.0f);
371          float lat = arg->getFloatValue("lat-deg", 0.0f);
372          float alt = arg->getFloatValue("alt-ft",  0.0f);
373          float x   = arg->getFloatValue("x-offset-m",  0.0f);
374          float y   = arg->getFloatValue("y-offset-m",  0.0f);
375
376    SGSky* thesky = globals->get_renderer()->getSky();
377    SGCloudField *layer = thesky->get_cloud_layer(l)->get_layer3D();
378    SGNewCloud cld(texture_root, arg, &seed);
379    bool success = layer->addCloud(lon, lat, alt, x, y, index, cld.genCloud());
380
381    // Adding a 3D cloud immediately makes this layer 3D.
382    thesky->get_cloud_layer(l)->set_enable3dClouds(true);
383
384    return success;
385  }
386
387  /**
388   * Removes a 3D cloud from a cloud layer
389   *
390   * Property arguments
391   *
392   * layer - the layer index to remove this cloud from. (defaults to 0)
393   * index - the cloud index
394   *
395   */
396  static bool
397  do_delete_3Dcloud (const SGPropertyNode *arg)
398  {
399    int l = arg->getIntValue("layer", 0);
400    int i = arg->getIntValue("index", 0);
401
402    SGSky* thesky = globals->get_renderer()->getSky();
403    SGCloudField *layer = thesky->get_cloud_layer(l)->get_layer3D();
404          return layer->deleteCloud(i);
405  }
406
407 /**
408  * Move a cloud within a 3D layer
409  *
410  * Property arguments
411  * layer - the layer index to add this cloud to. (Defaults to 0)
412  * index - the cloud index to move.
413  * lon/lat/alt - the position for the cloud
414  *
415  */
416  static bool
417  do_move_3Dcloud (const SGPropertyNode *arg)
418  {
419    int l = arg->getIntValue("layer", 0);
420    int i = arg->getIntValue("index", 0);
421       SGSky* thesky = globals->get_renderer()->getSky();
422      
423          float lon = arg->getFloatValue("lon-deg", 0.0f);
424          float lat = arg->getFloatValue("lat-deg", 0.0f);
425          float alt = arg->getFloatValue("alt-ft",  0.0f);
426          float x   = arg->getFloatValue("x-offset-m",  0.0f);
427          float y   = arg->getFloatValue("y-offset-m",  0.0f);
428
429    SGCloudField *layer = thesky->get_cloud_layer(l)->get_layer3D();
430          return layer->repositionCloud(i, lon, lat, alt, x, y);
431  }