]> git.mxchange.org Git - flightgear.git/blob - src/Environment/metarproperties.cxx
Live weather: ensure valid flag is set correctly
[flightgear.git] / src / Environment / metarproperties.cxx
1 // metarproperties.cxx -- Parse a METAR and write properties
2 //
3 // Written by David Megginson, started May 2002.
4 // Rewritten by Torsten Dreyer, August 2010
5 //
6 // Copyright (C) 2002  David Megginson - david@megginson.com
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <cstring> // for strlen
28
29 #include "metarproperties.hxx"
30 #include "fgmetar.hxx"
31 #include "environment.hxx"
32 #include "atmosphere.hxx"
33 #include "metarairportfilter.hxx"
34 #include <simgear/scene/sky/cloud.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/misc/strutils.hxx>
37 #include <simgear/magvar/magvar.hxx>
38 #include <simgear/timing/sg_time.hxx>
39 #include <Main/fg_props.hxx>
40
41 using std::string;
42
43 namespace Environment {
44
45 static vector<string> coverage_string;
46
47 /**
48  * @brief Helper class to wrap SGMagVar functionality and cache the variation and dip for
49  *        a certain position. 
50  */
51 class MagneticVariation : public SGMagVar {
52 public:
53   /**
54    * Constructor
55    */
56   MagneticVariation() : _lat(1), _lon(1), _alt(1) {
57     recalc( 0.0, 0.0, 0.0 );
58   }
59
60   /**
61    * @brief get the magnetic variation for a specific position at the current time
62    * @param lon the positions longitude in degrees
63    * @param lat the positions latitude in degrees
64    * @param alt the positions height above MSL (aka altitude) in feet
65    * @return the magnetic variation in degrees
66    */
67   double get_variation_deg( double lon, double lat, double alt );
68
69   /**
70    * @brief get the magnetic dip for a specific position at the current time
71    * @param lon the positions longitude in degrees
72    * @param lat the positions latitude in degrees
73    * @param alt the positions height above MSL (aka altitude) in feet
74    * @return the magnetic dip in degrees
75    */
76   double get_dip_deg( double lon, double lat, double alt );
77 private:
78   void recalc( double lon, double lat, double alt );
79   SGTime _time;
80   double _lat, _lon, _alt;
81 };
82
83 inline void MagneticVariation::recalc( double lon, double lat, double alt )
84 {
85   // calculation of magnetic variation is expensive. Cache the position
86   // and perform this calculation only if it has changed
87   if( _lon != lon || _lat != lat || _alt != alt ) {
88     SG_LOG(SG_ENVIRONMENT, SG_DEBUG, "Recalculating magvar for lon=" << lon << ", lat=" << lat << ", alt=" << alt );
89     _lon = lon;
90     _lat = lat;
91     _alt = alt;
92
93     SGGeod location(SGGeod::fromDegFt(lon, lat, alt));
94    _time.update( location, 0, 0 );
95     update( lon, lat, alt, _time.getJD() );
96   }
97 }
98
99 inline double MagneticVariation::get_variation_deg( double lon, double lat, double alt )
100 {
101   recalc( lon, lat, alt );
102   return get_magvar() * SGD_RADIANS_TO_DEGREES;
103 }
104
105 inline double MagneticVariation::get_dip_deg( double lon, double lat, double alt )
106 {
107   recalc( lon, lat, alt );
108   return get_magdip() * SGD_RADIANS_TO_DEGREES;
109 }
110
111 MetarProperties::MetarProperties( SGPropertyNode_ptr rootNode ) :
112   _rootNode(rootNode),
113   _metarValidNode( rootNode->getNode( "valid", true ) ),
114   _station_elevation(0.0),
115   _station_latitude(0.0),
116   _station_longitude(0.0),
117   _min_visibility(16000.0),
118   _max_visibility(16000.0),
119   _base_wind_dir(0),
120   _base_wind_range_from(0),
121   _base_wind_range_to(0),
122   _wind_speed(0.0),
123   _wind_from_north_fps(0.0),
124   _wind_from_east_fps(0.0),
125   _gusts(0.0),
126   _temperature(0.0),
127   _dewpoint(0.0),
128   _humidity(0.0),
129   _pressure(0.0),
130   _sea_level_temperature(0.0),
131   _sea_level_dewpoint(0.0),
132   _sea_level_pressure(29.92),
133   _rain(0.0),
134   _hail(0.0),
135   _snow(0.0),
136   _snow_cover(false),
137   _day(0),
138   _hour(0),
139   _minute(0),
140   _cavok(false),
141   _magneticVariation(new MagneticVariation())
142 {
143   // Hack to avoid static initialization order problems on OSX
144   if( coverage_string.empty() ) {
145     coverage_string.push_back(SGCloudLayer::SG_CLOUD_CLEAR_STRING);
146     coverage_string.push_back(SGCloudLayer::SG_CLOUD_FEW_STRING);
147     coverage_string.push_back(SGCloudLayer::SG_CLOUD_SCATTERED_STRING);
148     coverage_string.push_back(SGCloudLayer::SG_CLOUD_BROKEN_STRING);
149     coverage_string.push_back(SGCloudLayer::SG_CLOUD_OVERCAST_STRING);
150   }
151   // don't tie metar-valid, so listeners get triggered
152   _metarValidNode->setBoolValue( false );
153   _tiedProperties.setRoot( _rootNode );
154   _tiedProperties.Tie("data", this, &MetarProperties::get_metar, &MetarProperties::set_metar );
155   _tiedProperties.Tie("station-id", this, &MetarProperties::get_station_id, &MetarProperties::set_station_id );
156   _tiedProperties.Tie("station-elevation-ft", &_station_elevation );
157   _tiedProperties.Tie("station-latitude-deg", &_station_latitude );
158   _tiedProperties.Tie("station-longitude-deg", &_station_longitude );
159   _tiedProperties.Tie("station-magnetic-variation-deg", this, &MetarProperties::get_magnetic_variation_deg );
160   _tiedProperties.Tie("station-magnetic-dip-deg", this, &MetarProperties::get_magnetic_dip_deg );
161   _tiedProperties.Tie("min-visibility-m", &_min_visibility );
162   _tiedProperties.Tie("max-visibility-m", &_max_visibility );
163   _tiedProperties.Tie("base-wind-range-from", &_base_wind_range_from );
164   _tiedProperties.Tie("base-wind-range-to", &_base_wind_range_to );
165   _tiedProperties.Tie("base-wind-speed-kt", this, &MetarProperties::get_wind_speed, &MetarProperties::set_wind_speed );
166   _tiedProperties.Tie("base-wind-dir-deg", this, &MetarProperties::get_base_wind_dir, &MetarProperties::set_base_wind_dir );
167   _tiedProperties.Tie("base-wind-from-north-fps", this, &MetarProperties::get_wind_from_north_fps, &MetarProperties::set_wind_from_north_fps );
168   _tiedProperties.Tie("base-wind-from-east-fps",this, &MetarProperties::get_wind_from_east_fps, &MetarProperties::set_wind_from_east_fps );
169   _tiedProperties.Tie("gust-wind-speed-kt", &_gusts );
170   _tiedProperties.Tie("temperature-degc", &_temperature );
171   _tiedProperties.Tie("dewpoint-degc", &_dewpoint );
172   _tiedProperties.Tie("rel-humidity-norm", &_humidity );
173   _tiedProperties.Tie("pressure-inhg", &_pressure );
174   _tiedProperties.Tie("temperature-sea-level-degc", &_sea_level_temperature );
175   _tiedProperties.Tie("dewpoint-sea-level-degc", &_sea_level_dewpoint );
176   _tiedProperties.Tie("pressure-sea-level-inhg", &_sea_level_pressure );
177   _tiedProperties.Tie("rain-norm", &_rain );
178   _tiedProperties.Tie("hail-norm", &_hail );
179   _tiedProperties.Tie("snow-norm", &_snow);
180   _tiedProperties.Tie("snow-cover", &_snow_cover );
181   _tiedProperties.Tie("day", &_day );
182   _tiedProperties.Tie("hour", &_hour );
183   _tiedProperties.Tie("minute", &_minute );
184   _tiedProperties.Tie("decoded", this, &MetarProperties::get_decoded );
185   _tiedProperties.Tie("cavok", &_cavok );
186 }
187
188 MetarProperties::~MetarProperties()
189 {
190   delete _magneticVariation;
191 }
192
193 void MetarProperties::invalidate()
194 {
195   _metarValidNode->setBoolValue(false);
196 }
197
198 static const double thickness_value[] = { 0, 65, 600, 750, 1000 };
199
200 const char* MetarProperties::get_metar() const
201 {
202     if (!_metar) return "";
203     return _metar->getData();
204 }
205     
206 void MetarProperties::set_metar( const char * metarString )
207 {
208     SGSharedPtr<FGMetar> m;
209     if ((metarString == NULL) || (strlen(metarString) == 0)) {
210         setMetar(m);
211         return;
212     }
213     
214     try {
215         m = new FGMetar( metarString );
216     }
217     catch( sg_io_exception ) {
218         SG_LOG( SG_ENVIRONMENT, SG_WARN, "Can't parse metar: " << metarString );
219         _metarValidNode->setBoolValue(false);
220         return;
221     }
222     
223     setMetar(m);
224 }
225     
226 void MetarProperties::setMetar( SGSharedPtr<FGMetar> m )
227 {
228     _metar = m;
229     _decoded.clear();
230     if (!m) {
231         return;
232     }
233     
234     const vector<string> weather = m->getWeather();
235     for( vector<string>::const_iterator it = weather.begin(); it != weather.end(); ++it ) {
236         if( false == _decoded.empty() ) _decoded.append(", ");
237         _decoded.append(*it);
238     }
239
240     _min_visibility = m->getMinVisibility().getVisibility_m();
241     _max_visibility = m->getMaxVisibility().getVisibility_m();
242
243     const SGMetarVisibility *dirvis = m->getDirVisibility();
244     for ( int i = 0; i < 8; i++, dirvis++) {
245         SGPropertyNode *vis = _rootNode->getChild("visibility", i, true);
246         double v = dirvis->getVisibility_m();
247
248         vis->setDoubleValue("min-m", v);
249         vis->setDoubleValue("max-m", v);
250     }
251
252     set_base_wind_dir(m->getWindDir());
253     _base_wind_range_from = m->getWindRangeFrom();
254     _base_wind_range_to = m->getWindRangeTo();
255     set_wind_speed(m->getWindSpeed_kt());
256
257     _gusts = m->getGustSpeed_kt();
258     _temperature = m->getTemperature_C();
259     _dewpoint = m->getDewpoint_C();
260     _humidity = m->getRelHumidity();
261     _pressure = m->getPressure_inHg();
262
263     {
264         // 1. check the id given in the metar
265         FGAirport* a = FGAirport::findByIdent(m->getId());
266
267         // 2. if unknown, find closest airport with metar to current position
268         if( a == NULL ) {
269             SGGeod pos = SGGeod::fromDeg(
270                 fgGetDouble( "/position/longitude-deg", 0.0 ),
271                 fgGetDouble( "/position/latitude-deg", 0.0 ) );
272             a = FGAirport::findClosest(pos, 10000.0, MetarAirportFilter::instance() );
273         }
274
275         // 3. otherwise use ground elevation
276         if( a != NULL ) {
277             _station_elevation = a->getElevation();
278             const SGGeod & towerPosition = a->getTowerLocation();
279             _station_latitude = towerPosition.getLatitudeDeg();
280             _station_longitude = towerPosition.getLongitudeDeg();
281             _station_id = a->ident();
282         } else {
283             _station_elevation = fgGetDouble("/position/ground-elev-m", 0.0 ) * SG_METER_TO_FEET;
284             _station_latitude = fgGetDouble( "/position/latitude-deg", 0.0 );
285             _station_longitude = fgGetDouble( "/position/longitude-deg", 0.0 );
286             _station_id = "XXXX";
287         }
288     }
289
290     {    // calculate sea level temperature, dewpoint and pressure
291         FGEnvironment dummy; // instantiate a dummy so we can leech a method
292         dummy.set_elevation_ft( _station_elevation );
293         dummy.set_temperature_degc( _temperature );
294         dummy.set_dewpoint_degc( _dewpoint );
295         _sea_level_temperature = dummy.get_temperature_sea_level_degc();
296         _sea_level_dewpoint = dummy.get_dewpoint_sea_level_degc();
297
298         double elevation_m = _station_elevation * SG_FEET_TO_METER;
299         double fieldPressure = FGAtmo::fieldPressure( elevation_m, _pressure * atmodel::inHg );
300         _sea_level_pressure = P_layer(0, elevation_m, fieldPressure, _temperature + atmodel::freezing, atmodel::ISA::lam0) / atmodel::inHg;
301     }
302
303     bool isBC = false;
304     bool isBR = false;
305     bool isFG = false;
306     bool isMI = false;
307     bool isHZ = false;
308
309     {
310         for( unsigned i = 0; i < 3; i++ ) {
311             SGPropertyNode_ptr n = _rootNode->getChild("weather", i, true );
312             vector<struct SGMetar::Weather> weather = m->getWeather2();
313             struct SGMetar::Weather * w = i < weather.size() ? &weather[i] : NULL;
314             n->getNode("intensity",true)->setIntValue( w != NULL ? w->intensity : 0 );
315             n->getNode("vincinity",true)->setBoolValue( w != NULL ? w->vincinity : false );
316             for( unsigned j = 0; j < 3; j++ ) { 
317
318                 const string & phenomenon = w != NULL && j < w->phenomena.size() ? w->phenomena[j].c_str() : "";
319                 n->getChild( "phenomenon", j, true )->setStringValue( phenomenon );
320
321                 const string & description = w != NULL && j < w->descriptions.size() ? w->descriptions[j].c_str() : "";
322                 n->getChild( "description", j, true )->setStringValue( description );
323
324                 // need to know later, 
325                 // if its fog(FG) (might be shallow(MI) or patches(BC)) or haze (HZ) or mist(BR)
326                 if( phenomenon == "FG" ) isFG = true;
327                 if( phenomenon == "HZ" ) isHZ = true;
328                 if( phenomenon == "BR" ) isBR = true;
329                 if( description == "MI" ) isMI = true;
330                 if( description == "BC" ) isBC = true;
331             }
332         }
333     }
334
335     {
336         static const char * LAYER = "layer";
337         SGPropertyNode_ptr cloudsNode = _rootNode->getNode("clouds", true );
338         const vector<SGMetarCloud> & metarClouds = m->getClouds();
339         unsigned layerOffset = 0; // Oh, this is ugly!
340
341         // fog/mist/haze cloud layer does not work with 3d clouds yet :-(
342         bool setGroundCloudLayer = _rootNode->getBoolValue("set-ground-cloud-layer", false ) &&
343               false == (fgGetBool("/sim/rendering/shader-effects", false ) && 
344                         fgGetBool("/sim/rendering/clouds3d-enable", false ) );
345
346         if( setGroundCloudLayer ) {
347             // create a cloud layer #0 starting at the ground if its fog, mist or haze
348
349             // make sure layer actually starts at ground and set it's bottom at a constant
350             // value below the station's elevation
351             const double LAYER_BOTTOM_STATION_OFFSET =
352               fgGetDouble( "/environment/params/fog-mist-haze-layer/offset-from-station-elevation-ft", -200 );
353
354             SGMetarCloud::Coverage coverage = SGMetarCloud::COVERAGE_NIL;
355             double thickness = 0;
356             double alpha = 1.0;
357
358             if( isFG ) { // fog
359                 coverage = SGMetarCloud::getCoverage( isBC ? 
360                     fgGetString( "/environment/params/fog-mist-haze-layer/fog-bc-2dlayer-coverage", SGMetarCloud::COVERAGE_SCATTERED_STRING ) :
361                     fgGetString( "/environment/params/fog-mist-haze-layer/fog-2dlayer-coverage", SGMetarCloud::COVERAGE_BROKEN_STRING )
362                 );
363
364                 thickness = isMI ? 
365                    fgGetDouble("/environment/params/fog-mist-haze-layer/fog-shallow-thickness-ft",30) - LAYER_BOTTOM_STATION_OFFSET : // shallow fog, 10m/30ft
366                    fgGetDouble("/environment/params/fog-mist-haze-layer/fog-thickness-ft",500) - LAYER_BOTTOM_STATION_OFFSET; // fog, 150m/500ft
367                 alpha =  fgGetDouble("/environment/params/fog-mist-haze-layer/fog-2dlayer-alpha", 1.0);
368             } else if( isBR ) { // mist
369                 coverage = SGMetarCloud::getCoverage(fgGetString("/environment/params/fog-mist-haze-layer/mist-2dlayer-coverage", SGMetarCloud::COVERAGE_OVERCAST_STRING));
370                 thickness =  fgGetDouble("/environment/params/fog-mist-haze-layer/mist-thickness-ft",2000) - LAYER_BOTTOM_STATION_OFFSET;
371                 alpha =  fgGetDouble("/environment/params/fog-mist-haze-layer/mist-2dlayer-alpha",0.8);
372             } else if( isHZ ) { // haze
373                 coverage = SGMetarCloud::getCoverage(fgGetString("/environment/params/fog-mist-haze-layer/mist-2dlayer-coverage", SGMetarCloud::COVERAGE_OVERCAST_STRING));
374                 thickness =  fgGetDouble("/environment/params/fog-mist-haze-layer/haze-thickness-ft",2000) - LAYER_BOTTOM_STATION_OFFSET;
375                 alpha =  fgGetDouble("/environment/params/fog-mist-haze-layer/haze-2dlayer-alpha",0.6);
376             }
377
378             if( coverage != SGMetarCloud::COVERAGE_NIL ) {
379
380                 // if there is a layer above the fog, limit the top to one foot below that layer's bottom
381                 if( metarClouds.size() > 0 && metarClouds[0].getCoverage() != SGMetarCloud::COVERAGE_CLEAR )
382                     thickness = metarClouds[0].getAltitude_ft() - LAYER_BOTTOM_STATION_OFFSET - 1;
383
384                 SGPropertyNode_ptr layerNode = cloudsNode->getChild(LAYER, 0, true );
385                 layerNode->setDoubleValue( "coverage-type", SGCloudLayer::getCoverageType(coverage_string[coverage]) );
386                 layerNode->setStringValue( "coverage", coverage_string[coverage] );
387                 layerNode->setDoubleValue( "elevation-ft", _station_elevation + LAYER_BOTTOM_STATION_OFFSET );
388                 layerNode->setDoubleValue( "thickness-ft", thickness );
389                 layerNode->setDoubleValue( "visibility-m", _min_visibility );
390                 layerNode->setDoubleValue( "alpha", alpha );
391                 _min_visibility = _max_visibility =
392                   fgGetDouble("/environment/params/fog-mist-haze-layer/visibility-above-layer-m",20000.0); // assume good visibility above the fog
393                 layerOffset = 1;  // shudder
394             }
395         } 
396
397         for( unsigned i = 0; i < 5-layerOffset; i++ ) {
398             SGPropertyNode_ptr layerNode = cloudsNode->getChild(LAYER, i+layerOffset, true );
399             SGMetarCloud::Coverage coverage = i < metarClouds.size() ? metarClouds[i].getCoverage() : SGMetarCloud::COVERAGE_CLEAR;
400             double elevation = 
401                 i >= metarClouds.size() || coverage == SGMetarCloud::COVERAGE_CLEAR ? 
402                 -9999.0 : 
403                 metarClouds[i].getAltitude_ft() + _station_elevation;
404
405             layerNode->setDoubleValue( "alpha", 1.0 );
406             layerNode->setStringValue( "coverage", coverage_string[coverage] );
407             layerNode->setDoubleValue( "coverage-type", SGCloudLayer::getCoverageType(coverage_string[coverage]) );
408             layerNode->setDoubleValue( "elevation-ft", elevation );
409             layerNode->setDoubleValue( "thickness-ft", thickness_value[coverage]);
410             layerNode->setDoubleValue( "span-m", 40000 );
411             layerNode->setDoubleValue( "visibility-m", 50.0 );
412         }
413     }
414
415     _rain = m->getRain();
416     _hail = m->getHail();
417     _snow = m->getSnow();
418     _snow_cover = m->getSnowCover();
419     _day = m->getDay();
420     _hour = m->getHour();
421     _minute = m->getMinute();
422     _cavok = m->getCAVOK();
423     _metarValidNode->setBoolValue(true);
424 }
425
426 void MetarProperties::setStationId( const std::string & value )
427
428     set_station_id(simgear::strutils::strip(value).c_str());
429 }
430
431 double MetarProperties::get_magnetic_variation_deg() const 
432 {
433   return _magneticVariation->get_variation_deg( _station_longitude, _station_latitude, _station_elevation );
434 }
435
436 double MetarProperties::get_magnetic_dip_deg() const
437 {
438   return _magneticVariation->get_dip_deg( _station_longitude, _station_latitude, _station_elevation );
439 }
440
441 static inline void calc_wind_hs( double north_fps, double east_fps, int & heading_deg, double & speed_kt )
442 {
443     speed_kt = sqrt((north_fps)*(north_fps)+(east_fps)*(east_fps)) * 3600.0 / (SG_NM_TO_METER * SG_METER_TO_FEET);
444     heading_deg = SGMiscd::roundToInt( 
445         SGMiscd::normalizeAngle2( atan2( east_fps, north_fps ) ) * SGD_RADIANS_TO_DEGREES );
446 }
447
448 void MetarProperties::set_wind_from_north_fps( double value )
449 {
450     _wind_from_north_fps = value;
451     calc_wind_hs( _wind_from_north_fps, _wind_from_east_fps, _base_wind_dir, _wind_speed );
452 }
453
454 void MetarProperties::set_wind_from_east_fps( double value )
455 {
456     _wind_from_east_fps = value;
457     calc_wind_hs( _wind_from_north_fps, _wind_from_east_fps, _base_wind_dir, _wind_speed );
458 }
459
460 static inline void calc_wind_ne( double heading_deg, double speed_kt, double & north_fps, double & east_fps )
461 {
462     double speed_fps = speed_kt * SG_NM_TO_METER * SG_METER_TO_FEET / 3600.0;
463     north_fps = speed_fps * cos(heading_deg * SGD_DEGREES_TO_RADIANS);
464     east_fps = speed_fps * sin(heading_deg * SGD_DEGREES_TO_RADIANS);
465 }
466
467 void MetarProperties::set_base_wind_dir( double value )
468 {
469     _base_wind_dir = value;
470     calc_wind_ne( (double)_base_wind_dir, _wind_speed, _wind_from_north_fps, _wind_from_east_fps );
471 }
472
473 void MetarProperties::set_wind_speed( double value )
474 {
475     _wind_speed = value;
476     calc_wind_ne( (double)_base_wind_dir, _wind_speed, _wind_from_north_fps, _wind_from_east_fps );
477 }
478
479
480 } // namespace Environment