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>
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;
50 static void finalizePosition();
52 // Set current tower position lon/lat given an airport id
53 static bool fgSetTowerPosFromAirportID( const string& id) {
54 const FGAirport *a = fgFindAirportID( id);
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());
67 struct FGTowerLocationListener : SGPropertyChangeListener {
68 void valueChanged(SGPropertyNode* node) {
69 string id(node->getStringValue());
70 if (fgGetBool("/sim/tower/auto-position",true))
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))
77 node->setStringValue(id);
80 fgSetTowerPosFromAirportID(id);
84 struct FGClosestTowerLocationListener : SGPropertyChangeListener
86 void valueChanged(SGPropertyNode* )
88 // closest airport has changed
89 if (fgGetBool("/sim/tower/auto-position",true))
91 // update tower position
92 const char* id = fgGetString("/sim/airport/closest-airport-id", "");
94 fgSetString("/sim/tower/airport-id", id);
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 );
109 static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double aTargetHeading = HUGE_VAL)
111 SGGeod startPos(aStartPos);
112 if (aTargetHeading == HUGE_VAL) {
113 aTargetHeading = aHeading;
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;
127 SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
132 fgSetDouble("/sim/presets/longitude-deg", startPos.getLongitudeDeg() );
133 fgSetDouble("/sim/presets/latitude-deg", startPos.getLatitudeDeg() );
134 fgSetDouble("/sim/presets/heading-deg", aHeading );
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 );
142 // Set current_options lon/lat given an airport id and heading (degrees)
143 static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
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 );
152 const FGAirport* apt = fgFindAirportID(id);
153 if (!apt) return false;
156 double heading = tgt_hdg;
157 if (apt->type() == FGPositioned::HELIPORT) {
158 if (apt->numHelipads() > 0) {
159 startPos = apt->getHelipadByIndex(0)->geod();
161 startPos = apt->geod();
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();
170 fgApplyStartOffset(startPos, heading, tgt_hdg);
174 // Set current_options lon/lat given an airport id and parkig position name
175 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
180 // can't see an easy way around this const_cast at the moment
181 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
183 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
186 FGAirportDynamics* dcs = apt->getDynamics();
188 SG_LOG( SG_GENERAL, SG_ALERT,
189 "Airport " << id << "does not appear to have parking information available");
193 ParkingAssignment pka;
194 double radius = fgGetDouble("/sim/dimensions/radius-m");
195 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
200 acData = globals->get_fg_home();
201 acData.append("aircraft-data");
202 string acfile = fgGetString("/sim/aircraft") + string(".xml");
203 acData.append(acfile);
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");
213 // cout << path.str() << endl;
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" );
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" );
226 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
227 pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
229 fgGetString("/sim/presets/parkpos");
230 fgSetString("/sim/presets/parkpos", pka.parking()->getName());
232 SG_LOG( SG_GENERAL, SG_ALERT,
233 "Failed to find a suitable parking at airport " << id );
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);
245 fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
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 ) {
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 );
260 const FGAirport* apt = fgFindAirportID(id);
262 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
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." );
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());
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");
289 double apt_elev = 0.0;
290 if ( ! apt_id.empty() ) {
291 apt_elev = fgGetAirportElev( apt_id );
292 if ( apt_elev < -9990.0 ) {
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: "
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: "
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);
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 )
328 FGNavList::TypeFilter filter(type);
329 const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
331 if (navlist.size() == 0 ) {
332 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
333 << id << ":" << freq );
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()
350 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
354 FGNavRecord *nav = navlist[0];
355 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
359 // Set current_options lon/lat given an aircraft carrier id
360 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
362 // set initial position from runway and heading
366 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
367 double lon = geodPos.getLongitudeDeg();
368 double lat = geodPos.getLatitudeDeg();
369 double alt = geodPos.getElevationFt();
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);
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);
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));
392 fgSetBool("/sim/presets/onground", true);
396 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
402 // Set current_options lon/lat given an airport id and heading (degrees)
403 static bool fgSetPosFromFix( const string& id )
405 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
406 FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
408 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
412 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
416 // Set the initial position based on presets (or defaults)
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;
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");
430 bool set_pos = false;
432 // If glideslope is specified, then calculate offset-distance or
433 // altitude relative to glide slope if either of those was not
435 if ( fabs( gs ) > 0.01 ) {
436 fgSetDistOrAltFromGlideSlope();
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 )
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();
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);
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());
482 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
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());
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
499 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
500 fgSetString("/sim/tower/airport-id", apt.c_str());
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
510 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
511 fgSetString("/sim/tower/airport-id", apt.c_str());
516 if (hdg_preset->getDoubleValue() > 9990.0)
517 hdg_preset->setDoubleValue(hdg);
519 if ( !set_pos && !vor.empty() ) {
520 // a VOR is requested
521 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
526 if ( !set_pos && !ndb.empty() ) {
527 // an NDB is requested
528 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
533 if ( !set_pos && !carrier.empty() ) {
534 // an aircraft carrier is requested
535 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
540 if ( !set_pos && !fix.empty() ) {
541 // a Fix is requested
542 if ( fgSetPosFromFix( fix ) ) {
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);
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());
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);
564 fgSetBool("/sim/presets/onground", true);
567 fgSetBool("/sim/position-finalized", false);
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();
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");
591 if (!fgGetBool( "/environment/metar/valid" )) {
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
604 void finalizePosition()
606 // first call to finalize after an initPosition call
607 if (global_finalizeTime.get_usec() == 0) {
608 global_finalizeTime = SGTimeStamp::now();
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
621 std::string carrier = fgGetString("/sim/presets/carrier","");
622 if (!carrier.empty())
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);
630 done = finalizeMetar();
633 fgSetBool("/sim/position-finalized", done);
635 globals->get_event_mgr()->removeTask("finalizePosition");
636 global_callbackRegistered = false;
640 } // of namespace flightgear