1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
4 // This file is in the Public Domain and comes with no warranty.
12 #include <boost/tuple/tuple.hpp>
18 #include "Main/fg_props.hxx"
19 #include "Main/globals.hxx" // for get_subsystem
20 #include "Main/util.hxx" // for fgLowPass
21 #include "Navaids/positioned.hxx"
22 #include <Navaids/waypoint.hxx>
23 #include "Navaids/navrecord.hxx"
24 #include "Airports/simple.hxx"
25 #include "Airports/runways.hxx"
26 #include "Autopilot/route_mgr.hxx"
28 #include <simgear/math/sg_random.h>
29 #include <simgear/sg_inlines.h>
30 #include <simgear/math/sg_geodesy.hxx>
31 #include <simgear/structure/exception.hxx>
35 using namespace flightgear;
37 ///////////////////////////////////////////////////////////////////
39 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
41 _lon = base->getChild(lonStr, 0, true);
42 _lat = base->getChild(latStr, 0, true);
44 _alt = base->getChild(altStr, 0, true);
48 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
50 _lon = fgGetNode(lonStr, true);
51 _lat = fgGetNode(latStr, true);
53 _alt = fgGetNode(altStr, true);
57 void SGGeodProperty::clear()
59 _lon = _lat = _alt = NULL;
62 void SGGeodProperty::operator=(const SGGeod& geod)
64 _lon->setDoubleValue(geod.getLongitudeDeg());
65 _lat->setDoubleValue(geod.getLatitudeDeg());
67 _alt->setDoubleValue(geod.getElevationFt());
71 SGGeod SGGeodProperty::get() const
73 double lon = _lon->getDoubleValue(),
74 lat = _lat->getDoubleValue();
76 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
78 return SGGeod::fromDeg(lon,lat);
82 static const char* makeTTWString(double TTW)
84 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
88 unsigned int TTW_seconds = (int) (TTW + 0.5);
89 unsigned int TTW_minutes = 0;
90 unsigned int TTW_hours = 0;
91 static char TTW_str[9];
92 TTW_hours = TTW_seconds / 3600;
93 TTW_minutes = (TTW_seconds / 60) % 60;
94 TTW_seconds = TTW_seconds % 60;
95 snprintf(TTW_str, 9, "%02d:%02d:%02d",
96 TTW_hours, TTW_minutes, TTW_seconds);
100 /////////////////////////////////////////////////////////////////////////////
102 class GPSListener : public SGPropertyChangeListener
105 GPSListener(GPS *m) :
109 virtual void valueChanged (SGPropertyNode * prop)
116 if (prop == _gps->_route_current_wp_node) {
117 _gps->routeManagerSequenced();
118 } else if (prop == _gps->_route_active_node) {
119 _gps->routeActivated();
120 } else if (prop == _gps->_ref_navaid_id_node) {
121 _gps->referenceNavaidSet(prop->getStringValue(""));
122 } else if (prop == _gps->_routeEditedSignal) {
124 } else if (prop == _gps->_routeFinishedSignal) {
125 _gps->routeFinished();
131 void setGuard(bool g) {
136 bool _guard; // re-entrancy guard
139 ////////////////////////////////////////////////////////////////////////////
141 * Helper to monitor for Nasal or other code accessing properties we haven't
142 * defined. For the moment we complain about all such activites, since various
143 * users assume all kinds of weird, wonderful and non-existent interfaces.
146 class DeprecatedPropListener : public SGPropertyChangeListener
149 DeprecatedPropListener(SGPropertyNode* gps)
151 _parents.insert(gps);
152 SGPropertyNode* wp = gps->getChild("wp", 0, true);
154 _parents.insert(wp->getChild("wp", 0, true));
155 _parents.insert(wp->getChild("wp", 1, true));
157 std::set<SGPropertyNode*>::iterator it;
158 for (it = _parents.begin(); it != _parents.end(); ++it) {
159 (*it)->addChangeListener(this);
163 virtual void valueChanged (SGPropertyNode * prop)
167 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
169 if (isDeprecated(parent, child)) {
170 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
171 << child->getPath(true));
175 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
177 if (_parents.count(parent) < 1) {
181 // no child exclusions yet
185 std::set<SGPropertyNode*> _parents;
188 ////////////////////////////////////////////////////////////////////////////
189 // configuration helper object
191 GPS::Config::Config() :
192 _enableTurnAnticipation(true),
193 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
194 _overflightArmDistance(1.0),
195 _waypointAlertTime(30.0),
196 _minRunwayLengthFt(0.0),
197 _requireHardSurface(true),
198 _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
199 _driveAutopilot(true),
200 _courseSelectable(false)
202 _enableTurnAnticipation = false;
205 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
207 aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
208 aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
209 aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
210 aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
211 aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
212 aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
213 aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
214 aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
217 ////////////////////////////////////////////////////////////////////////////
219 GPS::GPS ( SGPropertyNode *node) :
220 _selectedCourse(0.0),
223 _lastPosValid(false),
225 _name(node->getStringValue("name", "gps")),
226 _num(node->getIntValue("number", 0)),
227 _computeTurnData(false),
228 _anticipateTurn(false),
231 string branch = "/instrumentation/" + _name;
232 _gpsNode = fgGetNode(branch.c_str(), _num, true );
233 _scratchNode = _gpsNode->getChild("scratch", 0, true);
235 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
236 _currentWayptNode = wp_node->getChild("wp", 1, true);
246 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
249 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
250 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
251 _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
252 _serviceable_node->setBoolValue(true);
253 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
256 _raim_node = _gpsNode->getChild("raim", 0, true);
257 _odometer_node = _gpsNode->getChild("odometer", 0, true);
258 _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
259 _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
260 _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
261 _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
262 _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
265 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
266 SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
267 wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
269 _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
272 SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
273 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
274 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
275 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
276 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
277 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
278 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
279 _ref_navaid_elapsed = 0.0;
280 _ref_navaid_set = false;
283 // should these move to the route manager?
284 _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
285 _routeETE = _gpsNode->getChild("ETE", 0, true);
286 _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
287 _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
289 // add listener to various things
290 _listener = new GPSListener(this);
291 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
292 _route_current_wp_node->addChangeListener(_listener);
293 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
294 _route_active_node->addChangeListener(_listener);
295 _ref_navaid_id_node->addChangeListener(_listener);
296 _routeEditedSignal->addChangeListener(_listener);
297 _routeFinishedSignal->addChangeListener(_listener);
299 // navradio slaving properties
300 SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
301 toFlag->alias(_currentWayptNode->getChild("to-flag"));
303 SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
304 fromFlag->alias(_currentWayptNode->getChild("from-flag"));
306 // autopilot drive properties
307 _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
308 _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
309 _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
310 _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
313 _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
314 if (!_realismSimpleGps->hasValue()) {
315 _realismSimpleGps->setBoolValue(true);
318 // last thing, add the deprecated prop watcher
319 new DeprecatedPropListener(_gpsNode);
327 _config.bind(this, _gpsNode->getChild("config", 0, true));
329 tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
330 (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
332 tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
333 (*this, &GPS::getDesiredCourse, NULL));
334 _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
336 tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg",
337 "indicated-latitude-deg", "indicated-altitude-ft");
339 tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
340 (*this, &GPS::getVerticalSpeed, NULL));
341 tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
342 (*this, &GPS::getTrueTrack, NULL));
343 tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
344 (*this, &GPS::getMagTrack, NULL));
345 tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
346 (*this, &GPS::getGroundspeedKts, NULL));
349 tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
350 tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
352 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
353 tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
354 tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
355 tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
356 tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
357 tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
358 _scratchValid = false;
361 SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
362 SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
364 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
365 tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
366 (*this, &GPS::getWP1Ident, NULL));
368 tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
369 (*this, &GPS::getWP1Distance, NULL));
370 tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
371 (*this, &GPS::getWP1Bearing, NULL));
372 tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
373 (*this, &GPS::getWP1MagBearing, NULL));
374 tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
375 (*this, &GPS::getWP1TTW, NULL));
376 tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
377 (*this, &GPS::getWP1TTWString, NULL));
379 tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
380 (*this, &GPS::getWP1CourseDeviation, NULL));
381 tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
382 (*this, &GPS::getWP1CourseErrorNm, NULL));
383 tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
384 (*this, &GPS::getWP1ToFlag, NULL));
385 tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
386 (*this, &GPS::getWP1FromFlag, NULL));
388 // leg properties (only valid in DTO/LEG modes, not OBS)
389 tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
390 tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
391 tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
393 // navradio slaving properties
394 tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
395 (*this, &GPS::getCDIDeflection));
401 for (unsigned int t=0; t<_tiedNodes.size(); ++t) {
402 _tiedNodes[t]->untie();
411 _last_speed_kts = 0.0;
412 _last_pos = SGGeod();
413 _lastPosValid = false;
414 _indicated_pos = SGGeod();
415 _last_vertical_speed = 0.0;
416 _last_true_track = 0.0;
417 _lastEWVelocity = _lastNSVelocity = 0.0;
418 _currentWaypt = _prevWaypt = NULL;
419 _legDistanceNm = -1.0;
421 _raim_node->setDoubleValue(0.0);
422 _indicated_pos = SGGeod();
423 _odometer_node->setDoubleValue(0);
424 _trip_odometer_node->setDoubleValue(0);
425 _tracking_bug_node->setDoubleValue(0);
426 _true_bug_error_node->setDoubleValue(0);
427 _magnetic_bug_error_node->setDoubleValue(0);
428 _northSouthVelocity->setDoubleValue(0.0);
429 _eastWestVelocity->setDoubleValue(0.0);
433 GPS::update (double delta_time_sec)
435 if (!_realismSimpleGps->getBoolValue()) {
436 // If it's off, don't bother.
437 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
443 if (delta_time_sec <= 0.0) {
444 return; // paused, don't bother
447 _raim_node->setDoubleValue(1.0);
448 _indicated_pos = _position.get();
449 updateBasicData(delta_time_sec);
452 if (_wayptController.get()) {
453 _wayptController->update();
454 SGGeod p(_wayptController->position());
455 _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
456 _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
457 _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
459 _desiredCourse = getLegMagCourse();
467 updateReferenceNavaid(delta_time_sec);
471 if (_dataValid && (_mode == "init")) {
472 // allow a realistic delay in the future, here
473 SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
475 if (_route_active_node->getBoolValue()) {
476 // GPS init with active route
477 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
480 // initialise in OBS mode, with waypt set to the nearest airport.
481 // keep in mind at this point, _dataValid is not set
483 auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
484 FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
486 setScratchFromPositioned(apt, 0);
490 } // of init mode check
492 _last_pos = _indicated_pos;
493 _lastPosValid = true;
496 ///////////////////////////////////////////////////////////////////////////
497 // implement the RNAV interface
498 SGGeod GPS::position()
504 return _indicated_pos;
507 double GPS::trackDeg()
509 return _last_true_track;
512 double GPS::groundSpeedKts()
514 return _last_speed_kts;
517 double GPS::vspeedFPM()
519 return _last_vertical_speed;
522 double GPS::magvarDeg()
524 return _magvar_node->getDoubleValue();
527 double GPS::overflightArmDistanceM()
529 return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
532 double GPS::selectedMagCourse()
534 return _selectedCourse;
537 ///////////////////////////////////////////////////////////////////////////
540 GPS::updateBasicData(double dt)
542 if (!_lastPosValid) {
548 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
550 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
551 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
552 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
554 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
555 _last_speed_kts = speed_kt;
557 SGGeod g = _indicated_pos;
558 g.setLongitudeDeg(_last_pos.getLongitudeDeg());
559 double northSouthM = SGGeodesy::distanceM(_last_pos, g);
560 northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
562 double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
563 _lastNSVelocity = nsMSec;
564 _northSouthVelocity->setDoubleValue(nsMSec);
568 g.setLatitudeDeg(_last_pos.getLatitudeDeg());
569 double eastWestM = SGGeodesy::distanceM(_last_pos, g);
570 eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
572 double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
573 _lastEWVelocity = ewMSec;
574 _eastWestVelocity->setDoubleValue(ewMSec);
576 double odometer = _odometer_node->getDoubleValue();
577 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
578 odometer = _trip_odometer_node->getDoubleValue();
579 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
582 SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
588 GPS::updateTrackingBug()
590 double tracking_bug = _tracking_bug_node->getDoubleValue();
591 double true_bug_error = tracking_bug - getTrueTrack();
592 double magnetic_bug_error = tracking_bug - getMagTrack();
594 // Get the errors into the (-180,180) range.
595 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
596 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
598 _true_bug_error_node->setDoubleValue(true_bug_error);
599 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
602 void GPS::updateReferenceNavaid(double dt)
604 if (!_ref_navaid_set) {
605 _ref_navaid_elapsed += dt;
606 if (_ref_navaid_elapsed > 5.0) {
607 _ref_navaid_elapsed = 0.0;
609 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
610 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
612 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
613 _ref_navaid_id_node->setStringValue("");
614 _ref_navaid_name_node->setStringValue("");
615 _ref_navaid_bearing_node->setDoubleValue(0.0);
616 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
617 _ref_navaid_distance_node->setDoubleValue(0.0);
618 _ref_navaid_frequency_node->setStringValue("");
619 } else if (nav != _ref_navaid) {
620 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
621 _listener->setGuard(true);
622 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
623 _ref_navaid_name_node->setStringValue(nav->name().c_str());
624 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
625 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
626 _listener->setGuard(false);
628 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
636 double trueCourse, distanceM, az2;
637 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
638 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
639 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
640 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
644 void GPS::referenceNavaidSet(const std::string& aNavaid)
647 // allow setting an empty string to restore normal nearest-vor selection
648 if (aNavaid.size() > 0) {
649 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
650 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
651 _position.get(), &vorFilter);
654 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
659 _ref_navaid_set = true;
660 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
661 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
662 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
663 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
664 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
666 _ref_navaid_set = false;
667 _ref_navaid_elapsed = 9999.0; // update next tick
671 void GPS::routeActivated()
673 if (_route_active_node->getBoolValue()) {
674 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
677 // if we've already passed the current waypoint, sequence.
678 if (_dataValid && getWP1FromFlag()) {
679 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
680 _routeMgr->sequence();
682 } else if (_mode == "leg") {
683 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
684 // select OBS mode, but keep current waypoint-as is
690 void GPS::routeManagerSequenced()
692 if (_mode != "leg") {
693 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
697 int index = _routeMgr->currentIndex(),
698 count = _routeMgr->numWaypts();
699 if ((index < 0) || (index >= count)) {
702 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
706 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
709 _prevWaypt = _routeMgr->previousWaypt();
710 if (_prevWaypt->flag(WPT_DYNAMIC)) {
711 _wp0_position = _indicated_pos;
713 _wp0_position = _prevWaypt->position();
717 _currentWaypt = _routeMgr->currentWaypt();
719 _desiredCourse = getLegMagCourse();
720 _desiredCourseNode->fireValueChanged();
724 void GPS::routeEdited()
726 if (_mode != "leg") {
730 SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
731 routeManagerSequenced();
734 void GPS::routeFinished()
736 if (_mode != "leg") {
740 SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
741 // select OBS mode, but keep current waypoint-as is
746 void GPS::updateTurn()
748 bool printProgress = false;
750 if (_computeTurnData) {
751 if (_last_speed_kts < 60) {
752 // need valid leg course and sensible ground speed to compute the turn
757 printProgress = true;
760 if (!_anticipateTurn) {
766 // find bearing to turn centre
767 double bearing, az2, distanceM;
768 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
769 double progress = computeTurnProgress(bearing);
772 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
775 if (!_inTurn && (progress > 0.0)) {
779 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
780 _turnSequenced = true;
781 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
782 _routeMgr->sequence();
785 if (_inTurn && (progress >= 1.0)) {
790 // drive deviation and desired course
791 double desiredCourse = bearing - copysign(90, _turnAngle);
792 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
793 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
794 double deviationDeg = desiredCourse - getMagTrack();
795 deviationNm = copysign(deviationNm, deviationDeg);
797 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
798 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
799 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
803 void GPS::updateOverflight()
805 if (!_wayptController->isDone()) {
809 if (_mode == "dto") {
810 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
812 // check for wp1 being on active route - resume leg mode
813 if (_routeMgr->isRouteActive()) {
814 int index = _routeMgr->findWayptIndex(_currentWaypt->position());
816 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
818 _routeMgr->jumpToIndex(index);
822 if (_mode == "dto") {
823 // if we didn't enter leg mode, drop back to OBS mode
824 // select OBS mode, but keep current waypoint-as is
828 } else if (_mode == "leg") {
829 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
830 _routeMgr->sequence();
831 } else if (_mode == "obs") {
832 // nothing to do here, TO/FROM will update but that's fine
835 _computeTurnData = true;
838 void GPS::beginTurn()
841 _turnSequenced = false;
842 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
848 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
849 _computeTurnData = true;
852 double GPS::computeTurnProgress(double aBearing) const
854 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
855 return (aBearing - startBearing) / _turnAngle;
858 void GPS::computeTurnData()
860 _computeTurnData = false;
861 if (_mode != "leg") { // and approach modes in the future
862 _anticipateTurn = false;
866 WayptRef next = _routeMgr->nextWaypt();
867 if (!next || next->flag(WPT_DYNAMIC)) {
868 _anticipateTurn = false;
872 if (!_config.turnAnticipationEnabled()) {
873 _anticipateTurn = false;
877 _turnStartBearing = _desiredCourse;
878 // compute next leg course
880 boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
883 // compute offset bearing
884 _turnAngle = crs - _turnStartBearing;
885 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
886 double median = _turnStartBearing + (_turnAngle * 0.5);
887 double offsetBearing = median + copysign(90, _turnAngle);
888 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
890 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
891 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
892 << ", offset=" << offsetBearing);
894 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
896 _turnPt = _currentWaypt->position();
897 _anticipateTurn = true;
900 void GPS::updateTurnData()
902 // depends on ground speed, so needs to be updated per-frame
903 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
905 // compute the turn centre, based on the turn radius.
906 // key thing is to understand that we're working a right-angle triangle,
907 // where the right-angle is the point we start the turn. From that point,
908 // one side is the inbound course to the turn pt, and the other is the
909 // perpendicular line, of length 'r', to the turn centre.
910 // the triangle's hypotenuse, which we need to find, is the distance from the
911 // turn pt to the turn center (in the direction of the offset bearing)
912 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
914 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
915 double d = _turnRadius / cos(halfTurnAngle);
917 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
918 // << " (cut distance=" << d - _turnRadius << ")");
920 double median = _turnStartBearing + (_turnAngle * 0.5);
921 double offsetBearing = median + copysign(90, _turnAngle);
922 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
925 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
928 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
930 // turn time is seconds to execute a 360 turn.
931 double turnTime = 360.0 / _config.turnRateDegSec();
933 // c is ground distance covered in that time (circumference of the circle)
934 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
936 // divide by 2PI to go from circumference -> radius
937 return c / (2 * M_PI);
940 void GPS::updateRouteData()
942 double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
943 // walk all waypoints from wp2 to route end, and sum
944 for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
945 //totalDistance += _routeMgr->get_waypoint(i).get_distance();
948 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
949 if (_last_speed_kts > 1.0) {
950 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
951 _routeETE->setStringValue(makeTTWString(TTW));
955 void GPS::driveAutopilot()
957 if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
958 _apDrivingFlag->setBoolValue(false);
962 // compatability feature - allow the route-manager / GPS to drive the
963 // generic autopilot heading hold *in leg mode only*
965 bool drive = _mode == "leg";
966 _apDrivingFlag->setBoolValue(drive);
969 // FIXME: we want to set desired track, not heading, here
970 _apTrueHeading->setDoubleValue(getWP1Bearing());
974 void GPS::wp1Changed()
978 if (_mode == "leg") {
979 _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
980 } else if (_mode == "obs") {
981 _wayptController.reset(new OBSController(this, _currentWaypt));
982 } else if (_mode == "dto") {
983 _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
986 _wayptController->init();
988 if (_mode == "obs") {
989 _legDistanceNm = -1.0;
991 _wayptController->update();
992 _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
995 if (!_config.driveAutopilot()) {
999 RouteRestriction ar = _currentWaypt->altitudeRestriction();
1000 double restrictAlt = _currentWaypt->altitudeFt();
1001 double alt = _indicated_pos.getElevationFt();
1002 if ((ar == RESTRICT_AT) ||
1003 ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1004 ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1006 SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1007 _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1011 /////////////////////////////////////////////////////////////////////////////
1012 // property getter/setters
1014 void GPS::setSelectedCourse(double crs)
1016 if (_selectedCourse == crs) {
1020 _selectedCourse = crs;
1021 if ((_mode == "obs") || _config.courseSelectable()) {
1022 _desiredCourse = _selectedCourse;
1023 _desiredCourseNode->fireValueChanged();
1027 double GPS::getLegDistance() const
1029 if (!_dataValid || (_mode == "obs")) {
1033 return _legDistanceNm;
1036 double GPS::getLegCourse() const
1038 if (!_dataValid || !_wayptController.get()) {
1042 return _wayptController->targetTrackDeg();
1045 double GPS::getLegMagCourse() const
1051 double m = getLegCourse() - _magvar_node->getDoubleValue();
1052 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1056 double GPS::getMagTrack() const
1062 double m = getTrueTrack() - _magvar_node->getDoubleValue();
1063 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1067 double GPS::getCDIDeflection() const
1074 if (_config.cdiDeflectionIsAngular()) {
1075 defl = getWP1CourseDeviation();
1076 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1078 double fullScale = _config.cdiDeflectionLinearPeg();
1079 double normError = getWP1CourseErrorNm() / fullScale;
1080 SG_CLAMP_RANGE(normError, -1.0, 1.0);
1081 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1087 const char* GPS::getWP0Ident() const
1089 if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1093 return _prevWaypt->ident().c_str();
1096 const char* GPS::getWP0Name() const
1101 const char* GPS::getWP1Ident() const
1103 if ((!_dataValid)||(!_currentWaypt)) {
1107 return _currentWaypt->ident().c_str();
1110 const char* GPS::getWP1Name() const
1115 double GPS::getWP1Distance() const
1117 if (!_dataValid || !_wayptController.get()) {
1121 return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1124 double GPS::getWP1TTW() const
1126 if (!_dataValid || !_wayptController.get()) {
1130 return _wayptController->timeToWaypt();
1133 const char* GPS::getWP1TTWString() const
1135 double t = getWP1TTW();
1140 return makeTTWString(t);
1143 double GPS::getWP1Bearing() const
1145 if (!_dataValid || !_wayptController.get()) {
1149 return _wayptController->trueBearingDeg();
1152 double GPS::getWP1MagBearing() const
1158 double magBearing = _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1159 SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1163 double GPS::getWP1CourseDeviation() const
1165 if (!_dataValid || !_wayptController.get()) {
1169 return _wayptController->courseDeviationDeg();
1172 double GPS::getWP1CourseErrorNm() const
1174 if (!_dataValid || !_wayptController.get()) {
1178 return _wayptController->xtrackErrorNm();
1181 bool GPS::getWP1ToFlag() const
1183 if (!_dataValid || !_wayptController.get()) {
1187 return _wayptController->toFlag();
1190 bool GPS::getWP1FromFlag() const
1192 if (!_dataValid || !_wayptController.get()) {
1196 return !getWP1ToFlag();
1199 double GPS::getScratchDistance() const
1201 if (!_scratchValid) {
1205 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1208 double GPS::getScratchTrueBearing() const
1210 if (!_scratchValid) {
1214 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1217 double GPS::getScratchMagBearing() const
1219 if (!_scratchValid) {
1223 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1224 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1228 /////////////////////////////////////////////////////////////////////////////
1229 // command / scratch / search system
1231 void GPS::setCommand(const char* aCmd)
1233 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1235 if (!strcmp(aCmd, "direct")) {
1237 } else if (!strcmp(aCmd, "obs")) {
1239 } else if (!strcmp(aCmd, "leg")) {
1241 } else if (!strcmp(aCmd, "load-route-wpt")) {
1242 loadRouteWaypoint();
1243 } else if (!strcmp(aCmd, "nearest")) {
1245 } else if (!strcmp(aCmd, "search")) {
1246 _searchNames = false;
1248 } else if (!strcmp(aCmd, "search-names")) {
1249 _searchNames = true;
1251 } else if (!strcmp(aCmd, "next")) {
1253 } else if (!strcmp(aCmd, "previous")) {
1255 } else if (!strcmp(aCmd, "define-user-wpt")) {
1257 } else if (!strcmp(aCmd, "route-insert-before")) {
1258 int index = _scratchNode->getIntValue("index");
1259 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1260 index = _routeMgr->numWaypts();
1261 } else if (index >= _routeMgr->numWaypts()) {
1262 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1266 insertWaypointAtIndex(index);
1267 } else if (!strcmp(aCmd, "route-insert-after")) {
1268 int index = _scratchNode->getIntValue("index");
1269 if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1270 index = _routeMgr->numWaypts();
1271 } else if (index >= _routeMgr->numWaypts()) {
1272 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1278 insertWaypointAtIndex(index);
1279 } else if (!strcmp(aCmd, "route-delete")) {
1280 int index = _scratchNode->getIntValue("index");
1282 index = _routeMgr->numWaypts();
1283 } else if (index >= _routeMgr->numWaypts()) {
1284 SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1288 removeWaypointAtIndex(index);
1290 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1294 void GPS::clearScratch()
1296 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1297 _scratchValid = false;
1298 _scratchNode->setStringValue("type", "");
1299 _scratchNode->setStringValue("query", "");
1302 bool GPS::isScratchPositionValid() const
1304 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1305 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1312 void GPS::directTo()
1314 if (!isScratchPositionValid()) {
1319 _wp0_position = _indicated_pos;
1320 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1327 void GPS::loadRouteWaypoint()
1329 _scratchValid = false;
1330 // if (!_routeMgr->isRouteActive()) {
1331 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1335 int index = _scratchNode->getIntValue("index", -9999);
1338 if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1339 index = _routeMgr->currentIndex();
1342 _searchIsRoute = true;
1343 setScratchFromRouteWaypoint(index);
1346 void GPS::setScratchFromRouteWaypoint(int aIndex)
1348 assert(_searchIsRoute);
1349 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1350 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1354 _searchResultIndex = aIndex;
1355 WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1356 _scratchNode->setStringValue("ident", wp->ident());
1357 _scratchPos = wp->position();
1358 _scratchValid = true;
1359 _scratchNode->setIntValue("index", aIndex);
1362 void GPS::loadNearest()
1364 string sty(_scratchNode->getStringValue("type"));
1365 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1366 if (ty == FGPositioned::INVALID) {
1367 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1371 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1372 int limitCount = _scratchNode->getIntValue("max-results", 1);
1373 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1375 SGGeod searchPos = _indicated_pos;
1376 if (isScratchPositionValid()) {
1377 searchPos = _scratchPos;
1380 clearScratch(); // clear now, regardless of whether we find a match or not
1383 FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1384 _searchResultIndex = 0;
1385 _searchIsRoute = false;
1387 if (_searchResults.empty()) {
1388 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1392 setScratchFromCachedSearchResult();
1395 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1397 switch (aPos->type()) {
1398 case FGPositioned::AIRPORT:
1399 // heliport and seaport too?
1400 case FGPositioned::VOR:
1401 case FGPositioned::NDB:
1402 case FGPositioned::FIX:
1403 case FGPositioned::TACAN:
1404 case FGPositioned::WAYPOINT:
1411 FGPositioned::Type GPS::SearchFilter::minType() const
1413 return FGPositioned::AIRPORT;
1416 FGPositioned::Type GPS::SearchFilter::maxType() const
1418 return FGPositioned::WAYPOINT;
1421 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1423 if (aTy == FGPositioned::AIRPORT) {
1424 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1427 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1428 if (aTy == FGPositioned::INVALID) {
1429 return new SearchFilter;
1432 return new FGPositioned::TypeFilter(aTy);
1437 // parse search terms into local members, and exec the first search
1438 string sty(_scratchNode->getStringValue("type"));
1439 _searchType = FGPositioned::typeFromName(sty);
1440 _searchQuery = _scratchNode->getStringValue("query");
1441 if (_searchQuery.empty()) {
1442 SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1447 _searchExact = _scratchNode->getBoolValue("exact", true);
1448 _searchResultIndex = 0;
1449 _searchIsRoute = false;
1451 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1453 _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1455 _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1458 bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1460 FGPositioned::sortByRange(_searchResults, _indicated_pos);
1463 if (_searchResults.empty()) {
1468 setScratchFromCachedSearchResult();
1471 bool GPS::getScratchHasNext() const
1474 if (_searchIsRoute) {
1475 lastResult = _routeMgr->numWaypts() - 1;
1477 lastResult = (int) _searchResults.size() - 1;
1480 if (lastResult < 0) { // search array might be empty
1484 return (_searchResultIndex < lastResult);
1487 void GPS::setScratchFromCachedSearchResult()
1489 int index = _searchResultIndex;
1491 if ((index < 0) || (index >= (int) _searchResults.size())) {
1492 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1496 setScratchFromPositioned(_searchResults[index], index);
1499 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1504 _scratchPos = aPos->geod();
1505 _scratchNode->setStringValue("name", aPos->name());
1506 _scratchNode->setStringValue("ident", aPos->ident());
1507 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1510 _scratchNode->setIntValue("index", aIndex);
1513 _scratchValid = true;
1514 _scratchNode->setIntValue("result-count", _searchResults.size());
1516 switch (aPos->type()) {
1517 case FGPositioned::VOR:
1518 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1521 case FGPositioned::NDB:
1522 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1525 case FGPositioned::AIRPORT:
1526 addAirportToScratch((FGAirport*)aPos);
1534 // look for being on the route and set?
1537 void GPS::addAirportToScratch(FGAirport* aAirport)
1539 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1540 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1541 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1542 // TODO - filter out unsuitable runways in the future
1543 // based on config again
1545 rwyNd->setStringValue("id", rwy->ident().c_str());
1546 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1547 rwyNd->setIntValue("width-ft", rwy->widthFt());
1548 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1549 // map surface code to a string
1550 // TODO - lighting information
1553 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1555 } // of runways iteration
1559 void GPS::selectOBSMode()
1561 if (!isScratchPositionValid()) {
1565 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1568 _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1569 _wp0_position = _indicated_pos;
1573 void GPS::selectLegMode()
1575 if (_mode == "leg") {
1579 if (!_routeMgr->isRouteActive()) {
1580 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1584 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1587 // depending on the situation, this will either get over-written
1588 // in routeManagerSequenced or not; either way it does no harm to
1590 _wp0_position = _indicated_pos;
1592 // not really sequenced, but does all the work of updating wp0/1
1593 routeManagerSequenced();
1596 void GPS::nextResult()
1598 if (!getScratchHasNext()) {
1603 if (_searchIsRoute) {
1604 setScratchFromRouteWaypoint(++_searchResultIndex);
1606 ++_searchResultIndex;
1607 setScratchFromCachedSearchResult();
1611 void GPS::previousResult()
1613 if (_searchResultIndex <= 0) {
1618 --_searchResultIndex;
1620 if (_searchIsRoute) {
1621 setScratchFromRouteWaypoint(_searchResultIndex);
1623 setScratchFromCachedSearchResult();
1627 void GPS::defineWaypoint()
1629 if (!isScratchPositionValid()) {
1630 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1634 string ident = _scratchNode->getStringValue("ident");
1635 if (ident.size() < 2) {
1636 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1640 // check for duplicate idents
1641 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1642 FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1643 if (!dups.empty()) {
1644 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1647 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1648 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1649 _searchResults.clear();
1650 _searchResults.push_back(wpt);
1651 setScratchFromPositioned(wpt.get(), -1);
1654 void GPS::insertWaypointAtIndex(int aIndex)
1656 // note we do allow index = routeMgr->size(), that's an append
1657 if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1658 throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1661 if (!isScratchPositionValid()) {
1662 SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1666 string ident = _scratchNode->getStringValue("ident");
1668 WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1669 _routeMgr->insertWayptAtIndex(wpt, aIndex);
1672 void GPS::removeWaypointAtIndex(int aIndex)
1674 if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1675 throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1678 _routeMgr->removeWayptAtIndex(aIndex);
1681 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
1682 const char* lonStr, const char* latStr, const char* altStr)
1684 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1685 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1688 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1692 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
1693 const char* lonStr, const char* latStr, const char* altStr)
1695 tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1696 tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1699 tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));