1 // positioninit.cxx - helpers relating to setting initial aircraft position
3 // Copyright (C) 2012 James Turner zakalawe@mac.com
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.
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.
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.
19 #include "positioninit.hxx"
26 #include <simgear/props/props_io.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/structure/event_mgr.hxx>
30 #include "globals.hxx"
31 #include "fg_props.hxx"
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>
45 /// to avoid blocking when metar-fetch is enabled, but the network is
46 /// unresponsive, we need a timeout value. This value is reset on initPosition,
47 /// and tracked through each call to finalizePosition.
48 static SGTimeStamp global_finalizeTime;
49 static bool global_callbackRegistered = false;
51 static void finalizePosition();
53 // Set current tower position lon/lat given an airport id
54 static bool fgSetTowerPosFromAirportID( const string& id) {
55 const FGAirport *a = fgFindAirportID( id);
57 SGGeod tower = a->getTowerLocation();
58 fgSetDouble("/sim/tower/longitude-deg", tower.getLongitudeDeg());
59 fgSetDouble("/sim/tower/latitude-deg", tower.getLatitudeDeg());
60 fgSetDouble("/sim/tower/altitude-ft", tower.getElevationFt());
68 struct FGTowerLocationListener : SGPropertyChangeListener {
69 void valueChanged(SGPropertyNode* node) {
70 string id(node->getStringValue());
71 if (fgGetBool("/sim/tower/auto-position",true))
73 // enforce using closest airport when auto-positioning is enabled
74 const char* closest_airport = fgGetString("/sim/airport/closest-airport-id", "");
75 if (closest_airport && (id != closest_airport))
78 node->setStringValue(id);
81 fgSetTowerPosFromAirportID(id);
85 struct FGClosestTowerLocationListener : SGPropertyChangeListener
87 void valueChanged(SGPropertyNode* )
89 // closest airport has changed
90 if (fgGetBool("/sim/tower/auto-position",true))
92 // update tower position
93 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
95 fgSetString("/sim/tower/airport-id", id);
100 void initTowerLocationListener() {
101 fgGetNode("/sim/tower/airport-id", true)
102 ->addChangeListener( new FGTowerLocationListener(), true );
103 FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
104 fgGetNode("/sim/airport/closest-airport-id", true)
105 ->addChangeListener(ntcl , true );
106 fgGetNode("/sim/tower/auto-position", true)
107 ->addChangeListener(ntcl, true );
110 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
112 SGGeod startPos(aStartPos);
113 if (aTargetHeading == HUGE_VAL) {
114 aTargetHeading = aHeading;
117 if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
118 double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
119 offsetDistance *= SG_NM_TO_METER;
120 double offsetAzimuth = aHeading;
121 if ( fabs(fgGetDouble("/sim/presets/offset-azimuth-deg")) > SG_EPSILON ) {
122 offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
123 aHeading = aTargetHeading;
128 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
133 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
134 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
135 fgSetDouble("/sim/presets/heading-deg", aHeading );
137 // other code depends on the actual values being set ...
138 fgSetDouble("/position/longitude-deg", startPos.getLongitudeDeg() );
139 fgSetDouble("/position/latitude-deg", startPos.getLatitudeDeg() );
140 fgSetDouble("/orientation/heading-deg", aHeading );
143 // Set current_options lon/lat given an airport id and heading (degrees)
144 static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
148 // set initial position from runway and heading
149 SG_LOG( SG_GENERAL, SG_INFO,
150 "Attempting to set starting position from airport code "
151 << id << " heading " << tgt_hdg );
153 const FGAirport* apt = fgFindAirportID(id);
154 if (!apt) return false;
157 double heading = tgt_hdg;
158 if (apt->type() == FGPositioned::HELIPORT) {
159 if (apt->numHelipads() > 0) {
160 startPos = apt->getHelipadByIndex(0)->geod();
162 startPos = apt->geod();
165 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
166 fgSetString("/sim/atc/runway", r->ident().c_str());
167 startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
168 heading = r->headingDeg();
171 fgApplyStartOffset(startPos, heading, tgt_hdg);
175 // Set current_options lon/lat given an airport id and parkig position name
176 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
181 // can't see an easy way around this const_cast at the moment
182 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
184 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
187 FGAirportDynamics* dcs = apt->getDynamics();
189 SG_LOG( SG_GENERAL, SG_ALERT,
190 "Airport " << id << "does not appear to have parking information available");
194 ParkingAssignment pka;
195 double radius = fgGetDouble("/sim/dimensions/radius-m");
196 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
201 acData = globals->get_fg_home();
202 acData.append("aircraft-data");
203 string acfile = fgGetString("/sim/aircraft") + string(".xml");
204 acData.append(acfile);
206 readProperties(acData.str(), &root);
207 SGPropertyNode * node = root.getNode("sim");
208 fltType = node->getStringValue("aircraft-class", "NONE" );
209 acOperator = node->getStringValue("aircraft-operator", "NONE" );
210 } catch (const sg_exception &) {
211 SG_LOG(SG_GENERAL, SG_INFO,
212 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
214 // cout << path.str() << endl;
216 if (fltType.empty() || fltType == "NONE") {
217 SG_LOG(SG_GENERAL, SG_INFO,
218 "Aircraft type information not found in: " << acData.str() << ". Using default value");
219 fltType = fgGetString("/sim/aircraft-class" );
221 if (acOperator.empty() || fltType == "NONE") {
222 SG_LOG(SG_GENERAL, SG_INFO,
223 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
224 acOperator = fgGetString("/sim/aircraft-operator" );
227 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
228 pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
230 fgGetString("/sim/presets/parkpos");
231 fgSetString("/sim/presets/parkpos", pka.parking()->getName());
233 SG_LOG( SG_GENERAL, SG_ALERT,
234 "Failed to find a suitable parking at airport " << id );
238 pka = dcs->getParkingByName(parkpos);
239 if (!pka.isValid()) {
240 SG_LOG( SG_GENERAL, SG_ALERT,
241 "Failed to find a parking at airport " << id << ":" << parkpos);
246 fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
251 // Set current_options lon/lat given an airport id and runway number
252 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
256 // set initial position from airport and runway number
257 SG_LOG( SG_GENERAL, SG_INFO,
258 "Attempting to set starting position for "
259 << id << ":" << rwy );
261 const FGAirport* apt = fgFindAirportID(id);
263 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
267 if (!apt->hasRunwayWithIdent(rwy)) {
268 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
269 "Failed to find runway " << rwy <<
270 " at airport " << id << ". Using default runway." );
274 FGRunway* r(apt->getRunwayByIdent(rwy));
275 fgSetString("/sim/atc/runway", r->ident().c_str());
276 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
277 fgApplyStartOffset(startPos, r->headingDeg());
282 static void fgSetDistOrAltFromGlideSlope() {
283 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
284 string apt_id = fgGetString("/sim/presets/airport-id");
285 double gs = fgGetDouble("/sim/presets/glideslope-deg")
286 * SG_DEGREES_TO_RADIANS ;
287 double od = fgGetDouble("/sim/presets/offset-distance-nm");
288 double alt = fgGetDouble("/sim/presets/altitude-ft");
290 double apt_elev = 0.0;
291 if ( ! apt_id.empty() ) {
292 apt_elev = fgGetAirportElev( apt_id );
293 if ( apt_elev < -9990.0 ) {
300 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
301 // set altitude from glideslope and offset-distance
302 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
303 alt = fabs(od*tan(gs)) + apt_elev;
304 fgSetDouble("/sim/presets/altitude-ft", alt);
305 fgSetBool("/sim/presets/onground", false);
306 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
308 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
309 // set offset-distance from glideslope and altitude
310 od = (alt - apt_elev) / tan(gs);
311 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
312 fgSetDouble("/sim/presets/offset-distance-nm", od);
313 fgSetBool("/sim/presets/onground", false);
314 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
316 } else if( fabs(gs) > 0.01 ) {
317 SG_LOG( SG_GENERAL, SG_ALERT,
318 "Glideslope given but not altitude or offset-distance." );
319 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
320 fgSetDouble("/sim/presets/glideslope-deg", 0);
321 fgSetBool("/sim/presets/onground", true);
326 // Set current_options lon/lat given an airport id and heading (degrees)
327 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
329 FGNavList::TypeFilter filter(type);
330 const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
332 if (navlist.empty()) {
333 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
334 << id << ":" << freq );
338 if( navlist.size() > 1 ) {
339 std::ostringstream buf;
340 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
341 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
342 // NDB stored in kHz, VOR stored in MHz * 100 :-P
343 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
344 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
345 buf << (*it)->ident() << " "
346 << std::setprecision(5) << (double)((*it)->get_freq() * factor) << " "
347 << (*it)->get_lat() << "/" << (*it)->get_lon()
351 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
355 FGNavRecord *nav = navlist[0];
356 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
360 // Set current_options lon/lat given an aircraft carrier id
361 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
363 // set initial position from runway and heading
367 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
368 double lon = geodPos.getLongitudeDeg();
369 double lat = geodPos.getLatitudeDeg();
370 double alt = geodPos.getElevationFt();
372 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
373 << carrier << " at lat = " << lat << ", lon = " << lon
374 << ", alt = " << alt << ", heading = " << heading);
376 fgSetDouble("/sim/presets/longitude-deg", lon);
377 fgSetDouble("/sim/presets/latitude-deg", lat);
378 fgSetDouble("/sim/presets/altitude-ft", alt);
379 fgSetDouble("/sim/presets/heading-deg", heading);
380 fgSetDouble("/position/longitude-deg", lon);
381 fgSetDouble("/position/latitude-deg", lat);
382 fgSetDouble("/position/altitude-ft", alt);
383 fgSetDouble("/orientation/heading-deg", heading);
385 fgSetString("/sim/presets/speed-set", "UVW");
386 fgSetDouble("/velocities/uBody-fps", uvw(0));
387 fgSetDouble("/velocities/vBody-fps", uvw(1));
388 fgSetDouble("/velocities/wBody-fps", uvw(2));
389 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
390 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
391 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
393 fgSetBool("/sim/presets/onground", true);
397 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
403 // Set current_options lon/lat given an airport id and heading (degrees)
404 static bool fgSetPosFromFix( const string& id )
406 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
407 FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
409 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
413 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
417 // Set the initial position based on presets (or defaults)
420 global_finalizeTime = SGTimeStamp(); // reset to invalid
421 if (!global_callbackRegistered) {
422 globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1);
423 global_callbackRegistered = true;
426 double gs = fgGetDouble("/sim/presets/glideslope-deg")
427 * SG_DEGREES_TO_RADIANS ;
428 double od = fgGetDouble("/sim/presets/offset-distance-nm");
429 double alt = fgGetDouble("/sim/presets/altitude-ft");
431 bool set_pos = false;
433 // If glideslope is specified, then calculate offset-distance or
434 // altitude relative to glide slope if either of those was not
436 if ( fabs( gs ) > 0.01 ) {
437 fgSetDistOrAltFromGlideSlope();
441 // If we have an explicit, in-range lon/lat, don't change it, just use it.
442 // If not, check for an airport-id and use that.
443 // If not, default to the middle of the KSFO field.
444 // The default values for lon/lat are deliberately out of range
445 // so that the airport-id can take effect; valid lon/lat will
446 // override airport-id, however.
447 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
448 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
449 if ( lon_deg >= -180.0 && lon_deg <= 180.0
450 && lat_deg >= -90.0 && lat_deg <= 90.0 )
455 string apt = fgGetString("/sim/presets/airport-id");
456 string rwy_no = fgGetString("/sim/presets/runway");
457 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
458 string vor = fgGetString("/sim/presets/vor-id");
459 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
460 string ndb = fgGetString("/sim/presets/ndb-id");
461 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
462 string carrier = fgGetString("/sim/presets/carrier");
463 string parkpos = fgGetString("/sim/presets/parkpos");
464 string fix = fgGetString("/sim/presets/fix");
465 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
466 double hdg = hdg_preset->getDoubleValue();
468 // save some start parameters, so that we can later say what the
469 // user really requested. TODO generalize that and move it to options.cxx
470 static bool start_options_saved = false;
471 if (!start_options_saved) {
472 start_options_saved = true;
473 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
475 opt->setDoubleValue("latitude-deg", lat_deg);
476 opt->setDoubleValue("longitude-deg", lon_deg);
477 opt->setDoubleValue("heading-deg", hdg);
478 opt->setStringValue("airport", apt.c_str());
479 opt->setStringValue("runway", rwy_no.c_str());
483 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
485 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
486 // An airport + parking position is requested
487 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
488 // set tower position
489 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
490 fgSetString("/sim/tower/airport-id", apt.c_str());
495 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
496 // An airport + runway is requested
497 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
498 // set tower position (a little off the heading for single
500 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
501 fgSetString("/sim/tower/airport-id", apt.c_str());
506 if ( !set_pos && !apt.empty() ) {
507 // An airport is requested (find runway closest to hdg)
508 if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
509 // set tower position (a little off the heading for single
511 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
512 fgSetString("/sim/tower/airport-id", apt.c_str());
517 if (hdg_preset->getDoubleValue() > 9990.0)
518 hdg_preset->setDoubleValue(hdg);
520 if ( !set_pos && !vor.empty() ) {
521 // a VOR is requested
522 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
527 if ( !set_pos && !ndb.empty() ) {
528 // an NDB is requested
529 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
534 if ( !set_pos && !carrier.empty() ) {
535 // an aircraft carrier is requested
536 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
541 if ( !set_pos && !fix.empty() ) {
542 // a Fix is requested
543 if ( fgSetPosFromFix( fix ) ) {
549 // No lon/lat specified, no airport specified, default to
550 // middle of KSFO field.
551 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
552 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
555 fgSetDouble( "/position/longitude-deg",
556 fgGetDouble("/sim/presets/longitude-deg") );
557 fgSetDouble( "/position/latitude-deg",
558 fgGetDouble("/sim/presets/latitude-deg") );
559 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
561 // determine if this should be an on-ground or in-air start
562 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
563 fgSetBool("/sim/presets/onground", false);
565 fgSetBool("/sim/presets/onground", true);
568 fgSetBool("/sim/position-finalized", false);
570 // Initialize the longitude, latitude and altitude to the initial position
571 fgSetDouble("/position/altitude-ft", fgGetDouble("/sim/presets/altitude-ft"));
572 fgSetDouble("/position/longitude-deg", fgGetDouble("/sim/presets/longitude-deg"));
573 fgSetDouble("/position/latitude-deg", fgGetDouble("/sim/presets/latitude-deg"));
580 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
581 string apt = fgGetString("/sim/presets/airport-id");
582 string rwy = fgGetString("/sim/presets/runway");
583 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
584 string parkpos = fgGetString( "/sim/presets/parkpos" );
585 bool onground = fgGetBool( "/sim/presets/onground", false );
586 // this logic is taken from former startup.nas
587 bool needMetar = (hdg < 360.0) && !apt.empty() && (strthdg > 360.0) &&
588 rwy.empty() && onground && parkpos.empty();
591 // timeout so we don't spin forever if the network is down
592 if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 10000)) {
593 SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
597 if (!fgGetBool( "/environment/metar/valid" )) {
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
610 void finalizePosition()
612 // first call to finalize after an initPosition call
613 if (global_finalizeTime.get_usec() == 0) {
614 global_finalizeTime = SGTimeStamp::now();
619 /* Scenarios require Nasal, so FGAIManager loads the scenarios,
620 * including its models such as a/c carriers, in its 'postinit',
621 * which is the very last thing we do.
622 * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
623 * one of the first things we do, long before scenarios/carriers are
624 * loaded. => When requested "initial preset position" relates to a
625 * carrier, recalculate the 'initial' position here
627 std::string carrier = fgGetString("/sim/presets/carrier","");
628 if (!carrier.empty())
630 SG_LOG(SG_GENERAL, SG_INFO, "finalizePositioned: re-init-ing position on carrier");
631 // clear preset location and re-trigger position setup
632 fgSetDouble("/sim/presets/longitude-deg", 9999);
633 fgSetDouble("/sim/presets/latitude-deg", 9999);
636 done = finalizeMetar();
639 fgSetBool("/sim/position-finalized", done);
641 globals->get_event_mgr()->removeTask("finalizePosition");
642 global_callbackRegistered = false;
646 } // of namespace flightgear