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