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.
14 #include "Main/fg_props.hxx"
15 #include "Main/globals.hxx" // for get_subsystem
16 #include "Main/util.hxx" // for fgLowPass
17 #include "Navaids/positioned.hxx"
18 #include "Navaids/navrecord.hxx"
19 #include "Airports/simple.hxx"
20 #include "Airports/runways.hxx"
21 #include "Autopilot/route_mgr.hxx"
23 #include <simgear/math/sg_random.h>
24 #include <simgear/sg_inlines.h>
25 #include <simgear/math/sg_geodesy.hxx>
29 ///////////////////////////////////////////////////////////////////
31 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
33 _lon = base->getChild(lonStr, 0, true);
34 _lat = base->getChild(latStr, 0, true);
36 _alt = base->getChild(altStr, 0, true);
40 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
42 _lon = fgGetNode(lonStr, true);
43 _lat = fgGetNode(latStr, true);
45 _alt = fgGetNode(altStr, true);
49 void SGGeodProperty::clear()
51 _lon = _lat = _alt = NULL;
54 void SGGeodProperty::operator=(const SGGeod& geod)
56 _lon->setDoubleValue(geod.getLongitudeDeg());
57 _lat->setDoubleValue(geod.getLatitudeDeg());
59 _alt->setDoubleValue(geod.getElevationFt());
63 SGGeod SGGeodProperty::get() const
65 double lon = _lon->getDoubleValue(),
66 lat = _lat->getDoubleValue();
68 return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
70 return SGGeod::fromDeg(lon,lat);
74 static void tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef,
75 const char* lonStr, const char* latStr, const char* altStr)
77 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
78 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
81 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
85 static void tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef,
86 const char* lonStr, const char* latStr, const char* altStr)
88 aNode->tie(lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
89 aNode->tie(latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
92 aNode->tie(altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
96 static const char* makeTTWString(double TTW)
98 if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
102 unsigned int TTW_seconds = (int) (TTW + 0.5);
103 unsigned int TTW_minutes = 0;
104 unsigned int TTW_hours = 0;
105 static char TTW_str[9];
106 TTW_hours = TTW_seconds / 3600;
107 TTW_minutes = (TTW_seconds / 60) % 60;
108 TTW_seconds = TTW_seconds % 60;
109 snprintf(TTW_str, 9, "%02d:%02d:%02d",
110 TTW_hours, TTW_minutes, TTW_seconds);
114 /////////////////////////////////////////////////////////////////////////////
116 class GPSListener : public SGPropertyChangeListener
119 GPSListener(GPS *m) :
123 virtual void valueChanged (SGPropertyNode * prop)
130 if (prop == _gps->_route_current_wp_node) {
131 _gps->routeManagerSequenced();
132 } else if (prop == _gps->_route_active_node) {
133 _gps->routeActivated();
134 } else if (prop == _gps->_ref_navaid_id_node) {
135 _gps->referenceNavaidSet(prop->getStringValue(""));
141 void setGuard(bool g) {
146 bool _guard; // re-entrancy guard
149 ////////////////////////////////////////////////////////////////////////////
151 * Helper to monitor for Nasal or other code accessing properties we haven't
152 * defined. For the moment we complain about all such activites, since various
153 * users assume all kinds of weird, wonderful and non-existent interfaces.
156 class DeprecatedPropListener : public SGPropertyChangeListener
159 DeprecatedPropListener(SGPropertyNode* gps)
161 _parents.insert(gps);
162 SGPropertyNode* wp = gps->getChild("wp");
164 _parents.insert(wp->getChild("wp", 0));
165 _parents.insert(wp->getChild("wp", 1));
167 std::set<SGPropertyNode*>::iterator it;
168 for (it = _parents.begin(); it != _parents.end(); ++it) {
169 (*it)->addChangeListener(this);
173 virtual void valueChanged (SGPropertyNode * prop)
177 virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
179 if (isDeprecated(parent, child)) {
180 SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
181 << child->getPath(true));
185 bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const
187 if (_parents.count(parent) < 1) {
191 // no child exclusions yet
195 std::set<SGPropertyNode*> _parents;
198 ////////////////////////////////////////////////////////////////////////////
199 // configuration helper object
201 GPS::Config::Config() :
202 _enableTurnAnticipation(true),
203 _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
204 _overflightArmDistance(0.5),
205 _waypointAlertTime(30.0),
206 _tuneRadio1ToRefVor(true),
207 _minRunwayLengthFt(0.0),
208 _requireHardSurface(true),
209 _cdiMaxDeflectionNm(-1) // default to angular mode
211 _enableTurnAnticipation = false;
212 _obsCourseSource = fgGetNode("/instrumentation/nav[0]/radials/selected-deg", true);
215 void GPS::Config::init(SGPropertyNode* aCfgNode)
217 aCfgNode->tie("turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
218 aCfgNode->tie("turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
219 aCfgNode->tie("wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
220 aCfgNode->tie("tune-nav-radio-to-ref-vor", SGRawValuePointer<bool>(&_tuneRadio1ToRefVor));
221 aCfgNode->tie("min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
222 aCfgNode->tie("hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
224 aCfgNode->tie("obs-course-source", SGRawValueMethods<GPS::Config, const char*>
225 (*this, &GPS::Config::getOBSCourseSource, &GPS::Config::setOBSCourseSource));
227 aCfgNode->tie("cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
231 GPS::Config::getOBSCourseSource() const
233 if (!_obsCourseSource) {
237 return _obsCourseSource->getPath(true);
241 GPS::Config::setOBSCourseSource(const char* aPath)
243 SGPropertyNode* nd = fgGetNode(aPath, false);
245 SG_LOG(SG_INSTR, SG_WARN, "couldn't find OBS course source at:" << aPath);
246 _obsCourseSource = NULL;
249 _obsCourseSource = nd;
253 GPS::Config::getOBSCourse() const
255 if (!_obsCourseSource) {
259 return _obsCourseSource->getDoubleValue();
262 ////////////////////////////////////////////////////////////////////////////
264 GPS::GPS ( SGPropertyNode *node) :
266 _name(node->getStringValue("name", "gps")),
267 _num(node->getIntValue("number", 0)),
268 _computeTurnData(false),
269 _anticipateTurn(false),
281 _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
285 branch = "/instrumentation/" + _name;
287 SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
288 _config.init(node->getChild("config", 0, true));
290 _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
291 _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
292 _serviceable_node = node->getChild("serviceable", 0, true);
293 _serviceable_node->setBoolValue(true);
294 _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
297 node->tie("selected-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getSelectedCourse, NULL));
299 _raim_node = node->getChild("raim", 0, true);
301 tieSGGeodReadOnly(node, _indicated_pos, "indicated-longitude-deg",
302 "indicated-latitude-deg", "indicated-altitude-ft");
304 node->tie("indicated-vertical-speed", SGRawValueMethods<GPS, double>
305 (*this, &GPS::getVerticalSpeed, NULL));
306 node->tie("indicated-track-true-deg", SGRawValueMethods<GPS, double>
307 (*this, &GPS::getTrueTrack, NULL));
308 node->tie("indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
309 (*this, &GPS::getMagTrack, NULL));
310 node->tie("indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
311 (*this, &GPS::getGroundspeedKts, NULL));
313 _odometer_node = node->getChild("odometer", 0, true);
314 _trip_odometer_node = node->getChild("trip-odometer", 0, true);
315 _true_bug_error_node = node->getChild("true-bug-error-deg", 0, true);
316 _magnetic_bug_error_node = node->getChild("magnetic-bug-error-deg", 0, true);
320 node->tie("mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
321 node->tie("command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
323 _scratchNode = node->getChild("scratch", 0, true);
324 tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
325 _scratchNode->tie("valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
326 _scratchNode->tie("distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
327 _scratchNode->tie("true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
328 _scratchNode->tie("mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
329 _scratchNode->tie("has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
330 _scratchValid = false;
332 // waypoint data (including various historical things)
333 SGPropertyNode *wp_node = node->getChild("wp", 0, true);
334 SGPropertyNode *wp0_node = wp_node->getChild("wp", 0, true);
335 SGPropertyNode *wp1_node = wp_node->getChild("wp", 1, true);
337 tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
338 wp0_node->tie("ID", SGRawValueMethods<GPS, const char*>
339 (*this, &GPS::getWP0Ident, NULL));
340 wp0_node->tie("name", SGRawValueMethods<GPS, const char*>
341 (*this, &GPS::getWP0Name, NULL));
343 tieSGGeodReadOnly(wp1_node, _wp1_position, "longitude-deg", "latitude-deg", "altitude-ft");
344 wp1_node->tie("ID", SGRawValueMethods<GPS, const char*>
345 (*this, &GPS::getWP1Ident, NULL));
346 wp1_node->tie("name", SGRawValueMethods<GPS, const char*>
347 (*this, &GPS::getWP1Name, NULL));
349 // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
350 SGPropertyNode* wp1Crs = wp1_node->getChild("desired-course-deg", 0, true);
351 wp1Crs->alias(node->getChild("selected-course-deg"));
353 // _true_wp1_bearing_error_node =
354 // wp1_node->getChild("true-bearing-error-deg", 0, true);
355 // _magnetic_wp1_bearing_error_node =
356 // wp1_node->getChild("magnetic-bearing-error-deg", 0, true);
358 wp1_node->tie("distance-nm", SGRawValueMethods<GPS, double>
359 (*this, &GPS::getWP1Distance, NULL));
360 wp1_node->tie("bearing-true-deg", SGRawValueMethods<GPS, double>
361 (*this, &GPS::getWP1Bearing, NULL));
362 wp1_node->tie("bearing-mag-deg", SGRawValueMethods<GPS, double>
363 (*this, &GPS::getWP1MagBearing, NULL));
364 wp1_node->tie("TTW-sec", SGRawValueMethods<GPS, double>
365 (*this, &GPS::getWP1TTW, NULL));
366 wp1_node->tie("TTW", SGRawValueMethods<GPS, const char*>
367 (*this, &GPS::getWP1TTWString, NULL));
369 wp1_node->tie("course-deviation-deg", SGRawValueMethods<GPS, double>
370 (*this, &GPS::getWP1CourseDeviation, NULL));
371 wp1_node->tie("course-error-nm", SGRawValueMethods<GPS, double>
372 (*this, &GPS::getWP1CourseErrorNm, NULL));
373 wp1_node->tie("to-flag", SGRawValueMethods<GPS, bool>
374 (*this, &GPS::getWP1ToFlag, NULL));
376 _tracking_bug_node = node->getChild("tracking-bug", 0, true);
378 // leg properties (only valid in DTO/LEG modes, not OBS)
379 wp_node->tie("leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
380 wp_node->tie("leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
381 wp_node->tie("leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
382 wp_node->tie("alt-dist-ratio", SGRawValueMethods<GPS, double>(*this, &GPS::getAltDistanceRatio, NULL));
385 SGPropertyNode_ptr ref_navaid = node->getChild("ref-navaid", 0, true);
386 _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
387 _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
388 _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
389 _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
390 _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
391 _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
392 _ref_navaid_elapsed = 0.0;
393 _ref_navaid_set = false;
396 // should these move to the route manager?
397 _routeDistanceNm = node->getChild("route-distance-nm", 0, true);
398 _routeETE = node->getChild("ETE", 0, true);
400 // disable auto-sequencing in the route manager; we'll deal with it
401 // ourselves using turn anticipation
402 SGPropertyNode_ptr autoSeq = fgGetNode("/autopilot/route-manager/auto-sequence", true);
403 autoSeq->setBoolValue(false);
405 // add listener to various things
406 _listener = new GPSListener(this);
407 _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
408 _route_current_wp_node->addChangeListener(_listener);
409 _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
410 _route_active_node->addChangeListener(_listener);
412 _ref_navaid_id_node->addChangeListener(_listener);
414 // navradio slaving properties
415 node->tie("cdi-deflection", SGRawValueMethods<GPS,double>
416 (*this, &GPS::getCDIDeflection));
418 SGPropertyNode* toFlag = node->getChild("to-flag", 0, true);
419 toFlag->alias(wp1_node->getChild("to-flag"));
421 _fromFlagNode = node->getChild("from-flag", 0, true);
423 // last thing, add the deprecated prop watcher
424 new DeprecatedPropListener(node);
431 _last_speed_kts = 0.0;
432 _last_pos = SGGeod();
433 _indicated_pos = SGGeod();
434 _last_vertical_speed = 0.0;
435 _last_true_track = 0.0;
437 _raim_node->setDoubleValue(false);
438 _indicated_pos = SGGeod();
440 _wp1TrueBearing = 0.0;
441 _wp1_position = SGGeod();
442 _odometer_node->setDoubleValue(0);
443 _trip_odometer_node->setDoubleValue(0);
444 _tracking_bug_node->setDoubleValue(0);
445 _true_bug_error_node->setDoubleValue(0);
446 _magnetic_bug_error_node->setDoubleValue(0);
448 _fromFlagNode->setBoolValue(false);
452 GPS::update (double delta_time_sec)
454 // If it's off, don't bother.
455 if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
460 if (delta_time_sec <= 0.0) {
461 return; // paused, don't bother
463 // TODO: Add noise and other errors.
466 // Bias and random error
467 double random_factor = sg_random();
468 double random_error = 1.4;
469 double error_radius = 5.1;
470 double bias_max_radius = 5.1;
471 double random_max_radius = 1.4;
473 bias_length += (random_factor-0.5) * 1.0e-3;
474 if (bias_length <= 0.0) bias_length = 0.0;
475 else if (bias_length >= bias_max_radius) bias_length = bias_max_radius;
476 bias_angle += (random_factor-0.5) * 1.0e-3;
477 if (bias_angle <= 0.0) bias_angle = 0.0;
478 else if (bias_angle >= 360.0) bias_angle = 360.0;
480 double random_length = random_factor * random_max_radius;
481 double random_angle = random_factor * 360.0;
483 double bias_x = bias_length * cos(bias_angle * SG_PI / 180.0);
484 double bias_y = bias_length * sin(bias_angle * SG_PI / 180.0);
485 double random_x = random_length * cos(random_angle * SG_PI / 180.0);
486 double random_y = random_length * sin(random_angle * SG_PI / 180.0);
487 double error_x = bias_x + random_x;
488 double error_y = bias_y + random_y;
489 double error_length = sqrt(error_x*error_x + error_y*error_y);
490 double error_angle = atan(error_y / error_x) * 180.0 / SG_PI;
495 geo_direct_wgs_84 ( altitude_m, latitude_deg,
496 longitude_deg, error_angle,
497 error_length, &lat2, &lon2,
499 //cout << lat2 << " " << lon2 << endl;
500 printf("%f %f \n", bias_length, bias_angle);
501 printf("%3.7f %3.7f \n", lat2, lon2);
502 printf("%f %f \n", error_length, error_angle);
505 _raim_node->setBoolValue(true);
506 _indicated_pos = _position.get();
509 updateWithValid(delta_time_sec);
513 if (_route_active_node->getBoolValue()) {
514 // GPS init with active route
515 SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
516 _listener->setGuard(true);
518 routeManagerSequenced();
519 _listener->setGuard(false);
523 _last_pos = _indicated_pos;
527 GPS::updateWithValid(double dt)
533 if (_mode == "obs") {
534 _selectedCourse = _config.getOBSCourse();
541 updateReferenceNavaid(dt);
546 GPS::updateBasicData(double dt)
550 SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
552 double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
553 double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
554 _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
556 speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/20.0);
557 _last_speed_kts = speed_kt;
559 double odometer = _odometer_node->getDoubleValue();
560 _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
561 odometer = _trip_odometer_node->getDoubleValue();
562 _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
566 GPS::updateTrackingBug()
568 double tracking_bug = _tracking_bug_node->getDoubleValue();
569 double true_bug_error = tracking_bug - getTrueTrack();
570 double magnetic_bug_error = tracking_bug - getMagTrack();
572 // Get the errors into the (-180,180) range.
573 SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
574 SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
576 _true_bug_error_node->setDoubleValue(true_bug_error);
577 _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
581 GPS::updateWaypoints()
584 SGGeodesy::inverse(_indicated_pos, _wp1_position, _wp1TrueBearing, az2,_wp1DistanceM);
585 bool toWp = getWP1ToFlag();
586 _fromFlagNode->setBoolValue(!toWp);
589 void GPS::updateReferenceNavaid(double dt)
591 if (!_ref_navaid_set) {
592 _ref_navaid_elapsed += dt;
593 if (_ref_navaid_elapsed > 5.0) {
594 _ref_navaid_elapsed = 0.0;
596 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
597 FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
599 SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navid");
600 _ref_navaid_id_node->setStringValue("");
601 _ref_navaid_name_node->setStringValue("");
602 _ref_navaid_bearing_node->setDoubleValue(0.0);
603 _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
604 _ref_navaid_distance_node->setDoubleValue(0.0);
605 _ref_navaid_frequency_node->setStringValue("");
606 } else if (nav != _ref_navaid) {
607 SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
608 _listener->setGuard(true);
609 _ref_navaid_id_node->setStringValue(nav->ident().c_str());
610 _ref_navaid_name_node->setStringValue(nav->name().c_str());
611 FGNavRecord* vor = (FGNavRecord*) nav.ptr();
612 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
613 _listener->setGuard(false);
616 // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
624 double trueCourse, distanceM, az2;
625 SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
626 _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
627 _ref_navaid_bearing_node->setDoubleValue(trueCourse);
628 _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
632 void GPS::referenceNavaidSet(const std::string& aNavaid)
635 // allow setting an empty string to restore normal nearest-vor selection
636 if (aNavaid.size() > 0) {
637 FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
638 _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid,
639 _position.get(), &vorFilter);
642 SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
647 _ref_navaid_set = true;
648 SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
649 _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
650 _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
651 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
652 _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
655 _ref_navaid_set = false;
656 _ref_navaid_elapsed = 9999.0; // update next tick
660 void GPS::tuneNavRadios()
662 if (!_ref_navaid || !_config.tuneNavRadioToRefVor()) {
666 SGPropertyNode_ptr navRadio1 = fgGetNode("/instrumentation/nav", false);
671 FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
672 SGPropertyNode_ptr freqs = navRadio1->getChild("frequencies");
673 freqs->setDoubleValue("selected-mhz", vor->get_freq() / 100.0);
676 void GPS::routeActivated()
678 if (_route_active_node->getBoolValue()) {
679 SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
681 _computeTurnData = true;
682 } else if (_mode == "leg") {
683 SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
688 void GPS::routeManagerSequenced()
690 if (_mode != "leg") {
691 SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
695 int index = _routeMgr->currentWaypoint(),
696 count = _routeMgr->size();
697 if ((index < 1) || (index >= count)) {
698 SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
702 SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
703 SGWayPoint wp0(_routeMgr->get_waypoint(index - 1));
704 SGWayPoint wp1(_routeMgr->get_waypoint(index));
706 _wp0Ident = wp0.get_id();
707 _wp0Name = wp0.get_name();
708 _wp0_position = wp0.get_target();
710 _wp1Ident = wp1.get_id();
711 _wp1Name = wp1.get_name();
712 _wp1_position = wp1.get_target();
714 _selectedCourse = getLegMagCourse();
717 void GPS::updateTurn()
719 bool printProgress = false;
721 if (_computeTurnData) {
722 if (_last_speed_kts < 60) {
723 // need valid leg course and sensible ground speed to compute the turn
728 printProgress = true;
731 if (!_anticipateTurn) {
737 // find bearing to turn centre
738 double bearing, az2, distanceM;
739 SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
740 double progress = computeTurnProgress(bearing);
743 SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
746 if (!_inTurn && (progress > 0.0)) {
750 if (_inTurn && !_turnSequenced && (progress > 0.5)) {
751 _turnSequenced = true;
752 SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
753 _routeMgr->sequence();
756 if (_inTurn && (progress >= 1.0)) {
761 // drive deviation and desired course
762 double desiredCourse = bearing - copysign(90, _turnAngle);
763 SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
764 double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
765 double deviationDeg = desiredCourse - getMagTrack();
766 deviationNm = copysign(deviationNm, deviationDeg);
768 //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
769 //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
770 //_cdiDeflectionNode->setDoubleValue(deviationDeg);
774 void GPS::updateOverflight()
776 if ((_wp1DistanceM * SG_METER_TO_NM) > _config.overflightArmDistanceNm()) {
780 if (getWP1ToFlag()) {
781 return; // still heading towards the WP
784 if (_mode == "dto") {
785 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
787 // check for wp1 being on active route - resume leg mode
788 if (_routeMgr->isRouteActive()) {
789 int index = _routeMgr->findWaypoint(_wp1_position);
791 SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
793 _routeMgr->jumpToIndex(index);
796 } else if (_mode == "leg") {
797 SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
798 _routeMgr->sequence();
799 } else if (_mode == "obs") {
800 // nothing to do here, TO/FROM will update but that's fine
803 _computeTurnData = true;
806 void GPS::beginTurn()
809 _turnSequenced = false;
810 SG_LOG(SG_INSTR, SG_INFO, "begining turn");
816 SG_LOG(SG_INSTR, SG_INFO, "ending turn");
817 _computeTurnData = true;
820 double GPS::computeTurnProgress(double aBearing) const
822 double startBearing = _turnStartBearing + copysign(90, _turnAngle);
823 return (aBearing - startBearing) / _turnAngle;
826 void GPS::computeTurnData()
828 _computeTurnData = false;
829 if (_mode != "leg") { // and approach modes in the future
830 _anticipateTurn = false;
834 int curIndex = _routeMgr->currentWaypoint();
835 if ((curIndex + 1) >= _routeMgr->size()) {
836 _anticipateTurn = false;
840 if (!_config.turnAnticipationEnabled()) {
841 _anticipateTurn = false;
845 _turnStartBearing = _selectedCourse;
846 // compute next leg course
847 SGWayPoint wp1(_routeMgr->get_waypoint(curIndex)),
848 wp2(_routeMgr->get_waypoint(curIndex + 1));
850 wp2.CourseAndDistance(wp1, &crs, &dist);
853 // compute offset bearing
854 _turnAngle = crs - _turnStartBearing;
855 SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
856 double median = _turnStartBearing + (_turnAngle * 0.5);
857 double offsetBearing = median + copysign(90, _turnAngle);
858 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
860 SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
861 ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median
862 << ", offset=" << offsetBearing);
864 SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << wp1.get_id() << "->" << wp2.get_id());
866 _turnPt = _wp1_position;
867 _anticipateTurn = true;
870 void GPS::updateTurnData()
872 // depends on ground speed, so needs to be updated per-frame
873 _turnRadius = computeTurnRadiusNm(_last_speed_kts);
875 // compute the turn centre, based on the turn radius.
876 // key thing is to understand that we're working a right-angle triangle,
877 // where the right-angle is the point we start the turn. From that point,
878 // one side is the inbound course to the turn pt, and the other is the
879 // perpendicular line, of length 'r', to the turn centre.
880 // the triangle's hypotenuse, which we need to find, is the distance from the
881 // turn pt to the turn center (in the direction of the offset bearing)
882 // note that d - _turnRadius tell us how much we're 'cutting' the corner.
884 double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
885 double d = _turnRadius / cos(halfTurnAngle);
887 // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
888 // << " (cut distance=" << d - _turnRadius << ")");
890 double median = _turnStartBearing + (_turnAngle * 0.5);
891 double offsetBearing = median + copysign(90, _turnAngle);
892 SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
895 SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2);
898 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
900 // turn time is seconds to execute a 360 turn.
901 double turnTime = 360.0 / _config.turnRateDegSec();
903 // c is ground distance covered in that time (circumference of the circle)
904 double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
906 // divide by 2PI to go from circumference -> radius
907 return c / (2 * M_PI);
910 void GPS::updateRouteData()
912 double totalDistance = _wp1DistanceM * SG_METER_TO_NM;
913 // walk all waypoints from wp2 to route end, and sum
914 for (int i=_routeMgr->currentWaypoint()+1; i<_routeMgr->size(); ++i) {
915 totalDistance += _routeMgr->get_waypoint(i).get_distance();
918 _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
919 double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
920 _routeETE->setStringValue(makeTTWString(TTW));
923 /////////////////////////////////////////////////////////////////////////////
924 // property getter/setters
926 double GPS::getLegDistance() const
928 if (_mode == "obs") {
932 return SGGeodesy::distanceNm(_wp0_position, _wp1_position);
935 double GPS::getLegCourse() const
937 if (_mode == "obs") {
941 return SGGeodesy::courseDeg(_wp0_position, _wp1_position);
944 double GPS::getLegMagCourse() const
946 if (!_last_valid || (_mode == "obs")) {
950 double m = getLegCourse() - _magvar_node->getDoubleValue();
951 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
955 double GPS::getAltDistanceRatio() const
957 if (!_last_valid || (_mode == "obs")) {
961 double dist = SGGeodesy::distanceM(_wp0_position, _wp1_position);
966 double alt_difference_m = _wp0_position.getElevationM() - _wp1_position.getElevationM();
967 return alt_difference_m / dist;
970 double GPS::getMagTrack() const
976 double m = getTrueTrack() - _magvar_node->getDoubleValue();
977 SG_NORMALIZE_RANGE(m, 0.0, 360.0);
981 double GPS::getCDIDeflection() const
988 if (_config.cdiDeflectionIsAngular()) {
989 defl = getWP1CourseDeviation();
990 SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
992 double fullScale = _config.cdiDeflectionLinearPeg();
993 double normError = getWP1CourseErrorNm() / fullScale;
994 SG_CLAMP_RANGE(normError, -1.0, 1.0);
995 defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1001 const char* GPS::getWP0Ident() const
1003 if (_mode != "leg") {
1007 return _wp0Ident.c_str();
1010 const char* GPS::getWP0Name() const
1012 if (_mode != "leg") {
1016 return _wp0Name.c_str();
1019 const char* GPS::getWP1Ident() const
1021 return _wp1Ident.c_str();
1024 const char* GPS::getWP1Name() const
1026 return _wp1Name.c_str();
1029 double GPS::getWP1Distance() const
1035 return _wp1DistanceM * SG_METER_TO_NM;
1038 double GPS::getWP1TTW() const
1044 if (_last_speed_kts <= 0.0) {
1048 return (getWP1Distance() / _last_speed_kts) * 3600.0;
1051 const char* GPS::getWP1TTWString() const
1053 return makeTTWString(getWP1TTW());
1056 double GPS::getWP1Bearing() const
1062 return _wp1TrueBearing;
1065 double GPS::getWP1MagBearing() const
1071 return _wp1TrueBearing - _magvar_node->getDoubleValue();
1074 double GPS::getWP1CourseDeviation() const
1080 double dev = getWP1MagBearing() - _selectedCourse;
1081 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1083 if (fabs(dev) > 90.0) {
1084 // When the course is away from the waypoint,
1085 // it makes sense to change the sign of the deviation.
1087 SG_NORMALIZE_RANGE(dev, -90.0, 90.0);
1093 double GPS::getWP1CourseErrorNm() const
1099 double radDev = getWP1CourseDeviation() * SG_DEGREES_TO_RADIANS;
1100 double course_error_m = sin(radDev) * _wp1DistanceM;
1101 return course_error_m * SG_METER_TO_NM;
1104 bool GPS::getWP1ToFlag() const
1110 double dev = getWP1MagBearing() - _selectedCourse;
1111 SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
1113 return (fabs(dev) < 90.0);
1116 double GPS::getScratchDistance() const
1118 if (!_scratchValid) {
1122 return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1125 double GPS::getScratchTrueBearing() const
1127 if (!_scratchValid) {
1131 return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1134 double GPS::getScratchMagBearing() const
1136 if (!_scratchValid) {
1140 double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1141 SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1145 /////////////////////////////////////////////////////////////////////////////
1146 // command / scratch / search system
1148 void GPS::setCommand(const char* aCmd)
1150 SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1152 if (!strcmp(aCmd, "direct")) {
1154 } else if (!strcmp(aCmd, "obs")) {
1156 } else if (!strcmp(aCmd, "leg")) {
1158 } else if (!strcmp(aCmd, "load-route-wpt")) {
1159 loadRouteWaypoint();
1160 } else if (!strcmp(aCmd, "nearest")) {
1162 } else if (!strcmp(aCmd, "search")) {
1163 _searchNames = false;
1165 } else if (!strcmp(aCmd, "search-names")) {
1166 _searchNames = true;
1168 } else if (!strcmp(aCmd, "next")) {
1170 } else if (!strcmp(aCmd, "previous")) {
1172 } else if (!strcmp(aCmd, "define-user-wpt")) {
1175 SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognzied command:" << aCmd);
1179 void GPS::clearScratch()
1181 _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1182 _scratchValid = false;
1183 _scratchNode->setStringValue("type", "");
1184 _scratchNode->setStringValue("query", "");
1187 bool GPS::isScratchPositionValid() const
1189 if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1190 (_scratchPos.getLatitudeDeg() < -9990.0)) {
1197 void GPS::directTo()
1199 if (!isScratchPositionValid()) {
1200 SG_LOG(SG_INSTR, SG_WARN, "invalid DTO lat/lon");
1204 _wp0_position = _indicated_pos;
1205 _wp1Ident = _scratchNode->getStringValue("ident");
1206 _wp1Name = _scratchNode->getStringValue("name");
1207 _wp1_position = _scratchPos;
1210 _selectedCourse = getLegMagCourse();
1214 void GPS::loadRouteWaypoint()
1216 _scratchValid = false;
1217 // if (!_routeMgr->isRouteActive()) {
1218 // SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1222 int index = _scratchNode->getIntValue("index", -9999);
1225 if (index == -9999) { // no index supplied, use current wp
1226 index = _routeMgr->currentWaypoint();
1229 _searchIsRoute = true;
1230 setScratchFromRouteWaypoint(index);
1233 void GPS::setScratchFromRouteWaypoint(int aIndex)
1235 assert(_searchIsRoute);
1236 if ((aIndex < 0) || (aIndex >= _routeMgr->size())) {
1237 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1241 _searchResultIndex = aIndex;
1242 SGWayPoint wp(_routeMgr->get_waypoint(aIndex));
1243 _scratchNode->setStringValue("name", wp.get_name());
1244 _scratchNode->setStringValue("ident", wp.get_id());
1245 _scratchPos = wp.get_target();
1246 _scratchValid = true;
1247 _scratchNode->setDoubleValue("course", wp.get_track());
1248 _scratchNode->setIntValue("index", aIndex);
1250 int lastResult = _routeMgr->size() - 1;
1251 _searchHasNext = (_searchResultIndex < lastResult);
1254 void GPS::loadNearest()
1256 string sty(_scratchNode->getStringValue("type"));
1257 FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1258 if (ty == FGPositioned::INVALID) {
1259 SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1263 auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1264 int limitCount = _scratchNode->getIntValue("max-results", 1);
1265 double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1267 clearScratch(); // clear now, regardless of whether we find a match or not
1270 FGPositioned::findClosestN(_indicated_pos, limitCount, cutoffDistance, f.get());
1271 _searchResultsCached = true;
1272 _searchResultIndex = 0;
1273 _searchIsRoute = false;
1274 _searchHasNext = false;
1276 if (_searchResults.empty()) {
1277 SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1281 _searchHasNext = (_searchResults.size() > 1);
1282 setScratchFromCachedSearchResult();
1285 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1287 switch (aPos->type()) {
1288 case FGPositioned::AIRPORT:
1289 // heliport and seaport too?
1290 case FGPositioned::VOR:
1291 case FGPositioned::NDB:
1292 case FGPositioned::FIX:
1293 case FGPositioned::TACAN:
1294 case FGPositioned::WAYPOINT:
1301 FGPositioned::Type GPS::SearchFilter::minType() const
1303 return FGPositioned::AIRPORT;
1306 FGPositioned::Type GPS::SearchFilter::maxType() const
1308 return FGPositioned::WAYPOINT;
1311 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1313 if (aTy == FGPositioned::AIRPORT) {
1314 return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1317 // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1318 if (aTy == FGPositioned::INVALID) {
1319 return new SearchFilter;
1322 return new FGPositioned::TypeFilter(aTy);
1327 // parse search terms into local members, and exec the first search
1328 string sty(_scratchNode->getStringValue("type"));
1329 _searchType = FGPositioned::typeFromName(sty);
1330 _searchQuery = _scratchNode->getStringValue("query");
1331 _searchExact = _scratchNode->getBoolValue("exact", true);
1332 _searchOrderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1333 _searchResultIndex = 0;
1334 _searchIsRoute = false;
1335 _searchHasNext = false;
1337 if (_searchExact && _searchOrderByRange) {
1338 // immediate mode search, get all the results now and cache them
1339 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1341 _searchResults = FGPositioned::findAllWithNameSortedByRange(_searchQuery, _indicated_pos, f.get());
1343 _searchResults = FGPositioned::findAllWithIdentSortedByRange(_searchQuery, _indicated_pos, f.get());
1346 _searchResultsCached = true;
1348 if (_searchResults.empty()) {
1353 _searchHasNext = (_searchResults.size() > 1);
1354 setScratchFromCachedSearchResult();
1356 // iterative search, look up result zero
1357 _searchResultsCached = false;
1362 void GPS::performSearch()
1364 auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1369 if (_searchOrderByRange) {
1370 r = FGPositioned::findClosestWithPartialName(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1372 r = FGPositioned::findWithPartialName(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1375 if (_searchOrderByRange) {
1376 r = FGPositioned::findClosestWithPartialId(_indicated_pos, _searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1378 r = FGPositioned::findWithPartialId(_searchQuery, f.get(), _searchResultIndex, _searchHasNext);
1386 setScratchFromPositioned(r.get(), _searchResultIndex);
1389 void GPS::setScratchFromCachedSearchResult()
1391 assert(_searchResultsCached);
1392 int index = _searchResultIndex;
1394 if ((index < 0) || (index >= (int) _searchResults.size())) {
1395 SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1399 setScratchFromPositioned(_searchResults[index], index);
1401 int lastResult = (int) _searchResults.size() - 1;
1402 _searchHasNext = (_searchResultIndex < lastResult);
1405 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1410 _scratchPos = aPos->geod();
1411 _scratchNode->setStringValue("name", aPos->name());
1412 _scratchNode->setStringValue("ident", aPos->ident());
1413 _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1416 _scratchNode->setIntValue("index", aIndex);
1419 _scratchValid = true;
1420 if (_searchResultsCached) {
1421 _scratchNode->setIntValue("result-count", _searchResults.size());
1424 switch (aPos->type()) {
1425 case FGPositioned::VOR:
1426 _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1429 case FGPositioned::NDB:
1430 _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1433 case FGPositioned::AIRPORT:
1434 addAirportToScratch((FGAirport*)aPos);
1442 // look for being on the route and set?
1445 void GPS::addAirportToScratch(FGAirport* aAirport)
1447 for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1448 SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1449 FGRunway* rwy = aAirport->getRunwayByIndex(r);
1450 // TODO - filter out unsuitable runways in the future
1451 // based on config again
1453 rwyNd->setStringValue("id", rwy->ident().c_str());
1454 rwyNd->setIntValue("length-ft", rwy->lengthFt());
1455 rwyNd->setIntValue("width-ft", rwy->widthFt());
1456 rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1457 // map surface code to a string
1458 // TODO - lighting information
1461 rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1463 } // of runways iteration
1467 void GPS::selectOBSMode()
1469 if (!isScratchPositionValid()) {
1470 SG_LOG(SG_INSTR, SG_WARN, "invalid OBS lat/lon");
1474 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1477 _wp1Ident = _scratchNode->getStringValue("ident");
1478 _wp1Name = _scratchNode->getStringValue("name");
1479 _wp1_position = _scratchPos;
1480 _wp0_position = _indicated_pos;
1483 void GPS::selectLegMode()
1485 if (_mode == "leg") {
1489 if (!_routeMgr->isRouteActive()) {
1490 SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1494 SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1497 // not really sequenced, but does all the work of updating wp0/1
1498 routeManagerSequenced();
1501 void GPS::nextResult()
1503 if (!_searchHasNext) {
1508 if (_searchIsRoute) {
1509 setScratchFromRouteWaypoint(++_searchResultIndex);
1510 } else if (_searchResultsCached) {
1511 ++_searchResultIndex;
1512 setScratchFromCachedSearchResult();
1514 ++_searchResultIndex;
1516 } // of iterative search case
1519 void GPS::previousResult()
1521 if (_searchResultIndex <= 0) {
1526 --_searchResultIndex;
1528 if (_searchIsRoute) {
1529 setScratchFromRouteWaypoint(_searchResultIndex);
1530 } else if (_searchResultsCached) {
1531 setScratchFromCachedSearchResult();
1537 void GPS::defineWaypoint()
1539 if (!isScratchPositionValid()) {
1540 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1544 string ident = _scratchNode->getStringValue("ident");
1545 if (ident.size() < 2) {
1546 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1550 // check for duplicate idents
1551 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1552 FGPositioned::List dups = FGPositioned::findAllWithIdentSortedByRange(ident, _indicated_pos, &f);
1553 if (!dups.empty()) {
1554 SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1557 SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1558 FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1559 _searchResultsCached = false;
1560 setScratchFromPositioned(wpt.get(), -1);