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;
154 FGRunway* r = apt->findBestRunwayForHeading(tgt_hdg);
155 fgSetString("/sim/atc/runway", r->ident().c_str());
157 SGGeod startPos = r->pointOnCenterline(fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
158 fgApplyStartOffset(startPos, r->headingDeg(), tgt_hdg);
162 // Set current_options lon/lat given an airport id and parkig position name
163 static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& parkpos )
168 // can't see an easy way around this const_cast at the moment
169 FGAirport* apt = const_cast<FGAirport*>(fgFindAirportID(id));
171 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
174 FGAirportDynamics* dcs = apt->getDynamics();
176 SG_LOG( SG_GENERAL, SG_ALERT,
177 "Airport " << id << "does not appear to have parking information available");
181 ParkingAssignment pka;
182 double radius = fgGetDouble("/sim/dimensions/radius-m");
183 if ((parkpos == string("AVAILABLE")) && (radius > 0)) {
188 acData = globals->get_fg_home();
189 acData.append("aircraft-data");
190 string acfile = fgGetString("/sim/aircraft") + string(".xml");
191 acData.append(acfile);
193 readProperties(acData.str(), &root);
194 SGPropertyNode * node = root.getNode("sim");
195 fltType = node->getStringValue("aircraft-class", "NONE" );
196 acOperator = node->getStringValue("aircraft-operator", "NONE" );
197 } catch (const sg_exception &) {
198 SG_LOG(SG_GENERAL, SG_INFO,
199 "Could not load aircraft aircrat type and operator information from: " << acData.str() << ". Using defaults");
201 // cout << path.str() << endl;
203 if (fltType.empty() || fltType == "NONE") {
204 SG_LOG(SG_GENERAL, SG_INFO,
205 "Aircraft type information not found in: " << acData.str() << ". Using default value");
206 fltType = fgGetString("/sim/aircraft-class" );
208 if (acOperator.empty() || fltType == "NONE") {
209 SG_LOG(SG_GENERAL, SG_INFO,
210 "Aircraft operator information not found in: " << acData.str() << ". Using default value");
211 acOperator = fgGetString("/sim/aircraft-operator" );
214 string acType; // Currently not used by findAvailable parking, so safe to leave empty.
215 pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
217 fgGetString("/sim/presets/parkpos");
218 fgSetString("/sim/presets/parkpos", pka.parking()->getName());
220 SG_LOG( SG_GENERAL, SG_ALERT,
221 "Failed to find a suitable parking at airport " << id );
225 pka = dcs->getParkingByName(parkpos);
226 if (!pka.isValid()) {
227 SG_LOG( SG_GENERAL, SG_ALERT,
228 "Failed to find a parking at airport " << id << ":" << parkpos);
233 fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
238 // Set current_options lon/lat given an airport id and runway number
239 static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
243 // set initial position from airport and runway number
244 SG_LOG( SG_GENERAL, SG_INFO,
245 "Attempting to set starting position for "
246 << id << ":" << rwy );
248 const FGAirport* apt = fgFindAirportID(id);
250 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
254 if (!apt->hasRunwayWithIdent(rwy)) {
255 SG_LOG( SG_GENERAL, rwy_req ? SG_ALERT : SG_INFO,
256 "Failed to find runway " << rwy <<
257 " at airport " << id << ". Using default runway." );
261 FGRunway* r(apt->getRunwayByIdent(rwy));
262 fgSetString("/sim/atc/runway", r->ident().c_str());
263 SGGeod startPos = r->pointOnCenterline( fgGetDouble("/sim/airport/runways/start-offset-m", 5.0));
264 fgApplyStartOffset(startPos, r->headingDeg());
269 static void fgSetDistOrAltFromGlideSlope() {
270 // cout << "fgSetDistOrAltFromGlideSlope()" << endl;
271 string apt_id = fgGetString("/sim/presets/airport-id");
272 double gs = fgGetDouble("/sim/presets/glideslope-deg")
273 * SG_DEGREES_TO_RADIANS ;
274 double od = fgGetDouble("/sim/presets/offset-distance-nm");
275 double alt = fgGetDouble("/sim/presets/altitude-ft");
277 double apt_elev = 0.0;
278 if ( ! apt_id.empty() ) {
279 apt_elev = fgGetAirportElev( apt_id );
280 if ( apt_elev < -9990.0 ) {
287 if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
288 // set altitude from glideslope and offset-distance
289 od *= SG_NM_TO_METER * SG_METER_TO_FEET;
290 alt = fabs(od*tan(gs)) + apt_elev;
291 fgSetDouble("/sim/presets/altitude-ft", alt);
292 fgSetBool("/sim/presets/onground", false);
293 SG_LOG( SG_GENERAL, SG_INFO, "Calculated altitude as: "
295 } else if( fabs(gs) > 0.01 && alt > 0 && fabs(od) < 0.1) {
296 // set offset-distance from glideslope and altitude
297 od = (alt - apt_elev) / tan(gs);
298 od *= -1*SG_FEET_TO_METER * SG_METER_TO_NM;
299 fgSetDouble("/sim/presets/offset-distance-nm", od);
300 fgSetBool("/sim/presets/onground", false);
301 SG_LOG( SG_GENERAL, SG_INFO, "Calculated offset distance as: "
303 } else if( fabs(gs) > 0.01 ) {
304 SG_LOG( SG_GENERAL, SG_ALERT,
305 "Glideslope given but not altitude or offset-distance." );
306 SG_LOG( SG_GENERAL, SG_ALERT, "Resetting glideslope to zero" );
307 fgSetDouble("/sim/presets/glideslope-deg", 0);
308 fgSetBool("/sim/presets/onground", true);
313 // Set current_options lon/lat given an airport id and heading (degrees)
314 static bool fgSetPosFromNAV( const string& id, const double& freq, FGPositioned::Type type )
316 FGNavList::TypeFilter filter(type);
317 const nav_list_type navlist = FGNavList::findByIdentAndFreq( id.c_str(), freq, &filter );
319 if (navlist.size() == 0 ) {
320 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate NAV = "
321 << id << ":" << freq );
325 if( navlist.size() > 1 ) {
326 std::ostringstream buf;
327 buf << "Ambigous NAV-ID: '" << id << "'. Specify id and frequency. Available stations:" << endl;
328 for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
329 // NDB stored in kHz, VOR stored in MHz * 100 :-P
330 double factor = (*it)->type() == FGPositioned::NDB ? 1.0 : 1/100.0;
331 string unit = (*it)->type() == FGPositioned::NDB ? "kHz" : "MHz";
332 buf << (*it)->ident() << " "
333 << std::setprecision(5) << (double)((*it)->get_freq() * factor) << " "
334 << (*it)->get_lat() << "/" << (*it)->get_lon()
338 SG_LOG( SG_GENERAL, SG_ALERT, buf.str() );
342 FGNavRecord *nav = navlist[0];
343 fgApplyStartOffset(nav->geod(), fgGetDouble("/sim/presets/heading-deg"));
347 // Set current_options lon/lat given an aircraft carrier id
348 static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
350 // set initial position from runway and heading
354 if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
355 double lon = geodPos.getLongitudeDeg();
356 double lat = geodPos.getLatitudeDeg();
357 double alt = geodPos.getElevationFt();
359 SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
360 << carrier << " at lat = " << lat << ", lon = " << lon
361 << ", alt = " << alt << ", heading = " << heading);
363 fgSetDouble("/sim/presets/longitude-deg", lon);
364 fgSetDouble("/sim/presets/latitude-deg", lat);
365 fgSetDouble("/sim/presets/altitude-ft", alt);
366 fgSetDouble("/sim/presets/heading-deg", heading);
367 fgSetDouble("/position/longitude-deg", lon);
368 fgSetDouble("/position/latitude-deg", lat);
369 fgSetDouble("/position/altitude-ft", alt);
370 fgSetDouble("/orientation/heading-deg", heading);
372 fgSetString("/sim/presets/speed-set", "UVW");
373 fgSetDouble("/velocities/uBody-fps", uvw(0));
374 fgSetDouble("/velocities/vBody-fps", uvw(1));
375 fgSetDouble("/velocities/wBody-fps", uvw(2));
376 fgSetDouble("/sim/presets/uBody-fps", uvw(0));
377 fgSetDouble("/sim/presets/vBody-fps", uvw(1));
378 fgSetDouble("/sim/presets/wBody-fps", uvw(2));
380 fgSetBool("/sim/presets/onground", true);
384 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
390 // Set current_options lon/lat given an airport id and heading (degrees)
391 static bool fgSetPosFromFix( const string& id )
393 FGPositioned::TypeFilter fixFilter(FGPositioned::FIX);
394 FGPositioned* fix = FGPositioned::findFirstWithIdent(id, &fixFilter);
396 SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
400 fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
404 // Set the initial position based on presets (or defaults)
407 global_finalizeTime = SGTimeStamp(); // reset to invalid
408 if (!global_callbackRegistered) {
409 globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1);
410 global_callbackRegistered = true;
413 double gs = fgGetDouble("/sim/presets/glideslope-deg")
414 * SG_DEGREES_TO_RADIANS ;
415 double od = fgGetDouble("/sim/presets/offset-distance-nm");
416 double alt = fgGetDouble("/sim/presets/altitude-ft");
418 bool set_pos = false;
420 // If glideslope is specified, then calculate offset-distance or
421 // altitude relative to glide slope if either of those was not
423 if ( fabs( gs ) > 0.01 ) {
424 fgSetDistOrAltFromGlideSlope();
428 // If we have an explicit, in-range lon/lat, don't change it, just use it.
429 // If not, check for an airport-id and use that.
430 // If not, default to the middle of the KSFO field.
431 // The default values for lon/lat are deliberately out of range
432 // so that the airport-id can take effect; valid lon/lat will
433 // override airport-id, however.
434 double lon_deg = fgGetDouble("/sim/presets/longitude-deg");
435 double lat_deg = fgGetDouble("/sim/presets/latitude-deg");
436 if ( lon_deg >= -180.0 && lon_deg <= 180.0
437 && lat_deg >= -90.0 && lat_deg <= 90.0 )
442 string apt = fgGetString("/sim/presets/airport-id");
443 string rwy_no = fgGetString("/sim/presets/runway");
444 bool rwy_req = fgGetBool("/sim/presets/runway-requested");
445 string vor = fgGetString("/sim/presets/vor-id");
446 double vor_freq = fgGetDouble("/sim/presets/vor-freq");
447 string ndb = fgGetString("/sim/presets/ndb-id");
448 double ndb_freq = fgGetDouble("/sim/presets/ndb-freq");
449 string carrier = fgGetString("/sim/presets/carrier");
450 string parkpos = fgGetString("/sim/presets/parkpos");
451 string fix = fgGetString("/sim/presets/fix");
452 SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
453 double hdg = hdg_preset->getDoubleValue();
455 // save some start parameters, so that we can later say what the
456 // user really requested. TODO generalize that and move it to options.cxx
457 static bool start_options_saved = false;
458 if (!start_options_saved) {
459 start_options_saved = true;
460 SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
462 opt->setDoubleValue("latitude-deg", lat_deg);
463 opt->setDoubleValue("longitude-deg", lon_deg);
464 opt->setDoubleValue("heading-deg", hdg);
465 opt->setStringValue("airport", apt.c_str());
466 opt->setStringValue("runway", rwy_no.c_str());
470 hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
472 if ( !set_pos && !apt.empty() && !parkpos.empty() ) {
473 // An airport + parking position is requested
474 if ( fgSetPosFromAirportIDandParkpos( apt, parkpos ) ) {
475 // set tower position
476 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
477 fgSetString("/sim/tower/airport-id", apt.c_str());
482 if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
483 // An airport + runway is requested
484 if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
485 // set tower position (a little off the heading for single
487 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
488 fgSetString("/sim/tower/airport-id", apt.c_str());
493 if ( !set_pos && !apt.empty() ) {
494 // An airport is requested (find runway closest to hdg)
495 if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
496 // set tower position (a little off the heading for single
498 fgSetString("/sim/airport/closest-airport-id", apt.c_str());
499 fgSetString("/sim/tower/airport-id", apt.c_str());
504 if (hdg_preset->getDoubleValue() > 9990.0)
505 hdg_preset->setDoubleValue(hdg);
507 if ( !set_pos && !vor.empty() ) {
508 // a VOR is requested
509 if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR ) ) {
514 if ( !set_pos && !ndb.empty() ) {
515 // an NDB is requested
516 if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB ) ) {
521 if ( !set_pos && !carrier.empty() ) {
522 // an aircraft carrier is requested
523 if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
528 if ( !set_pos && !fix.empty() ) {
529 // a Fix is requested
530 if ( fgSetPosFromFix( fix ) ) {
536 // No lon/lat specified, no airport specified, default to
537 // middle of KSFO field.
538 fgSetDouble("/sim/presets/longitude-deg", -122.374843);
539 fgSetDouble("/sim/presets/latitude-deg", 37.619002);
542 fgSetDouble( "/position/longitude-deg",
543 fgGetDouble("/sim/presets/longitude-deg") );
544 fgSetDouble( "/position/latitude-deg",
545 fgGetDouble("/sim/presets/latitude-deg") );
546 fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
548 // determine if this should be an on-ground or in-air start
549 if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
550 fgSetBool("/sim/presets/onground", false);
552 fgSetBool("/sim/presets/onground", true);
555 fgSetBool("/sim/position-finalized", false);
562 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
563 string apt = fgGetString("/sim/presets/airport-id");
564 string rwy = fgGetString("/sim/presets/runway");
565 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
566 string parkpos = fgGetString( "/sim/presets/parkpos" );
567 bool onground = fgGetBool( "/sim/presets/onground", false );
568 // this logic is taken from former startup.nas
569 bool needMetar = (hdg < 360.0) && !apt.empty() && (strthdg > 360.0) &&
570 rwy.empty() && onground && parkpos.empty();
573 // timeout so we don't spin forever if the network is down
574 if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 10000)) {
575 SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
579 if (!fgGetBool( "/environment/metar/valid" )) {
583 SG_LOG(SG_ENVIRONMENT, SG_INFO,
584 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
585 setPosFromAirportIDandHdg( apt, hdg );
586 // fall through to return true
587 } // of need-metar case
592 void finalizePosition()
594 // first call to finalize after an initPosition call
595 if (global_finalizeTime.get_usec() == 0) {
596 global_finalizeTime = SGTimeStamp::now();
601 /* Scenarios require Nasal, so FGAIManager loads the scenarios,
602 * including its models such as a/c carriers, in its 'postinit',
603 * which is the very last thing we do.
604 * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
605 * one of the first things we do, long before scenarios/carriers are
606 * loaded. => When requested "initial preset position" relates to a
607 * carrier, recalculate the 'initial' position here
609 std::string carrier = fgGetString("/sim/presets/carrier","");
610 if (!carrier.empty())
612 SG_LOG(SG_GENERAL, SG_INFO, "finalizePositioned: re-init-ing position on carrier");
613 // clear preset location and re-trigger position setup
614 fgSetDouble("/sim/presets/longitude-deg", 9999);
615 fgSetDouble("/sim/presets/latitude-deg", 9999);
618 done = finalizeMetar();
621 fgSetBool("/sim/position-finalized", done);
623 globals->get_event_mgr()->removeTask("finalizePosition");
624 global_callbackRegistered = false;
628 } // of namespace flightgear