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.
15 #include "Main/fg_props.hxx"
16 #include "Main/globals.hxx" // for get_subsystem
17 #include "Main/util.hxx" // for fgLowPass
18 #include "Navaids/positioned.hxx"
19 #include "Navaids/navrecord.hxx"
20 #include "Airports/simple.hxx"
21 #include "Airports/runways.hxx"
22 #include "Autopilot/route_mgr.hxx"
24 #include <simgear/math/sg_random.h>
25 #include <simgear/sg_inlines.h>
26 #include <simgear/math/sg_geodesy.hxx>
31 ///////////////////////////////////////////////////////////////////
33 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
35 _lon = base->getChild(lonStr, 0, true);
36 _lat = base->getChild(latStr, 0, true);
38 _alt = base->getChild(altStr, 0, true);
42 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
44 _lon = fgGetNode(lonStr, true);
45 _lat = fgGetNode(latStr, true);
47 _alt = fgGetNode(altStr, true);
51 void SGGeodProperty::clear()
53 _lon = _lat = _alt = NULL;
56 void SGGeodProperty::operator=(const SGGeod& geod)
58 _lon->setDoubleValue(geod.getLongitudeDeg());
59 _lat->setDoubleValue(geod.getLatitudeDeg());
61 _alt->setDoubleValue(geod.getElevationFt());
65 SGGeod SGGeodProperty::get() const
67 double lon = _lon->getDoubleValue(),
68 lat = _lat->getDoubleValue();
70 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
72 return SGGeod::fromDeg(lon,lat);
76 static void tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
77 const char* lonStr, const char* latStr, const char* altStr)
79 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
80 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
83 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
87 static void tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
88 const char* lonStr, const char* latStr, const char* altStr)
90 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
91 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
94 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
98 static const char* makeTTWString(double TTW)
100 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
104 unsigned int TTW_seconds = (int) (TTW + 0.5);
105 unsigned int TTW_minutes = 0;
106 unsigned int TTW_hours = 0;
107 static char TTW_str[9];
108 TTW_hours = TTW_seconds / 3600;
109 TTW_minutes = (TTW_seconds / 60) % 60;
110 TTW_seconds = TTW_seconds % 60;
111 snprintf(TTW_str, 9, "%02d:%02d:%02d",
112 TTW_hours, TTW_minutes, TTW_seconds);
116 /////////////////////////////////////////////////////////////////////////////
118 class GPSListener : public SGPropertyChangeListener
121 GPSListener(GPS *m) :
125 virtual void valueChanged (SGPropertyNode * prop)
132 if (prop == _gps->_route_current_wp_node) {
133 _gps->routeManagerSequenced();
134 } else if (prop == _gps->_route_active_node) {
135 _gps->routeActivated();
136 } else if (prop == _gps->_ref_navaid_id_node) {
137 _gps->referenceNavaidSet(prop->getStringValue(""));
143 void setGuard(bool g) {
148 bool _guard; // re-entrancy guard
151 ////////////////////////////////////////////////////////////////////////////
153 * Helper to monitor for Nasal or other code accessing properties we haven't
154 * defined. For the moment we complain about all such activites, since various
155 * users assume all kinds of weird, wonderful and non-existent interfaces.
158 class DeprecatedPropListener : public SGPropertyChangeListener
161 DeprecatedPropListener(SGPropertyNode* gps)
163 _parents.insert(gps);
164 SGPropertyNode* wp = gps->getChild("wp");
166 _parents.insert(wp->getChild("wp", 0));
167 _parents.insert(wp->getChild("wp", 1));
169 std::set<SGPropertyNode*>::iterator it;
170 for (it = _parents.begin(); it != _parents.end(); ++it) {
171 (*it)->addChangeListener(this);
175 virtual void valueChanged (SGPropertyNode * prop)
179 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
181 if (isDeprecated(parent, child)) {
182 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
183 << child->getPath(true));
187 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
189 if (_parents.count(parent) < 1) {
193 // no child exclusions yet
197 std::set<SGPropertyNode*> _parents;
200 ////////////////////////////////////////////////////////////////////////////
201 // configuration helper object
203 GPS::Config::Config() :
204 _enableTurnAnticipation(true),
205 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
206 _overflightArmDistance(0.5),
207 _waypointAlertTime(30.0),
208 _tuneRadio1ToRefVor(true),
209 _minRunwayLengthFt(0.0),
210 _requireHardSurface(true),
211 _cdiMaxDeflectionNm(-1) // default to angular mode
213 _enableTurnAnticipation = false;
214 _obsCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
217 void GPS::Config::init(SGPropertyNode* aCfgNode)
219 aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
220 aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
221 aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
222 aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
223 aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
224 aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
226 aCfgNode->tie("obs-course-source", SGRawValueMethods<GPS::Config, const char*>
227 (*this, &GPS::Config::getOBSCourseSource, &GPS::Config::setOBSCourseSource));
229 aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
233 GPS::Config::getOBSCourseSource() const
235 if (!_obsCourseSource) {
239 return _obsCourseSource->getPath(true);
243 GPS::Config::setOBSCourseSource(const char* aPath)
245 SGPropertyNode* nd = fgGetNode(aPath, false);
247 SG_LOG(SG_INSTR, SG_WARN, "couldn't find OBS course source at:" << aPath);
248 _obsCourseSource = NULL;
251 _obsCourseSource = nd;
255 GPS::Config::getOBSCourse() const
257 if (!_obsCourseSource) {
261 return _obsCourseSource->getDoubleValue();
264 ////////////////////////////////////////////////////////////////////////////
266 GPS::GPS ( SGPropertyNode *node) :
268 _name(node->getStringValue("name", "gps")),
269 _num(node->getIntValue("number", 0)),
270 _computeTurnData(false),
271 _anticipateTurn(false),
283 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
287 branch = "/instrumentation/" + _name;
289 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
290 _config.init(node->getChild("config", 0, true));
292 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
293 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
294 _serviceable_node = node->getChild("serviceable", 0, true);
295 _serviceable_node->setBoolValue(true);
296 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
299 node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
301 _raim_node = node->getChild("raim", 0, true);
303 tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg",
304 "indicated-latitude-deg", "indicated-altitude-ft");
306 node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
307 (*this, &GPS::getVerticalSpeed, NULL));
308 node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
309 (*this, &GPS::getTrueTrack, NULL));
310 node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
311 (*this, &GPS::getMagTrack, NULL));
312 node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
313 (*this, &GPS::getGroundspeedKts, NULL));
315 _odometer_node = node->getChild("odometer", 0, true);
316 _trip_odometer_node = node->getChild("trip-odometer", 0, true);
317 _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
318 _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
322 node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
323 node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
325 _scratchNode = node->getChild("scratch", 0, true);
326 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
327 _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
328 _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
329 _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
330 _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
331 _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
332 _scratchValid = false;
334 // waypoint data (including various historical things)
335 SGPropertyNode *wp_node = node->getChild("wp", 0, true);
336 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
337 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
339 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
340 wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
341 (*this, &GPS::getWP0Ident, NULL));
342 wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
343 (*this, &GPS::getWP0Name, NULL));
345 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
346 wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
347 (*this, &GPS::getWP1Ident, NULL));
348 wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
349 (*this, &GPS::getWP1Name, NULL));
351 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
352 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
353 wp1Crs->alias(node->getChild("selected-course-deg"));
355 // _true_wp1_bearing_error_node =
356 // wp1_node->getChild("true-bearing-error-deg", 0, true);
357 // _magnetic_wp1_bearing_error_node =
358 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
360 wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
361 (*this, &GPS::getWP1Distance, NULL));
362 wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
363 (*this, &GPS::getWP1Bearing, NULL));
364 wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
365 (*this, &GPS::getWP1MagBearing, NULL));
366 wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
367 (*this, &GPS::getWP1TTW, NULL));
368 wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
369 (*this, &GPS::getWP1TTWString, NULL));
371 wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
372 (*this, &GPS::getWP1CourseDeviation, NULL));
373 wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
374 (*this, &GPS::getWP1CourseErrorNm, NULL));
375 wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
376 (*this, &GPS::getWP1ToFlag, NULL));
378 _tracking_bug_node = node->getChild("tracking-bug", 0, true);
380 // leg properties (only valid in DTO/LEG modes, not OBS)
381 wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
382 wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
383 wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
384 wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
387 SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
388 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
389 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
390 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
391 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
392 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
393 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
394 _ref_navaid_elapsed = 0.0;
395 _ref_navaid_set = false;
398 // should these move to the route manager?
399 _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
400 _routeETE = node->getChild("ETE", 0, true);
402 // disable auto-sequencing in the route manager; we'll deal with it
403 // ourselves using turn anticipation
404 SGPropertyNode_ptr autoSeq = fgGetNode("/autopilot/route-manager/auto-sequence", true);
405 autoSeq->setBoolValue(false);
407 // add listener to various things
408 _listener = new GPSListener(this);
409 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
410 _route_current_wp_node->addChangeListener(_listener);
411 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
412 _route_active_node->addChangeListener(_listener);
414 _ref_navaid_id_node->addChangeListener(_listener);
416 // navradio slaving properties
417 node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
418 (*this, &GPS::getCDIDeflection));
420 SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
421 toFlag->alias(wp1_node->getChild("to-flag"));
423 _fromFlagNode = node->getChild("from-flag", 0, true);
425 // last thing, add the deprecated prop watcher
426 new DeprecatedPropListener(node);
433 _last_speed_kts = 0.0;
434 _last_pos = SGGeod();
435 _indicated_pos = SGGeod();
436 _last_vertical_speed = 0.0;
437 _last_true_track = 0.0;
439 _raim_node->setDoubleValue(false);
440 _indicated_pos = SGGeod();
442 _wp1TrueBearing = 0.0;
443 _wp1_position = SGGeod();
444 _odometer_node->setDoubleValue(0);
445 _trip_odometer_node->setDoubleValue(0);
446 _tracking_bug_node->setDoubleValue(0);
447 _true_bug_error_node->setDoubleValue(0);
448 _magnetic_bug_error_node->setDoubleValue(0);
450 _fromFlagNode->setBoolValue(false);
454 GPS::update (double delta_time_sec)
456 // If it's off, don't bother.
457 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
462 if (delta_time_sec <= 0.0) {
463 return; // paused, don't bother
465 // TODO: Add noise and other errors.
468 // Bias and random error
469 double random_factor = sg_random();
470 double random_error = 1.4;
471 double error_radius = 5.1;
472 double bias_max_radius = 5.1;
473 double random_max_radius = 1.4;
475 bias_length += (random_factor-0.5) * 1.0e-3;
476 if (bias_length <= 0.0) bias_length = 0.0;
477 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
478 bias_angle += (random_factor-0.5) * 1.0e-3;
479 if (bias_angle <= 0.0) bias_angle = 0.0;
480 else if (bias_angle >= 360.0) bias_angle = 360.0;
482 double random_length = random_factor * random_max_radius;
483 double random_angle = random_factor * 360.0;
485 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
486 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
487 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
488 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
489 double error_x = bias_x + random_x;
490 double error_y = bias_y + random_y;
491 double error_length = sqrt(error_x*error_x + error_y*error_y);
492 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
497 geo_direct_wgs_84 ( altitude_m, latitude_deg,
498 longitude_deg, error_angle,
499 error_length, &lat2, &lon2,
501 //cout << lat2 << " " << lon2 << endl;
502 printf("%f %f \n", bias_length, bias_angle);
503 printf("%3.7f %3.7f \n", lat2, lon2);
504 printf("%f %f \n", error_length, error_angle);
507 _raim_node->setBoolValue(true);
508 _indicated_pos = _position.get();
511 updateWithValid(delta_time_sec);
515 if (_route_active_node->getBoolValue()) {
516 // GPS init with active route
517 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
518 _listener->setGuard(true);
520 routeManagerSequenced();
521 _listener->setGuard(false);
525 _last_pos = _indicated_pos;
529 GPS::updateWithValid(double dt)
535 if (_mode == "obs") {
536 _selectedCourse = _config.getOBSCourse();
543 updateReferenceNavaid(dt);
548 GPS::updateBasicData(double dt)
552 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
554 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
555 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
556 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
558 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/20.0);
559 _last_speed_kts = speed_kt;
561 double odometer = _odometer_node->getDoubleValue();
562 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
563 odometer = _trip_odometer_node->getDoubleValue();
564 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
568 GPS::updateTrackingBug()
570 double tracking_bug = _tracking_bug_node->getDoubleValue();
571 double true_bug_error = tracking_bug - getTrueTrack();
572 double magnetic_bug_error = tracking_bug - getMagTrack();
574 // Get the errors into the (-180,180) range.
575 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
576 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
578 _true_bug_error_node->setDoubleValue(true_bug_error);
579 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
583 GPS::updateWaypoints()
586 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
587 bool toWp = getWP1ToFlag();
588 _fromFlagNode->setBoolValue(!toWp);
591 void GPS::updateReferenceNavaid(double dt)
593 if (!_ref_navaid_set) {
594 _ref_navaid_elapsed += dt;
595 if (_ref_navaid_elapsed > 5.0) {
596 _ref_navaid_elapsed = 0.0;
598 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
599 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
601 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
602 _ref_navaid_id_node->setStringValue("");
603 _ref_navaid_name_node->setStringValue("");
604 _ref_navaid_bearing_node->setDoubleValue(0.0);
605 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
606 _ref_navaid_distance_node->setDoubleValue(0.0);
607 _ref_navaid_frequency_node->setStringValue("");
608 } else if (nav != _ref_navaid) {
609 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
610 _listener->setGuard(true);
611 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
612 _ref_navaid_name_node->setStringValue(nav->name().c_str());
613 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
614 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
615 _listener->setGuard(false);
618 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
626 double trueCourse, distanceM, az2;
627 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
628 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
629 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
630 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
634 void GPS::referenceNavaidSet(const std::string& aNavaid)
637 // allow setting an empty string to restore normal nearest-vor selection
638 if (aNavaid.size() > 0) {
639 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
640 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
641 _position.get(), &vorFilter);
644 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
649 _ref_navaid_set = true;
650 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
651 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
652 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
653 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
654 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
657 _ref_navaid_set = false;
658 _ref_navaid_elapsed = 9999.0; // update next tick
662 void GPS::tuneNavRadios()
664 if (!_ref_navaid || !_config.tuneNavRadioToRefVor()) {
668 SGPropertyNode_ptr navRadio1 = fgGetNode("/instrumentation/nav", false);
673 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
674 SGPropertyNode_ptr freqs = navRadio1->getChild("frequencies");
675 freqs->setDoubleValue("selected-mhz", vor->get_freq() / 100.0);
678 void GPS::routeActivated()
680 if (_route_active_node->getBoolValue()) {
681 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
683 _computeTurnData = true;
684 } else if (_mode == "leg") {
685 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
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->currentWaypoint(),
698 count = _routeMgr->size();
699 if ((index < 1) || (index >= count)) {
700 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
704 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
705 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
706 SGWayPoint wp1(_routeMgr->get_waypoint(index));
708 _wp0Ident = wp0.get_id();
709 _wp0Name = wp0.get_name();
710 _wp0_position = wp0.get_target();
712 _wp1Ident = wp1.get_id();
713 _wp1Name = wp1.get_name();
714 _wp1_position = wp1.get_target();
716 _selectedCourse = getLegMagCourse();
719 void GPS::updateTurn()
721 bool printProgress = false;
723 if (_computeTurnData) {
724 if (_last_speed_kts < 60) {
725 // need valid leg course and sensible ground speed to compute the turn
730 printProgress = true;
733 if (!_anticipateTurn) {
739 // find bearing to turn centre
740 double bearing, az2, distanceM;
741 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
742 double progress = computeTurnProgress(bearing);
745 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
748 if (!_inTurn && (progress > 0.0)) {
752 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
753 _turnSequenced = true;
754 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
755 _routeMgr->sequence();
758 if (_inTurn && (progress >= 1.0)) {
763 // drive deviation and desired course
764 double desiredCourse = bearing - copysign(90, _turnAngle);
765 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
766 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
767 double deviationDeg = desiredCourse - getMagTrack();
768 deviationNm = copysign(deviationNm, deviationDeg);
770 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
771 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
772 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
776 void GPS::updateOverflight()
778 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
782 if (getWP1ToFlag()) {
783 return; // still heading towards the WP
786 if (_mode == "dto") {
787 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
789 // check for wp1 being on active route - resume leg mode
790 if (_routeMgr->isRouteActive()) {
791 int index = _routeMgr->findWaypoint(_wp1_position);
793 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
795 _routeMgr->jumpToIndex(index);
798 } else if (_mode == "leg") {
799 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
800 _routeMgr->sequence();
801 } else if (_mode == "obs") {
802 // nothing to do here, TO/FROM will update but that's fine
805 _computeTurnData = true;
808 void GPS::beginTurn()
811 _turnSequenced = false;
812 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
818 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
819 _computeTurnData = true;
822 double GPS::computeTurnProgress(double aBearing) const
824 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
825 return (aBearing - startBearing) / _turnAngle;
828 void GPS::computeTurnData()
830 _computeTurnData = false;
831 if (_mode != "leg") { // and approach modes in the future
832 _anticipateTurn = false;
836 int curIndex = _routeMgr->currentWaypoint();
837 if ((curIndex + 1) >= _routeMgr->size()) {
838 _anticipateTurn = false;
842 if (!_config.turnAnticipationEnabled()) {
843 _anticipateTurn = false;
847 _turnStartBearing = _selectedCourse;
848 // compute next leg course
849 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
850 wp2(_routeMgr->get_waypoint(curIndex + 1));
852 wp2.CourseAndDistance(wp1, &crs, &dist);
855 // compute offset bearing
856 _turnAngle = crs - _turnStartBearing;
857 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
858 double median = _turnStartBearing + (_turnAngle * 0.5);
859 double offsetBearing = median + copysign(90, _turnAngle);
860 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
862 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
863 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
864 << ", offset=" << offsetBearing);
866 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
868 _turnPt = _wp1_position;
869 _anticipateTurn = true;
872 void GPS::updateTurnData()
874 // depends on ground speed, so needs to be updated per-frame
875 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
877 // compute the turn centre, based on the turn radius.
878 // key thing is to understand that we're working a right-angle triangle,
879 // where the right-angle is the point we start the turn. From that point,
880 // one side is the inbound course to the turn pt, and the other is the
881 // perpendicular line, of length 'r', to the turn centre.
882 // the triangle's hypotenuse, which we need to find, is the distance from the
883 // turn pt to the turn center (in the direction of the offset bearing)
884 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
886 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
887 double d = _turnRadius / cos(halfTurnAngle);
889 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
890 // << " (cut distance=" << d - _turnRadius << ")");
892 double median = _turnStartBearing + (_turnAngle * 0.5);
893 double offsetBearing = median + copysign(90, _turnAngle);
894 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
897 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
900 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
902 // turn time is seconds to execute a 360 turn.
903 double turnTime = 360.0 / _config.turnRateDegSec();
905 // c is ground distance covered in that time (circumference of the circle)
906 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
908 // divide by 2PI to go from circumference -> radius
909 return c / (2 * M_PI);
912 void GPS::updateRouteData()
914 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
915 // walk all waypoints from wp2 to route end, and sum
916 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
917 totalDistance += _routeMgr->get_waypoint(i).get_distance();
920 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
921 if (_last_speed_kts > 1.0) {
922 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
923 _routeETE->setStringValue(makeTTWString(TTW));
927 /////////////////////////////////////////////////////////////////////////////
928 // property getter/setters
930 double GPS::getLegDistance() const
932 if (!_last_valid || (_mode == "obs")) {
936 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
939 double GPS::getLegCourse() const
941 if (!_last_valid || (_mode == "obs")) {
945 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
948 double GPS::getLegMagCourse() const
950 if (!_last_valid || (_mode == "obs")) {
954 double m = getLegCourse() - _magvar_node->getDoubleValue();
955 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
959 double GPS::getAltDistanceRatio() const
961 if (!_last_valid || (_mode == "obs")) {
965 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
970 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
971 return alt_difference_m / dist;
974 double GPS::getMagTrack() const
980 double m = getTrueTrack() - _magvar_node->getDoubleValue();
981 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
985 double GPS::getCDIDeflection() const
992 if (_config.cdiDeflectionIsAngular()) {
993 defl = getWP1CourseDeviation();
994 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
996 double fullScale = _config.cdiDeflectionLinearPeg();
997 double normError = getWP1CourseErrorNm() / fullScale;
998 SG_CLAMP_RANGE(normError, -1.0, 1.0);
999 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1005 const char* GPS::getWP0Ident() const
1007 if (!_last_valid || (_mode != "leg")) {
1011 return _wp0Ident.c_str();
1014 const char* GPS::getWP0Name() const
1016 if (!_last_valid || (_mode != "leg")) {
1020 return _wp0Name.c_str();
1023 const char* GPS::getWP1Ident() const
1029 return _wp1Ident.c_str();
1032 const char* GPS::getWP1Name() const
1038 return _wp1Name.c_str();
1041 double GPS::getWP1Distance() const
1047 return _wp1DistanceM * SG_METER_TO_NM;
1050 double GPS::getWP1TTW() const
1056 if (_last_speed_kts < 1.0) {
1060 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1063 const char* GPS::getWP1TTWString() const
1069 return makeTTWString(getWP1TTW());
1072 double GPS::getWP1Bearing() const
1078 return _wp1TrueBearing;
1081 double GPS::getWP1MagBearing() const
1087 return _wp1TrueBearing - _magvar_node->getDoubleValue();
1090 double GPS::getWP1CourseDeviation() const
1096 double dev = getWP1MagBearing() - _selectedCourse;
1097 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1099 if (fabs(dev) > 90.0) {
1100 // When the course is away from the waypoint,
1101 // it makes sense to change the sign of the deviation.
1103 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1109 double GPS::getWP1CourseErrorNm() const
1115 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1116 double course_error_m = sin(radDev) * _wp1DistanceM;
1117 return course_error_m * SG_METER_TO_NM;
1120 bool GPS::getWP1ToFlag() const
1126 double dev = getWP1MagBearing() - _selectedCourse;
1127 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1129 return (fabs(dev) < 90.0);
1132 double GPS::getScratchDistance() const
1134 if (!_scratchValid) {
1138 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1141 double GPS::getScratchTrueBearing() const
1143 if (!_scratchValid) {
1147 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1150 double GPS::getScratchMagBearing() const
1152 if (!_scratchValid) {
1156 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1157 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1161 /////////////////////////////////////////////////////////////////////////////
1162 // command / scratch / search system
1164 void GPS::setCommand(const char* aCmd)
1166 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1168 if (!strcmp(aCmd, "direct")) {
1170 } else if (!strcmp(aCmd, "obs")) {
1172 } else if (!strcmp(aCmd, "leg")) {
1174 } else if (!strcmp(aCmd, "load-route-wpt")) {
1175 loadRouteWaypoint();
1176 } else if (!strcmp(aCmd, "nearest")) {
1178 } else if (!strcmp(aCmd, "search")) {
1179 _searchNames = false;
1181 } else if (!strcmp(aCmd, "search-names")) {
1182 _searchNames = true;
1184 } else if (!strcmp(aCmd, "next")) {
1186 } else if (!strcmp(aCmd, "previous")) {
1188 } else if (!strcmp(aCmd, "define-user-wpt")) {
1191 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognzied command:" << aCmd);
1195 void GPS::clearScratch()
1197 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1198 _scratchValid = false;
1199 _scratchNode->setStringValue("type", "");
1200 _scratchNode->setStringValue("query", "");
1203 bool GPS::isScratchPositionValid() const
1205 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1206 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1213 void GPS::directTo()
1215 if (!isScratchPositionValid()) {
1216 SG_LOG(SG_INSTR, SG_WARN, "invalid DTO lat/lon");
1220 _wp0_position = _indicated_pos;
1221 _wp1Ident = _scratchNode->getStringValue("ident");
1222 _wp1Name = _scratchNode->getStringValue("name");
1223 _wp1_position = _scratchPos;
1226 _selectedCourse = getLegMagCourse();
1230 void GPS::loadRouteWaypoint()
1232 _scratchValid = false;
1233 // if (!_routeMgr->isRouteActive()) {
1234 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1238 int index = _scratchNode->getIntValue("index", -9999);
1241 if (index == -9999) { // no index supplied, use current wp
1242 index = _routeMgr->currentWaypoint();
1245 _searchIsRoute = true;
1246 setScratchFromRouteWaypoint(index);
1249 void GPS::setScratchFromRouteWaypoint(int aIndex)
1251 assert(_searchIsRoute);
1252 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1253 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1257 _searchResultIndex = aIndex;
1258 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1259 _scratchNode->setStringValue("name", wp.get_name());
1260 _scratchNode->setStringValue("ident", wp.get_id());
1261 _scratchPos = wp.get_target();
1262 _scratchValid = true;
1263 _scratchNode->setDoubleValue("course", wp.get_track());
1264 _scratchNode->setIntValue("index", aIndex);
1266 int lastResult = _routeMgr->size() - 1;
1267 _searchHasNext = (_searchResultIndex < lastResult);
1270 void GPS::loadNearest()
1272 string sty(_scratchNode->getStringValue("type"));
1273 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1274 if (ty == FGPositioned::INVALID) {
1275 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1279 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1280 int limitCount = _scratchNode->getIntValue("max-results", 1);
1281 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1283 clearScratch(); // clear now, regardless of whether we find a match or not
1286 FGPositioned::findClosestN(_indicated_pos, limitCount, cutoffDistance, f.get());
1287 _searchResultsCached = true;
1288 _searchResultIndex = 0;
1289 _searchIsRoute = false;
1290 _searchHasNext = false;
1292 if (_searchResults.empty()) {
1293 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1297 _searchHasNext = (_searchResults.size() > 1);
1298 setScratchFromCachedSearchResult();
1301 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1303 switch (aPos->type()) {
1304 case FGPositioned::AIRPORT:
1305 // heliport and seaport too?
1306 case FGPositioned::VOR:
1307 case FGPositioned::NDB:
1308 case FGPositioned::FIX:
1309 case FGPositioned::TACAN:
1310 case FGPositioned::WAYPOINT:
1317 FGPositioned::Type GPS::SearchFilter::minType() const
1319 return FGPositioned::AIRPORT;
1322 FGPositioned::Type GPS::SearchFilter::maxType() const
1324 return FGPositioned::WAYPOINT;
1327 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1329 if (aTy == FGPositioned::AIRPORT) {
1330 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1333 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1334 if (aTy == FGPositioned::INVALID) {
1335 return new SearchFilter;
1338 return new FGPositioned::TypeFilter(aTy);
1343 // parse search terms into local members, and exec the first search
1344 string sty(_scratchNode->getStringValue("type"));
1345 _searchType = FGPositioned::typeFromName(sty);
1346 _searchQuery = _scratchNode->getStringValue("query");
1347 _searchExact = _scratchNode->getBoolValue("exact", true);
1348 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1349 _searchResultIndex = 0;
1350 _searchIsRoute = false;
1351 _searchHasNext = false;
1353 if (_searchExact && _searchOrderByRange) {
1354 // immediate mode search, get all the results now and cache them
1355 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1357 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1359 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1362 _searchResultsCached = true;
1364 if (_searchResults.empty()) {
1369 _searchHasNext = (_searchResults.size() > 1);
1370 setScratchFromCachedSearchResult();
1372 // iterative search, look up result zero
1373 _searchResultsCached = false;
1378 void GPS::performSearch()
1380 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1385 if (_searchOrderByRange) {
1386 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1388 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1391 if (_searchOrderByRange) {
1392 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1394 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1402 setScratchFromPositioned(r.get(), _searchResultIndex);
1405 void GPS::setScratchFromCachedSearchResult()
1407 assert(_searchResultsCached);
1408 int index = _searchResultIndex;
1410 if ((index < 0) || (index >= (int) _searchResults.size())) {
1411 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1415 setScratchFromPositioned(_searchResults[index], index);
1417 int lastResult = (int) _searchResults.size() - 1;
1418 _searchHasNext = (_searchResultIndex < lastResult);
1421 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1426 _scratchPos = aPos->geod();
1427 _scratchNode->setStringValue("name", aPos->name());
1428 _scratchNode->setStringValue("ident", aPos->ident());
1429 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1432 _scratchNode->setIntValue("index", aIndex);
1435 _scratchValid = true;
1436 if (_searchResultsCached) {
1437 _scratchNode->setIntValue("result-count", _searchResults.size());
1440 switch (aPos->type()) {
1441 case FGPositioned::VOR:
1442 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1445 case FGPositioned::NDB:
1446 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1449 case FGPositioned::AIRPORT:
1450 addAirportToScratch((FGAirport*)aPos);
1458 // look for being on the route and set?
1461 void GPS::addAirportToScratch(FGAirport* aAirport)
1463 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1464 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1465 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1466 // TODO - filter out unsuitable runways in the future
1467 // based on config again
1469 rwyNd->setStringValue("id", rwy->ident().c_str());
1470 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1471 rwyNd->setIntValue("width-ft", rwy->widthFt());
1472 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1473 // map surface code to a string
1474 // TODO - lighting information
1477 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1479 } // of runways iteration
1483 void GPS::selectOBSMode()
1485 if (!isScratchPositionValid()) {
1486 SG_LOG(SG_INSTR, SG_WARN, "invalid OBS lat/lon");
1490 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1493 _wp1Ident = _scratchNode->getStringValue("ident");
1494 _wp1Name = _scratchNode->getStringValue("name");
1495 _wp1_position = _scratchPos;
1496 _wp0_position = _indicated_pos;
1499 void GPS::selectLegMode()
1501 if (_mode == "leg") {
1505 if (!_routeMgr->isRouteActive()) {
1506 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1510 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1513 // not really sequenced, but does all the work of updating wp0/1
1514 routeManagerSequenced();
1517 void GPS::nextResult()
1519 if (!_searchHasNext) {
1524 if (_searchIsRoute) {
1525 setScratchFromRouteWaypoint(++_searchResultIndex);
1526 } else if (_searchResultsCached) {
1527 ++_searchResultIndex;
1528 setScratchFromCachedSearchResult();
1530 ++_searchResultIndex;
1532 } // of iterative search case
1535 void GPS::previousResult()
1537 if (_searchResultIndex <= 0) {
1542 --_searchResultIndex;
1544 if (_searchIsRoute) {
1545 setScratchFromRouteWaypoint(_searchResultIndex);
1546 } else if (_searchResultsCached) {
1547 setScratchFromCachedSearchResult();
1553 void GPS::defineWaypoint()
1555 if (!isScratchPositionValid()) {
1556 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1560 string ident = _scratchNode->getStringValue("ident");
1561 if (ident.size() < 2) {
1562 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1566 // check for duplicate idents
1567 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1568 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1569 if (!dups.empty()) {
1570 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1573 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1574 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1575 _searchResultsCached = false;
1576 setScratchFromPositioned(wpt.get(), -1);