]> git.mxchange.org Git - flightgear.git/blob - src/Main/positioninit.cxx
Issue #809, restructure position init code.
[flightgear.git] / src / Main / positioninit.cxx
1 // positioninit.cxx - helpers relating to setting initial aircraft position
2 //
3 // Copyright (C) 2012 James Turner  zakalawe@mac.com
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #include "positioninit.hxx"
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 // simgear
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28
29 #include "globals.hxx"
30 #include "fg_props.hxx"
31
32 #include <Navaids/navlist.hxx>
33 #include <Airports/runways.hxx>
34 #include <Airports/simple.hxx>
35 #include <Airports/dynamics.hxx>
36 #include <AIModel/AIManager.hxx>
37
38 using std::endl;
39
40 namespace flightgear
41 {
42     
43 /// to avoid blocking when metar-fetch is enabled, but the network is
44 /// unresponsive, we need a timeout value. This value is reset on initPosition,
45 /// and tracked through each call to finalizePosition.
46 static SGTimeStamp global_finalizeTime;
47   
48 // Set current tower position lon/lat given an airport id
49 static bool fgSetTowerPosFromAirportID( const string& id) {
50   const FGAirport *a = fgFindAirportID( id);
51   if (a) {
52     SGGeod tower = a->getTowerLocation();
53     fgSetDouble("/sim/tower/longitude-deg",  tower.getLongitudeDeg());
54     fgSetDouble("/sim/tower/latitude-deg",  tower.getLatitudeDeg());
55     fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
56     return true;
57   } else {
58     return false;
59   }
60   
61 }
62
63 struct FGTowerLocationListener : SGPropertyChangeListener {
64   void valueChanged(SGPropertyNode* node) {
65     string id(node->getStringValue());
66     if (fgGetBool("/sim/tower/auto-position",true))
67     {
68       // enforce using closest airport when auto-positioning is enabled
69       const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
70       if (closest_airport && (id != closest_airport))
71       {
72         id = closest_airport;
73         node->setStringValue(id);
74       }
75     }
76     fgSetTowerPosFromAirportID(id);
77   }
78 };
79
80 struct FGClosestTowerLocationListener : SGPropertyChangeListener
81 {
82   void valueChanged(SGPropertyNode* )
83   {
84     // closest airport has changed
85     if (fgGetBool("/sim/tower/auto-position",true))
86     {
87       // update tower position
88       const char* id = fgGetString("/sim/airport/closest-airport-id", "");
89       if (id && *id!=0)
90         fgSetString("/sim/tower/airport-id", id);
91     }
92   }
93 };
94
95 void initTowerLocationListener() {
96   fgGetNode("/sim/tower/airport-id",  true)
97   ->addChangeListener( new FGTowerLocationListener(), true );
98   FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
99   fgGetNode("/sim/airport/closest-airport-id", true)
100   ->addChangeListener(ntcl , true );
101   fgGetNode("/sim/tower/auto-position", true)
102   ->addChangeListener(ntcl, true );
103 }
104
105 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
106 {
107   SGGeod startPos(aStartPos);
108   if (aTargetHeading == HUGE_VAL) {
109     aTargetHeading = aHeading;
110   }
111   
112   if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
113     double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
114     offsetDistance *= SG_NM_TO_METER;
115     double offsetAzimuth = aHeading;
116     if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
117       offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
118       aHeading = aTargetHeading;
119     }
120     
121     SGGeod offset;
122     double az2; // dummy
123     SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
124     startPos = offset;
125   }
126   
127   // presets
128   fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
129   fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
130   fgSetDouble("/sim/presets/heading-deg", aHeading );
131   
132   // other code depends on the actual values being set ...
133   fgSetDouble("/position/longitude-deg",  startPos.getLongitudeDeg() );
134   fgSetDouble("/position/latitude-deg",  startPos.getLatitudeDeg() );
135   fgSetDouble("/orientation/heading-deg", aHeading );
136 }
137
138 // Set current_options lon/lat given an airport id and heading (degrees)
139 static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
140   if ( id.empty() )
141     return false;
142   
143   // set initial position from runway and heading
144   SG_LOG( SG_GENERAL, SG_INFO,
145          "Attempting to set starting position from airport code "
146          << id << " heading " << tgt_hdg );
147   
148   const FGAirport* apt = fgFindAirportID(id);
149   if (!apt) return false;
150   FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
151   fgSetString("/sim/atc/runway", r->ident().c_str());
152   
153   SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
154   fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
155   return true;
156 }
157
158 // Set current_options lon/lat given an airport id and parkig position name
159 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
160 {
161   if ( id.empty() )
162     return false;
163   
164   // can't see an easy way around this const_cast at the moment
165   FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
166   if (!apt) {
167     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
168     return false;
169   }
170   FGAirportDynamics* dcs = apt->getDynamics();
171   if (!dcs) {
172     SG_LOG( SG_GENERAL, SG_ALERT,
173            "Airport " << id << "does not appear to have parking information available");
174     return false;
175   }
176   
177   ParkingAssignment pka;
178   double radius = fgGetDouble("/sim/dimensions/radius-m");
179   if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
180     string fltType;
181     string acOperator;
182     SGPath acData;
183     try {
184       acData = globals->get_fg_home();
185       acData.append("aircraft-data");
186       string acfile = fgGetString("/sim/aircraft") + string(".xml");
187       acData.append(acfile);
188       SGPropertyNode root;
189       readProperties(acData.str(), &root);
190       SGPropertyNode * node = root.getNode("sim");
191       fltType    = node->getStringValue("aircraft-class", "NONE"     );
192       acOperator = node->getStringValue("aircraft-operator", "NONE"     );
193     } catch (const sg_exception &) {
194       SG_LOG(SG_GENERAL, SG_INFO,
195              "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
196       
197       // cout << path.str() << endl;
198     }
199     if (fltType.empty() || fltType == "NONE") {
200       SG_LOG(SG_GENERAL, SG_INFO,
201              "Aircraft type information not found in: " << acData.str() << ". Using default value");
202       fltType = fgGetString("/sim/aircraft-class"   );
203     }
204     if (acOperator.empty() || fltType == "NONE") {
205       SG_LOG(SG_GENERAL, SG_INFO,
206              "Aircraft operator information not found in: " << acData.str() << ". Using default value");
207       acOperator = fgGetString("/sim/aircraft-operator"   );
208     }
209     
210     string acType; // Currently not used by findAvailable parking, so safe to leave empty.
211     pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
212     if (pka.isValid()) {
213       fgGetString("/sim/presets/parkpos");
214       fgSetString("/sim/presets/parkpos", pka.parking()->getName());
215     } else {
216       SG_LOG( SG_GENERAL, SG_ALERT,
217              "Failed to find a suitable parking at airport " << id );
218       return false;
219     }
220   } else {
221     pka = dcs->getParkingByName(parkpos);
222     if (!pka.isValid()) {
223       SG_LOG( SG_GENERAL, SG_ALERT,
224                "Failed to find a parking at airport " << id << ":" << parkpos);
225       return false;
226     }
227   }
228   
229   fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
230   return true;
231 }
232
233
234 // Set current_options lon/lat given an airport id and runway number
235 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
236   if ( id.empty() )
237     return false;
238   
239   // set initial position from airport and runway number
240   SG_LOG( SG_GENERAL, SG_INFO,
241          "Attempting to set starting position for "
242          << id << ":" << rwy );
243   
244   const FGAirport* apt = fgFindAirportID(id);
245   if (!apt) {
246     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
247     return false;
248   }
249   
250   if (!apt->hasRunwayWithIdent(rwy)) {
251     SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
252            "Failed to find runway " << rwy <<
253            " at airport " << id << ". Using default runway." );
254     return false;
255   }
256   
257   FGRunway* r(apt->getRunwayByIdent(rwy));
258   fgSetString("/sim/atc/runway", r->ident().c_str());
259   SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
260   fgApplyStartOffset(startPos, r->headingDeg());
261   return true;
262 }
263
264
265 static void fgSetDistOrAltFromGlideSlope() {
266   // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
267   string apt_id = fgGetString("/sim/presets/airport-id");
268   double gs = fgGetDouble("/sim/presets/glideslope-deg")
269   * SG_DEGREES_TO_RADIANS ;
270   double od = fgGetDouble("/sim/presets/offset-distance-nm");
271   double alt = fgGetDouble("/sim/presets/altitude-ft");
272   
273   double apt_elev = 0.0;
274   if ( ! apt_id.empty() ) {
275     apt_elev = fgGetAirportElev( apt_id );
276     if ( apt_elev < -9990.0 ) {
277       apt_elev = 0.0;
278     }
279   } else {
280     apt_elev = 0.0;
281   }
282   
283   if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
284     // set altitude from glideslope and offset-distance
285     od *= SG_NM_TO_METER * SG_METER_TO_FEET;
286     alt = fabs(od*tan(gs)) + apt_elev;
287     fgSetDouble("/sim/presets/altitude-ft", alt);
288     fgSetBool("/sim/presets/onground", false);
289     SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
290            << alt  << " ft" );
291   } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
292     // set offset-distance from glideslope and altitude
293     od  = (alt - apt_elev) / tan(gs);
294     od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
295     fgSetDouble("/sim/presets/offset-distance-nm", od);
296     fgSetBool("/sim/presets/onground", false);
297     SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
298            << od  << " nm" );
299   } else if( fabs(gs) > 0.01 ) {
300     SG_LOG( SG_GENERAL, SG_ALERT,
301            "Glideslope given but not altitude or offset-distance." );
302     SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
303     fgSetDouble("/sim/presets/glideslope-deg", 0);
304     fgSetBool("/sim/presets/onground", true);
305   }
306 }
307
308
309 // Set current_options lon/lat given an airport id and heading (degrees)
310 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
311 {
312   FGNavList::TypeFilter filter(type);
313   const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
314   
315   if (navlist.size() == 0 ) {
316     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
317            << id << ":" << freq );
318     return false;
319   }
320   
321   if( navlist.size() > 1 ) {
322     std::ostringstream buf;
323     buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
324     for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
325       // NDB stored in kHz, VOR stored in MHz * 100 :-P
326       double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
327       string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
328       buf << (*it)->ident() << " "
329       << std::setprecision(5) << (double)((*it)->get_freq() * factor) << " "
330       << (*it)->get_lat() << "/" << (*it)->get_lon()
331       << endl;
332     }
333     
334     SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
335     return false;
336   }
337   
338   FGNavRecord *nav = navlist[0];
339   fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
340   return true;
341 }
342
343 // Set current_options lon/lat given an aircraft carrier id
344 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
345   
346   // set initial position from runway and heading
347   SGGeod geodPos;
348   double heading;
349   SGVec3d uvw;
350   if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
351     double lon = geodPos.getLongitudeDeg();
352     double lat = geodPos.getLatitudeDeg();
353     double alt = geodPos.getElevationFt();
354     
355     SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
356            << carrier << " at lat = " << lat << ", lon = " << lon
357            << ", alt = " << alt << ", heading = " << heading);
358     
359     fgSetDouble("/sim/presets/longitude-deg",  lon);
360     fgSetDouble("/sim/presets/latitude-deg",  lat);
361     fgSetDouble("/sim/presets/altitude-ft", alt);
362     fgSetDouble("/sim/presets/heading-deg", heading);
363     fgSetDouble("/position/longitude-deg",  lon);
364     fgSetDouble("/position/latitude-deg",  lat);
365     fgSetDouble("/position/altitude-ft", alt);
366     fgSetDouble("/orientation/heading-deg", heading);
367     
368     fgSetString("/sim/presets/speed-set", "UVW");
369     fgSetDouble("/velocities/uBody-fps", uvw(0));
370     fgSetDouble("/velocities/vBody-fps", uvw(1));
371     fgSetDouble("/velocities/wBody-fps", uvw(2));
372     fgSetDouble("/sim/presets/uBody-fps", uvw(0));
373     fgSetDouble("/sim/presets/vBody-fps", uvw(1));
374     fgSetDouble("/sim/presets/wBody-fps", uvw(2));
375     
376     fgSetBool("/sim/presets/onground", true);
377     
378     return true;
379   } else {
380     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
381            << carrier );
382     return false;
383   }
384 }
385
386 // Set current_options lon/lat given an airport id and heading (degrees)
387 static bool fgSetPosFromFix( const string& id )
388 {
389   FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
390   FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
391   if (!fix) {
392     SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
393     return false;
394   }
395   
396   fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
397   return true;
398 }
399
400 // Set the initial position based on presets (or defaults)
401 bool initPosition()
402 {
403   global_finalizeTime = SGTimeStamp(); // reset to invalid
404   
405   double gs = fgGetDouble("/sim/presets/glideslope-deg")
406   * SG_DEGREES_TO_RADIANS ;
407   double od = fgGetDouble("/sim/presets/offset-distance-nm");
408   double alt = fgGetDouble("/sim/presets/altitude-ft");
409   
410   bool set_pos = false;
411   
412   // If glideslope is specified, then calculate offset-distance or
413   // altitude relative to glide slope if either of those was not
414   // specified.
415   if ( fabs( gs ) > 0.01 ) {
416     fgSetDistOrAltFromGlideSlope();
417   }
418   
419   
420   // If we have an explicit, in-range lon/lat, don't change it, just use it.
421   // If not, check for an airport-id and use that.
422   // If not, default to the middle of the KSFO field.
423   // The default values for lon/lat are deliberately out of range
424   // so that the airport-id can take effect; valid lon/lat will
425   // override airport-id, however.
426   double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
427   double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
428   if ( lon_deg >= -180.0 && lon_deg <= 180.0
429       && lat_deg >= -90.0 && lat_deg <= 90.0 )
430   {
431     set_pos = true;
432   }
433   
434   string apt = fgGetString("/sim/presets/airport-id");
435   string rwy_no = fgGetString("/sim/presets/runway");
436   bool rwy_req = fgGetBool("/sim/presets/runway-requested");
437   string vor = fgGetString("/sim/presets/vor-id");
438   double vor_freq = fgGetDouble("/sim/presets/vor-freq");
439   string ndb = fgGetString("/sim/presets/ndb-id");
440   double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
441   string carrier = fgGetString("/sim/presets/carrier");
442   string parkpos = fgGetString("/sim/presets/parkpos");
443   string fix = fgGetString("/sim/presets/fix");
444   SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
445   double hdg = hdg_preset->getDoubleValue();
446   
447   // save some start parameters, so that we can later say what the
448   // user really requested. TODO generalize that and move it to options.cxx
449   static bool start_options_saved = false;
450   if (!start_options_saved) {
451     start_options_saved = true;
452     SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
453     
454     opt->setDoubleValue("latitude-deg", lat_deg);
455     opt->setDoubleValue("longitude-deg", lon_deg);
456     opt->setDoubleValue("heading-deg", hdg);
457     opt->setStringValue("airport", apt.c_str());
458     opt->setStringValue("runway", rwy_no.c_str());
459   }
460   
461   if (hdg > 9990.0)
462     hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
463   
464   if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
465     // An airport + parking position is requested
466     if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
467       // set tower position
468       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
469       fgSetString("/sim/tower/airport-id",  apt.c_str());
470       set_pos = true;
471     }
472   }
473   
474   if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
475     // An airport + runway is requested
476     if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
477       // set tower position (a little off the heading for single
478       // runway airports)
479       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
480       fgSetString("/sim/tower/airport-id",  apt.c_str());
481       set_pos = true;
482     }
483   }
484   
485   if ( !set_pos && !apt.empty() ) {
486     // An airport is requested (find runway closest to hdg)
487     if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
488       // set tower position (a little off the heading for single
489       // runway airports)
490       fgSetString("/sim/airport/closest-airport-id",  apt.c_str());
491       fgSetString("/sim/tower/airport-id",  apt.c_str());
492       set_pos = true;
493     }
494   }
495   
496   if (hdg_preset->getDoubleValue() > 9990.0)
497     hdg_preset->setDoubleValue(hdg);
498   
499   if ( !set_pos && !vor.empty() ) {
500     // a VOR is requested
501     if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
502       set_pos = true;
503     }
504   }
505   
506   if ( !set_pos && !ndb.empty() ) {
507     // an NDB is requested
508     if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
509       set_pos = true;
510     }
511   }
512   
513   if ( !set_pos && !carrier.empty() ) {
514     // an aircraft carrier is requested
515     if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
516       set_pos = true;
517     }
518   }
519   
520   if ( !set_pos && !fix.empty() ) {
521     // a Fix is requested
522     if ( fgSetPosFromFix( fix ) ) {
523       set_pos = true;
524     }
525   }
526   
527   if ( !set_pos ) {
528     // No lon/lat specified, no airport specified, default to
529     // middle of KSFO field.
530     fgSetDouble("/sim/presets/longitude-deg", -122.374843);
531     fgSetDouble("/sim/presets/latitude-deg", 37.619002);
532   }
533   
534   fgSetDouble( "/position/longitude-deg",
535               fgGetDouble("/sim/presets/longitude-deg") );
536   fgSetDouble( "/position/latitude-deg",
537               fgGetDouble("/sim/presets/latitude-deg") );
538   fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
539   
540   // determine if this should be an on-ground or in-air start
541   if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
542     fgSetBool("/sim/presets/onground", false);
543   } else {
544     fgSetBool("/sim/presets/onground", true);
545   }
546   
547   return true;
548 }
549   
550 bool finalizePosition()
551 {
552   // first call to finalize after an initPosition call
553   if (global_finalizeTime.get_usec() == 0) {
554     global_finalizeTime = SGTimeStamp::now();
555   }
556   
557     /* Scenarios require Nasal, so FGAIManager loads the scenarios,
558      * including its models such as a/c carriers, in its 'postinit',
559      * which is the very last thing we do.
560      * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
561      * one of the first things we do, long before scenarios/carriers are
562      * loaded. => When requested "initial preset position" relates to a
563      * carrier, recalculate the 'initial' position here 
564      */
565     std::string carrier = fgGetString("/sim/presets/carrier","");
566     if (!carrier.empty())
567     {
568         SG_LOG(SG_GENERAL, SG_INFO, "finalizePositioned: re-init-ing position on carrier");
569         // clear preset location and re-trigger position setup
570         fgSetDouble("/sim/presets/longitude-deg", 9999);
571         fgSetDouble("/sim/presets/latitude-deg", 9999);
572         return initPosition();
573     }
574
575     double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
576     string apt = fgGetString( "/sim/startup/options/airport" );
577     string rwy = fgGetString( "/sim/startup/options/runway" );
578     double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
579     string parkpos = fgGetString( "/sim/presets/parkpos" );
580     bool onground = fgGetBool( "/sim/presets/onground", false );
581 // this logic is taken from former startup.nas
582     bool needMetar = (hdg < 360.0) && !apt.empty() && (strthdg > 360.0) &&
583         rwy.empty() && onground && parkpos.empty();
584     
585     if (needMetar) {
586       // timeout so we don't spin forever if the network is down
587       if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 5000)) {
588         SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
589         return true;
590       }
591     
592       if (!fgGetBool( "/environment/metar/valid" )) {
593         // bit hacky - run these two subsystems. We can't run the whole
594         // lot since some view things aren't initialised and hence FGLight
595         // crashes.
596         globals->get_subsystem("http")->update(0.0);
597         globals->get_subsystem("environment")->update(0.0);
598         return false;
599       }
600       
601       SG_LOG(SG_ENVIRONMENT, SG_INFO,
602              "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
603       setPosFromAirportIDandHdg( apt, hdg );
604         // fall through to return true
605     } // of need-metar case
606     
607     return true;
608 }
609     
610 } // of namespace flightgear