]> git.mxchange.org Git - flightgear.git/blob - src/Environment/environment_ctrl.cxx
e5114a2a25377e45f5f013dd91700678dbbd7354
[flightgear.git] / src / Environment / environment_ctrl.cxx
1 // environment_ctrl.cxx -- manager for natural environment information.
2 //
3 // Written by David Megginson, started February 2002.
4 //
5 // Copyright (C) 2002  David Megginson - david@megginson.com
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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23 #include <simgear/debug/logstream.hxx>
24
25 #include <stdlib.h>
26 #include <algorithm>
27
28 #include <simgear/structure/commands.hxx>
29 #include <simgear/structure/exception.hxx>
30
31 #include <Airports/simple.hxx>
32 #include <Main/fg_props.hxx>
33 #include <Main/util.hxx>
34
35 #include "environment_mgr.hxx"
36 #include "environment_ctrl.hxx"
37
38 SG_USING_STD(sort);
39
40
41 \f
42 ////////////////////////////////////////////////////////////////////////
43 // Implementation of FGEnvironmentCtrl abstract base class.
44 ////////////////////////////////////////////////////////////////////////
45
46 FGEnvironmentCtrl::FGEnvironmentCtrl ()
47   : _environment(0),
48     _lon_deg(0),
49     _lat_deg(0),
50     _elev_ft(0)
51 {
52 }
53
54 FGEnvironmentCtrl::~FGEnvironmentCtrl ()
55 {
56 }
57
58 void
59 FGEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
60 {
61   _environment = environment;
62 }
63
64 void
65 FGEnvironmentCtrl::setLongitudeDeg (double lon_deg)
66 {
67   _lon_deg = lon_deg;
68 }
69
70 void
71 FGEnvironmentCtrl::setLatitudeDeg (double lat_deg)
72 {
73   _lat_deg = lat_deg;
74 }
75
76 void
77 FGEnvironmentCtrl::setElevationFt (double elev_ft)
78 {
79   _elev_ft = elev_ft;
80 }
81
82 void
83 FGEnvironmentCtrl::setPosition (double lon_deg, double lat_deg, double elev_ft)
84 {
85   _lon_deg = lon_deg;
86   _lat_deg = lat_deg;
87   _elev_ft = elev_ft;
88 }
89
90
91 \f
92 ////////////////////////////////////////////////////////////////////////
93 // Implementation of FGUserDefEnvironmentCtrl.
94 ////////////////////////////////////////////////////////////////////////
95
96 FGUserDefEnvironmentCtrl::FGUserDefEnvironmentCtrl ()
97   : _base_wind_speed_node(0),
98     _gust_wind_speed_node(0),
99     _current_wind_speed_kt(0),
100     _delta_wind_speed_kt(0)
101 {
102 }
103
104 FGUserDefEnvironmentCtrl::~FGUserDefEnvironmentCtrl ()
105 {
106 }
107
108 void
109 FGUserDefEnvironmentCtrl::init ()
110 {
111                                 // Fill in some defaults.
112   if (!fgHasNode("/environment/params/base-wind-speed-kt"))
113     fgSetDouble("/environment/params/base-wind-speed-kt",
114                 fgGetDouble("/environment/wind-speed-kt"));
115   if (!fgHasNode("/environment/params/gust-wind-speed-kt"))
116     fgSetDouble("/environment/params/gust-wind-speed-kt",
117                 fgGetDouble("/environment/params/base-wind-speed-kt"));
118
119   _base_wind_speed_node =
120     fgGetNode("/environment/params/base-wind-speed-kt", true);
121   _gust_wind_speed_node =
122     fgGetNode("/environment/params/gust-wind-speed-kt", true);
123
124   _current_wind_speed_kt = _base_wind_speed_node->getDoubleValue();
125   _delta_wind_speed_kt = 0.1;
126 }
127
128 void
129 FGUserDefEnvironmentCtrl::update (double dt)
130 {
131   double base_wind_speed = _base_wind_speed_node->getDoubleValue();
132   double gust_wind_speed = _gust_wind_speed_node->getDoubleValue();
133
134   if (gust_wind_speed < base_wind_speed) {
135       gust_wind_speed = base_wind_speed;
136       _gust_wind_speed_node->setDoubleValue(gust_wind_speed);
137   }
138
139   if (base_wind_speed == gust_wind_speed) {
140     _current_wind_speed_kt = base_wind_speed;
141   } else {
142     int rn = rand() % 128;
143     int sign = (_delta_wind_speed_kt < 0 ? -1 : 1);
144     double gust = _current_wind_speed_kt - base_wind_speed;
145     double incr = gust / 50;
146
147     if (rn == 0)
148       _delta_wind_speed_kt = - _delta_wind_speed_kt;
149     else if (rn < 4)
150       _delta_wind_speed_kt -= incr * sign;
151     else if (rn < 16)
152       _delta_wind_speed_kt += incr * sign;
153
154     _current_wind_speed_kt += _delta_wind_speed_kt;
155
156     if (_current_wind_speed_kt < base_wind_speed) {
157       _current_wind_speed_kt = base_wind_speed;
158       _delta_wind_speed_kt = 0.01;
159     } else if (_current_wind_speed_kt > gust_wind_speed) {
160       _current_wind_speed_kt = gust_wind_speed;
161       _delta_wind_speed_kt = -0.01;
162     }
163   }
164   
165   if (_environment != 0)
166     _environment->set_wind_speed_kt(_current_wind_speed_kt);
167 }
168
169
170 \f
171 ////////////////////////////////////////////////////////////////////////
172 // Implementation of FGInterpolateEnvironmentCtrl.
173 ////////////////////////////////////////////////////////////////////////
174
175 FGInterpolateEnvironmentCtrl::FGInterpolateEnvironmentCtrl ()
176 {
177 }
178
179 FGInterpolateEnvironmentCtrl::~FGInterpolateEnvironmentCtrl ()
180 {
181     unsigned int i;
182     for (i = 0; i < _boundary_table.size(); i++)
183         delete _boundary_table[i];
184     for (i = 0; i < _aloft_table.size(); i++)
185         delete _aloft_table[i];
186 }
187
188
189
190 void
191 FGInterpolateEnvironmentCtrl::init ()
192 {
193     read_table(fgGetNode("/environment/config/boundary", true),
194                _boundary_table);
195     read_table(fgGetNode("/environment/config/aloft", true),
196                _aloft_table);
197 }
198
199 void
200 FGInterpolateEnvironmentCtrl::reinit ()
201 {
202     unsigned int i;
203     for (i = 0; i < _boundary_table.size(); i++)
204         delete _boundary_table[i];
205     for (i = 0; i < _aloft_table.size(); i++)
206         delete _aloft_table[i];
207     _boundary_table.clear();
208     _aloft_table.clear();
209     init();
210 }
211
212 void
213 FGInterpolateEnvironmentCtrl::read_table (const SGPropertyNode * node,
214                                           vector<bucket *> &table)
215 {
216     for (int i = 0; i < node->nChildren(); i++) {
217         const SGPropertyNode * child = node->getChild(i);
218         if ( strcmp(child->getName(), "entry") == 0
219              && child->getStringValue("elevation-ft", "")[0] != '\0'
220              && ( child->getDoubleValue("elevation-ft") > 0.1 || i == 0 ) )
221         {
222             bucket * b = new bucket;
223             if (i > 0)
224                 b->environment.copy(table[i-1]->environment);
225             b->environment.read(child);
226             b->altitude_ft = b->environment.get_elevation_ft();
227             table.push_back(b);
228         }
229     }
230     sort(table.begin(), table.end());
231 }
232
233 void
234 FGInterpolateEnvironmentCtrl::update (double delta_time_sec)
235 {
236                                 // FIXME
237     double altitude_ft = fgGetDouble("/position/altitude-ft");
238     double altitude_agl_ft = fgGetDouble("/position/altitude-agl-ft");
239     double boundary_transition =
240         fgGetDouble("/environment/config/boundary-transition-ft", 500);
241
242     // double ground_elevation_ft = altitude_ft - altitude_agl_ft;
243
244     int length = _boundary_table.size();
245
246     if (length > 0) {
247                                 // boundary table
248         double boundary_limit = _boundary_table[length-1]->altitude_ft;
249         if (boundary_limit >= altitude_agl_ft) {
250             do_interpolate(_boundary_table, altitude_agl_ft,
251                            _environment);
252             return;
253         } else if ((boundary_limit + boundary_transition) >= altitude_agl_ft) {
254                                 // both tables
255             do_interpolate(_boundary_table, altitude_agl_ft, &env1);
256             do_interpolate(_aloft_table, altitude_ft, &env2);
257             double fraction =
258                 (altitude_agl_ft - boundary_limit) / boundary_transition;
259             interpolate(&env1, &env2, fraction, _environment);
260             return;
261         }
262     }
263
264                                 // aloft table
265     do_interpolate(_aloft_table, altitude_ft, _environment);
266 }
267
268 void
269 FGInterpolateEnvironmentCtrl::do_interpolate (vector<bucket *> &table,
270                                               double altitude_ft,
271                                               FGEnvironment * environment)
272 {
273     int length = table.size();
274     if (length == 0)
275         return;
276
277                                 // Boundary conditions
278     if ((length == 1) || (table[0]->altitude_ft >= altitude_ft)) {
279         environment->copy(table[0]->environment);
280         return;
281     } else if (table[length-1]->altitude_ft <= altitude_ft) {
282         environment->copy(table[length-1]->environment);
283         return;
284     }
285         
286                                 // Search the interpolation table
287     for (int i = 0; i < length - 1; i++) {
288         if ((i == length - 1) || (table[i]->altitude_ft <= altitude_ft)) {
289                 FGEnvironment * env1 = &(table[i]->environment);
290                 FGEnvironment * env2 = &(table[i+1]->environment);
291                 double fraction;
292                 if (table[i]->altitude_ft == table[i+1]->altitude_ft)
293                     fraction = 1.0;
294                 else
295                     fraction =
296                         ((altitude_ft - table[i]->altitude_ft) /
297                          (table[i+1]->altitude_ft - table[i]->altitude_ft));
298                 interpolate(env1, env2, fraction, environment);
299
300                 return;
301         }
302     }
303 }
304
305 bool
306 FGInterpolateEnvironmentCtrl::bucket::operator< (const bucket &b) const
307 {
308     return (altitude_ft < b.altitude_ft);
309 }
310
311
312 \f
313 ////////////////////////////////////////////////////////////////////////
314 // Implementation of FGMetarEnvironmentCtrl.
315 ////////////////////////////////////////////////////////////////////////
316
317 FGMetarEnvironmentCtrl::FGMetarEnvironmentCtrl ()
318     : env( new FGInterpolateEnvironmentCtrl ),
319       _icao( fgGetString("/sim/presets/airport-id") ),
320       search_interval_sec( 60.0 ),        // 1 minute
321       same_station_interval_sec( 900.0 ), // 15 minutes
322       search_elapsed( 9999.0 ),
323       fetch_elapsed( 9999.0 ),
324       proxy_host( fgGetNode("/sim/presets/proxy/host", true) ),
325       proxy_port( fgGetNode("/sim/presets/proxy/port", true) ),
326       proxy_auth( fgGetNode("/sim/presets/proxy/authentication", true) )
327 {
328 #ifdef ENABLE_THREADS
329     thread = new MetarThread(this);
330     thread->start();
331 #endif // ENABLE_THREADS
332 }
333
334 FGMetarEnvironmentCtrl::~FGMetarEnvironmentCtrl ()
335 {
336 #ifdef ENABLE_THREADS
337    thread->cancel();
338    thread->join();
339 #endif // ENABLE_THREADS
340
341    delete env;
342    env = NULL;
343 }
344
345
346 // use a "command" to set station temp at station elevation
347 static void set_temp_at_altitude( float temp_degc, float altitude_ft ) {
348     SGPropertyNode args;
349     SGPropertyNode *node = args.getNode("temp-degc", 0, true);
350     node->setFloatValue( temp_degc );
351     node = args.getNode("altitude-ft", 0, true);
352     node->setFloatValue( altitude_ft );
353     globals->get_commands()->execute("set-outside-air-temp-degc", &args);
354 }
355
356
357 static void set_dewpoint_at_altitude( float dewpoint_degc, float altitude_ft ) {
358     SGPropertyNode args;
359     SGPropertyNode *node = args.getNode("dewpoint-degc", 0, true);
360     node->setFloatValue( dewpoint_degc );
361     node = args.getNode("altitude-ft", 0, true);
362     node->setFloatValue( altitude_ft );
363     globals->get_commands()->execute("set-dewpoint-temp-degc", &args);
364 }
365
366
367 void
368 FGMetarEnvironmentCtrl::update_env_config ()
369 {
370     fgSetupWind( fgGetDouble("/environment/metar/base-wind-range-from"),
371                  fgGetDouble("/environment/metar/base-wind-range-to"),
372                  fgGetDouble("/environment/metar/base-wind-speed-kt"),
373                  fgGetDouble("/environment/metar/gust-wind-speed-kt") );
374
375     fgDefaultWeatherValue( "visibility-m",
376                            fgGetDouble("/environment/metar/min-visibility-m") );
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     fgDefaultWeatherValue( "pressure-sea-level-inhg",
382                            fgGetDouble("/environment/metar/pressure-inhg") );
383 }
384
385 void
386 FGMetarEnvironmentCtrl::init ()
387 {
388     const SGPropertyNode *longitude
389         = fgGetNode( "/position/longitude-deg", true );
390     const SGPropertyNode *latitude
391         = fgGetNode( "/position/latitude-deg", true );
392
393     bool found_metar = false;
394     while ( !found_metar ) {
395         FGAirport a = globals->get_airports()
396             ->search( longitude->getDoubleValue(),
397                       latitude->getDoubleValue(),
398                       true );
399         if ( fetch_data( a.id ) ) {
400             cout << "closest station w/ metar = " << a.id << endl;
401             last_apt = a;
402             _icao = a.id;
403             search_elapsed = 0.0;
404             fetch_elapsed = 0.0;
405             update_env_config();
406             env->init();
407             found_metar = true;
408         } else {
409             // mark as no metar so it doesn't show up in subsequent
410             // searches.
411             cout << "no metar at metar = " << a.id << endl;
412             globals->get_airports()->no_metar( a.id );
413         }
414     }
415 }
416
417 void
418 FGMetarEnvironmentCtrl::reinit ()
419 {
420 #if 0
421     update_env_config();
422 #endif
423
424     env->reinit();
425 }
426
427 void
428 FGMetarEnvironmentCtrl::update(double delta_time_sec)
429 {
430     static const SGPropertyNode *longitude
431         = fgGetNode( "/position/longitude-deg", true );
432     static const SGPropertyNode *latitude
433         = fgGetNode( "/position/latitude-deg", true );
434     search_elapsed += delta_time_sec;
435     fetch_elapsed += delta_time_sec;
436     if ( search_elapsed > search_interval_sec ) {
437         FGAirport a = globals->get_airports()
438             ->search( longitude->getDoubleValue(),
439                       latitude->getDoubleValue(),
440                       true );
441         if ( last_apt.id != a.id
442              || fetch_elapsed > same_station_interval_sec )
443         {
444             if ( fetch_data( a.id ) ) {
445                 cout << "closest station w/ metar = " << a.id << endl;
446                 last_apt = a;
447                 _icao = a.id;
448                 search_elapsed = 0.0;
449                 fetch_elapsed = 0.0;
450                 update_env_config();
451                 env->reinit();
452             } else {
453                 // mark as no metar so it doesn't show up in subsequent
454                 // searches.
455                 cout << "no metar at metar = " << a.id << endl;
456                 globals->get_airports()->no_metar( a.id );
457             }
458         } else {
459             search_elapsed = 0.0;
460             // cout << "same station, waiting = "
461             //      << same_station_interval_sec - fetch_elapsed << endl;
462         }
463     }
464
465     env->update(delta_time_sec);
466 }
467
468 void
469 FGMetarEnvironmentCtrl::setEnvironment (FGEnvironment * environment)
470 {
471     env->setEnvironment(environment);
472 }
473
474 bool
475 FGMetarEnvironmentCtrl::fetch_data (const string &icao)
476 {
477     char s[128];
478     double d, dt;
479     int i;
480
481     if ((icao == "") && (_icao == "")) {
482         _icao = fgGetString("/sim/presets/airport-id");
483
484     } else if (icao != "") {
485         _icao = icao;
486     }
487
488     // fetch station elevation if exists
489     FGAirport a = globals->get_airports()->search( _icao );
490     station_elevation_ft = a.elevation;
491
492     // fetch current metar data
493     SGMetar *m = NULL;
494 #ifdef ENABLE_THREADS
495
496     // We are only interested in the latest metar report
497     // FIXME: Do we want to keep the latest valid report instead?
498     while (!metar_queue.empty()) {
499  
500         if (m != NULL)
501             delete m;
502
503         m = metar_queue.pop();
504     }
505
506     if ( m != NULL ) {
507
508 #else
509     try {
510         string host = proxy_host->getStringValue();
511         string auth = proxy_auth->getStringValue();
512         string port = proxy_port->getStringValue();
513         m = new SGMetar( _icao, host, port, auth);
514
515 #endif // ENABLE_THREADS
516
517         d = m->getMinVisibility().getVisibility_m();
518         d = (d != SGMetarNaN) ? d : 10000;
519         fgSetDouble("/environment/metar/min-visibility-m", d);
520
521         dt =  m->getMaxVisibility().getVisibility_m();
522         d = (dt != SGMetarNaN) ? dt : d;
523         fgSetDouble("/environment/metar/max-visibility-m", d);
524
525         SGMetarVisibility *dirvis = m->getDirVisibility();
526         for (i = 0; i < 8; i++, dirvis++) {
527             const char *min = "/environment/metar/visibility[%d]/min-m";
528             const char *max = "/environment/metar/visibility[%d]/max-m";
529             char s[128];
530
531             d = dirvis->getVisibility_m();
532             d = (d != SGMetarNaN) ? d : 10000;
533
534             snprintf(s, 128, min, i);
535             fgSetDouble(s, d);
536             snprintf(s, 128, max, i);
537             fgSetDouble(s, d);
538         }
539
540         i = m->getWindDir();
541         if ( i == -1 ) {
542             fgSetInt("/environment/metar/base-wind-range-from",
543                         m->getWindRangeFrom() );
544             fgSetInt("/environment/metar/base-wind-range-to",
545                         m->getWindRangeTo() );
546         } else {
547             fgSetInt("/environment/metar/base-wind-range-from", i);
548             fgSetInt("/environment/metar/base-wind-range-to", i);
549         }
550         fgSetDouble("/environment/metar/base-wind-speed-kt",
551                     m->getWindSpeed_kt() );
552
553         d = m->getGustSpeed_kt();
554         d = (d != SGMetarNaN) ? d : 0.0;
555         fgSetDouble("/environment/metar/gust-wind-speed-kt", d);
556
557         d = m->getTemperature_C();
558         if (d != SGMetarNaN) {
559             dt = m->getDewpoint_C();
560             dt = (dt != SGMetarNaN) ? dt : 0.0;
561             fgSetDouble("/environment/metar/dewpoint-degc", dt);
562             fgSetDouble("/environment/metar/rel-humidity-norm",
563                         m->getRelHumidity() );
564         }   
565         d = (d != SGMetarNaN) ? d : 15.0;
566         fgSetDouble("/environment/metar/temperature-degc", d);
567
568         d = m->getPressure_inHg();
569         d = (d != SGMetarNaN) ? d : 30.0;
570         fgSetDouble("/environment/metar/pressure-inhg", d);
571
572         vector<SGMetarCloud> cv = m->getClouds();
573         vector<SGMetarCloud>::iterator cloud;
574
575         const char *cl = "/environment/clouds/layer[%i]";
576         for (i = 0, cloud = cv.begin(); cloud != cv.end(); cloud++, i++) {
577             const char *coverage_string[5] = 
578                           { "clear", "few", "scattered", "broken", "overcast" };
579             const double thickness[5] = { 0, 65, 600,750, 1000};
580             int q;
581
582             snprintf(s, 128, cl, i);
583             strncat(s, "/coverage", 128);
584             q = cloud->getCoverage();
585             q = (q != -1 ) ? q : 0;
586             fgSetString(s, coverage_string[q] );
587
588             snprintf(s, 128, cl, i);
589             strncat(s, "/elevation-ft", 128);
590             d = cloud->getAltitude_ft();
591             d = (d != SGMetarNaN) ? d : -9999;
592             fgSetDouble(s, d + station_elevation_ft);
593
594             snprintf(s, 128, cl, i);
595             strncat(s, "/thickness-ft", 128);
596             fgSetDouble(s, thickness[q]);
597
598             snprintf(s, 128, cl, i);
599             strncat(s, "/span-m", 128);
600             fgSetDouble(s, 40000.0);
601         }
602         for (; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
603             snprintf(s, 128, cl, i);
604             strncat(s, "/coverage", 128);
605             fgSetString(s, "clear");
606
607             snprintf(s, 128, cl, i);
608             strncat(s, "/elevation-ft", 128);
609             fgSetDouble(s, -9999);
610
611             snprintf(s, 128, cl, i);
612             strncat(s, "/thickness-ft", 128);
613             fgSetDouble(s, 0);
614
615             snprintf(s, 128, cl, i);
616             strncat(s, "/span-m", 128);
617             fgSetDouble(s, 40000.0);
618         }
619
620         delete m;
621
622     }
623 #ifdef ENABLE_THREADS
624
625     mutex.lock();
626     metar_cond.signal();
627     mutex.unlock();
628
629     if (m == NULL)
630         return false;
631
632 #else
633     catch (const sg_io_exception& e) {
634         SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
635                                       << e.getFormattedMessage().c_str() );
636         return false;
637     }
638 #endif // ENABLE_THREADS
639
640     return true;
641 }
642
643 #ifdef ENABLE_THREADS
644 /**
645  *
646  */
647 void
648 FGMetarEnvironmentCtrl::MetarThread::run()
649 {
650     SGMetar *m = NULL;
651
652     // pthread_cleanup_push( metar_cleanup_handler, fetcher );
653     while ( true )
654     {
655         set_cancel( SGThread::CANCEL_DISABLE );
656         try
657         {
658             cout << "Fetching ..." << endl;
659             // if (m != NULL)  m = NULL;
660             string host = fetcher->proxy_host->getStringValue();
661             string auth = fetcher->proxy_auth->getStringValue();
662             string port = fetcher->proxy_port->getStringValue();
663             m = new SGMetar( fetcher->_icao, host, port, auth );
664
665         } catch (const sg_io_exception& e) {
666             // SG_LOG( SG_GENERAL, SG_WARN, "Error fetching live weather data: "
667             //                             << e.getFormattedMessage().c_str() );
668             m = NULL;
669         }
670         set_cancel( SGThread::CANCEL_DEFERRED );
671
672         fetcher->metar_queue.push( m );
673
674         // Wait for the next frame signal before we fetch the next metar data
675         fetcher->mutex.lock();
676         fetcher->metar_cond.wait( fetcher->mutex );
677         fetcher->mutex.unlock();
678     }
679     // pthread_cleanup_pop(1);
680 }
681
682 /**
683  * Ensure mutex is unlocked.
684  */
685 void
686 metar_cleanup_handler( void* arg )
687 {
688     FGMetarEnvironmentCtrl* fetcher = (FGMetarEnvironmentCtrl*) arg;
689     fetcher->mutex.unlock();
690 }
691 #endif // ENABLE_THREADS
692
693
694 // end of environment_ctrl.cxx