]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
bind the sky disable cutoff distance to a property
[flightgear.git] / src / Instrumentation / gps.cxx
1 // gps.cxx - distance-measuring equipment.
2 // Written by David Megginson, started 2003.
3 //
4 // This file is in the Public Domain and comes with no warranty.
5
6 #ifdef HAVE_CONFIG_H
7 #  include <config.h>
8 #endif
9
10 #include "gps.hxx"
11
12 #include <boost/tuple/tuple.hpp>
13
14 #include <memory>
15 #include <set>
16 #include <cstring>
17
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"
27
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>
32 #include <simgear/scene/util/OsgMath.hxx>
33
34 using std::auto_ptr;
35 using std::string;
36 using namespace flightgear;
37
38 ///////////////////////////////////////////////////////////////////
39
40 void SGGeodProperty::init(SGPropertyNode* base, const char* lonStr, const char* latStr, const char* altStr)
41 {
42     _lon = base->getChild(lonStr, 0, true);
43     _lat = base->getChild(latStr, 0, true);
44     if (altStr) {
45         _alt = base->getChild(altStr, 0, true);
46     }
47 }
48
49 void SGGeodProperty::init(const char* lonStr, const char* latStr, const char* altStr)
50 {
51     _lon = fgGetNode(lonStr, true);
52     _lat = fgGetNode(latStr, true);
53     if (altStr) {
54         _alt = fgGetNode(altStr, true);
55     }
56 }
57
58 void SGGeodProperty::clear()
59 {
60     _lon = _lat = _alt = NULL;
61 }
62
63 void SGGeodProperty::operator=(const SGGeod& geod)
64 {
65     _lon->setDoubleValue(geod.getLongitudeDeg());
66     _lat->setDoubleValue(geod.getLatitudeDeg());
67     if (_alt) {
68         _alt->setDoubleValue(geod.getElevationFt());
69     }
70 }
71
72 SGGeod SGGeodProperty::get() const
73 {
74     double lon = _lon->getDoubleValue(),
75         lat = _lat->getDoubleValue();
76         
77     if (osg::isNaN(lon) || osg::isNaN(lat)) {
78       SG_LOG(SG_INSTR, SG_WARN, "read NaN for lon/lat:" << _lon->getPath() 
79         << ", " << _lat->getPath());
80       return SGGeod();
81     }
82         
83     if (_alt) {
84         return SGGeod::fromDegFt(lon, lat, _alt->getDoubleValue());
85     } else {
86         return SGGeod::fromDeg(lon,lat);
87     }
88 }
89
90 static const char* makeTTWString(double TTW)
91 {
92   if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
93     return "--:--:--";
94   }
95       
96   unsigned int TTW_seconds = (int) (TTW + 0.5);
97   unsigned int TTW_minutes = 0;
98   unsigned int TTW_hours   = 0;
99   static char TTW_str[9];
100   TTW_hours   = TTW_seconds / 3600;
101   TTW_minutes = (TTW_seconds / 60) % 60;
102   TTW_seconds = TTW_seconds % 60;
103   snprintf(TTW_str, 9, "%02d:%02d:%02d",
104     TTW_hours, TTW_minutes, TTW_seconds);
105   return TTW_str;
106 }
107
108 /////////////////////////////////////////////////////////////////////////////
109
110 class GPSListener : public SGPropertyChangeListener
111 {
112 public:
113   GPSListener(GPS *m) : 
114     _gps(m),
115     _guard(false) {}
116     
117   virtual void valueChanged (SGPropertyNode * prop)
118   {
119     if (_guard) {
120       return;
121     }
122     
123     _guard = true;
124     if (prop == _gps->_route_current_wp_node) {
125       _gps->routeManagerSequenced();
126     } else if (prop == _gps->_route_active_node) {
127       _gps->routeActivated();
128     } else if (prop == _gps->_ref_navaid_id_node) {
129       _gps->referenceNavaidSet(prop->getStringValue(""));
130     } else if (prop == _gps->_routeEditedSignal) {
131       _gps->routeEdited();
132     } else if (prop == _gps->_routeFinishedSignal) {
133       _gps->routeFinished();
134     }
135         
136     _guard = false;
137   }
138   
139   void setGuard(bool g) {
140     _guard = g;
141   }
142 private:
143   GPS* _gps;
144   bool _guard; // re-entrancy guard
145 };
146
147 ////////////////////////////////////////////////////////////////////////////
148 /**
149  * Helper to monitor for Nasal or other code accessing properties we haven't
150  * defined. For the moment we complain about all such activites, since various
151  * users assume all kinds of weird, wonderful and non-existent interfaces.
152  */
153  
154 class DeprecatedPropListener : public SGPropertyChangeListener
155 {
156 public:
157   DeprecatedPropListener(SGPropertyNode* gps)
158   {
159     _parents.insert(gps);
160     SGPropertyNode* wp = gps->getChild("wp", 0, true); 
161     _parents.insert(wp);
162     _parents.insert(wp->getChild("wp", 0, true));
163     _parents.insert(wp->getChild("wp", 1, true));
164     
165     std::set<SGPropertyNode*>::iterator it;
166     for (it = _parents.begin(); it != _parents.end(); ++it) {
167       (*it)->addChangeListener(this);
168     }
169   }
170   
171   virtual void valueChanged (SGPropertyNode * prop)
172   {
173   }
174   
175   virtual void childAdded (SGPropertyNode * parent, SGPropertyNode * child)
176   {
177     if (isDeprecated(parent, child)) {
178       SG_LOG(SG_INSTR, SG_WARN, "GPS: someone accessed a deprecated property:"
179         << child->getPath(true));
180     }
181   }
182 private:
183   bool isDeprecated(SGPropertyNode * parent, SGPropertyNode * child) const 
184   {
185     if (_parents.count(parent) < 1) {
186       return false;
187     }
188     
189     // no child exclusions yet
190     return true;
191   }
192   
193   std::set<SGPropertyNode*> _parents;
194 };
195
196 ////////////////////////////////////////////////////////////////////////////
197 // configuration helper object
198
199 GPS::Config::Config() :
200   _enableTurnAnticipation(true),
201   _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
202   _overflightArmDistance(1.0),
203   _waypointAlertTime(30.0),
204   _minRunwayLengthFt(0.0),
205   _requireHardSurface(true),
206   _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
207   _driveAutopilot(true),
208   _courseSelectable(false)
209 {
210   _enableTurnAnticipation = false;
211 }
212
213 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
214 {
215   aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
216   aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
217   aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
218   aOwner->tie(aCfg, "min-runway-length-ft", SGRawValuePointer<double>(&_minRunwayLengthFt));
219   aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
220   aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
221   aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
222   aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
223 }
224
225 ////////////////////////////////////////////////////////////////////////////
226
227 GPS::GPS ( SGPropertyNode *node) : 
228   _selectedCourse(0.0),
229   _desiredCourse(0.0),
230   _dataValid(false),
231   _lastPosValid(false),
232   _mode("init"),
233   _name(node->getStringValue("name", "gps")),
234   _num(node->getIntValue("number", 0)),
235   _computeTurnData(false),
236   _anticipateTurn(false),
237   _inTurn(false)
238 {
239   string branch = "/instrumentation/" + _name;
240   _gpsNode = fgGetNode(branch.c_str(), _num, true );
241   _scratchNode = _gpsNode->getChild("scratch", 0, true);
242   
243   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
244   _currentWayptNode = wp_node->getChild("wp", 1, true);
245 }
246
247 GPS::~GPS ()
248 {
249 }
250
251 void
252 GPS::init ()
253 {
254   _routeMgr = (FGRouteMgr*) globals->get_subsystem("route-manager");
255   assert(_routeMgr);
256   
257   _position.init("/position/longitude-deg", "/position/latitude-deg", "/position/altitude-ft");
258   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
259   _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
260   _serviceable_node->setBoolValue(true);
261   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
262
263 // basic GPS outputs
264   _raim_node = _gpsNode->getChild("raim", 0, true);
265   _odometer_node = _gpsNode->getChild("odometer", 0, true);
266   _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
267   _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
268   _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
269   _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
270   _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
271   
272 // waypoints
273   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
274   SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
275   wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
276
277   _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
278          
279 // reference navid
280   SGPropertyNode_ptr ref_navaid = _gpsNode->getChild("ref-navaid", 0, true);
281   _ref_navaid_id_node = ref_navaid->getChild("id", 0, true);
282   _ref_navaid_name_node = ref_navaid->getChild("name", 0, true);
283   _ref_navaid_bearing_node = ref_navaid->getChild("bearing-deg", 0, true);
284   _ref_navaid_frequency_node = ref_navaid->getChild("frequency-mhz", 0, true);
285   _ref_navaid_distance_node = ref_navaid->getChild("distance-nm", 0, true);
286   _ref_navaid_mag_bearing_node = ref_navaid->getChild("mag-bearing-deg", 0, true);
287   _ref_navaid_elapsed = 0.0;
288   _ref_navaid_set = false;
289     
290 // route properties    
291   // should these move to the route manager?
292   _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
293   _routeETE = _gpsNode->getChild("ETE", 0, true);
294   _routeEditedSignal = fgGetNode("/autopilot/route-manager/signals/edited", true);
295   _routeFinishedSignal = fgGetNode("/autopilot/route-manager/signals/finished", true);
296   
297 // add listener to various things
298   _listener = new GPSListener(this);
299   _route_current_wp_node = fgGetNode("/autopilot/route-manager/current-wp", true);
300   _route_current_wp_node->addChangeListener(_listener);
301   _route_active_node = fgGetNode("/autopilot/route-manager/active", true);
302   _route_active_node->addChangeListener(_listener);
303   _ref_navaid_id_node->addChangeListener(_listener);
304   _routeEditedSignal->addChangeListener(_listener);
305   _routeFinishedSignal->addChangeListener(_listener);
306   
307 // navradio slaving properties  
308   SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
309   toFlag->alias(_currentWayptNode->getChild("to-flag"));
310   
311   SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
312   fromFlag->alias(_currentWayptNode->getChild("from-flag"));
313     
314 // autopilot drive properties
315   _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
316   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
317   _apTargetAltitudeFt = fgGetNode("/autopilot/settings/target-altitude-ft", true);
318   _apAltitudeLock = fgGetNode("/autopilot/locks/altitude", true);
319   
320 // realism prop[s]
321   _realismSimpleGps = fgGetNode("/sim/realism/simple-gps", true);
322   if (!_realismSimpleGps->hasValue()) {
323     _realismSimpleGps->setBoolValue(true);
324   }
325   
326   // last thing, add the deprecated prop watcher
327   new DeprecatedPropListener(_gpsNode);
328   
329   clearOutput();
330 }
331
332 void
333 GPS::bind()
334 {
335   _config.bind(this, _gpsNode->getChild("config", 0, true));
336
337 // basic GPS outputs
338   tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
339     (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
340
341   tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
342     (*this, &GPS::getDesiredCourse, NULL));
343   _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
344     
345   tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
346         "indicated-latitude-deg", "indicated-altitude-ft");
347
348   tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
349     (*this, &GPS::getVerticalSpeed, NULL));
350   tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
351     (*this, &GPS::getTrueTrack, NULL));
352   tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
353     (*this, &GPS::getMagTrack, NULL));
354   tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
355     (*this, &GPS::getGroundspeedKts, NULL));
356   
357 // command system
358   tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
359   tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
360     
361   tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
362   tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
363   tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
364   tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
365   tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
366   tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
367   _scratchValid = false;
368
369   
370   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
371   SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
372   
373   tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
374   tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
375     (*this, &GPS::getWP1Ident, NULL));
376   
377   tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
378     (*this, &GPS::getWP1Distance, NULL));
379   tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
380     (*this, &GPS::getWP1Bearing, NULL));
381   tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
382     (*this, &GPS::getWP1MagBearing, NULL));
383   tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
384     (*this, &GPS::getWP1TTW, NULL));
385   tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
386     (*this, &GPS::getWP1TTWString, NULL));
387   
388   tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
389     (*this, &GPS::getWP1CourseDeviation, NULL));
390   tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
391     (*this, &GPS::getWP1CourseErrorNm, NULL));
392   tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
393     (*this, &GPS::getWP1ToFlag, NULL));
394   tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
395     (*this, &GPS::getWP1FromFlag, NULL));
396
397 // leg properties (only valid in DTO/LEG modes, not OBS)
398   tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
399   tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
400   tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
401
402 // navradio slaving properties  
403   tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
404     (*this, &GPS::getCDIDeflection));
405 }
406
407 void
408 GPS::unbind()
409 {
410   _tiedProperties.Untie();
411 }
412
413 void
414 GPS::clearOutput()
415 {
416   _dataValid = false;
417   _last_speed_kts = 0.0;
418   _last_pos = SGGeod();
419   _lastPosValid = false;
420   _indicated_pos = SGGeod();
421   _last_vertical_speed = 0.0;
422   _last_true_track = 0.0;
423   _lastEWVelocity = _lastNSVelocity = 0.0;
424   _currentWaypt = _prevWaypt = NULL;
425   _legDistanceNm = -1.0;
426   
427   _raim_node->setDoubleValue(0.0);
428   _indicated_pos = SGGeod();
429   _odometer_node->setDoubleValue(0);
430   _trip_odometer_node->setDoubleValue(0);
431   _tracking_bug_node->setDoubleValue(0);
432   _true_bug_error_node->setDoubleValue(0);
433   _magnetic_bug_error_node->setDoubleValue(0);
434   _northSouthVelocity->setDoubleValue(0.0);
435   _eastWestVelocity->setDoubleValue(0.0);
436 }
437
438 void
439 GPS::update (double delta_time_sec)
440 {
441   if (!_realismSimpleGps->getBoolValue()) {
442     // If it's off, don't bother.
443     if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
444       clearOutput();
445       return;
446     }
447   }
448   
449   if (delta_time_sec <= 0.0) {
450     return; // paused, don't bother
451   }    
452   
453   _raim_node->setDoubleValue(1.0);
454   _indicated_pos = _position.get();
455   updateBasicData(delta_time_sec);
456
457   if (_dataValid) {
458     if (_wayptController.get()) {
459       _wayptController->update();
460       SGGeod p(_wayptController->position());
461       _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
462       _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
463       _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
464       
465       _desiredCourse = getLegMagCourse();
466       
467       updateTurn();
468       updateRouteData();
469     }
470
471     
472     updateTrackingBug();
473     updateReferenceNavaid(delta_time_sec);
474     driveAutopilot();
475   }
476   
477   if (_dataValid && (_mode == "init")) {
478     // allow a realistic delay in the future, here
479     SG_LOG(SG_INSTR, SG_INFO, "GPS initialisation complete");
480         
481     if (_route_active_node->getBoolValue()) {
482       // GPS init with active route
483       SG_LOG(SG_INSTR, SG_INFO, "GPS init with active route");
484       selectLegMode();
485     } else {
486       // initialise in OBS mode, with waypt set to the nearest airport.
487       // keep in mind at this point, _dataValid is not set
488     
489       auto_ptr<FGPositioned::Filter> f(createFilter(FGPositioned::AIRPORT));
490       FGPositionedRef apt = FGPositioned::findClosest(_position.get(), 20.0, f.get());
491       if (apt) {
492         setScratchFromPositioned(apt, 0);
493         selectOBSMode();
494       }
495     }
496   } // of init mode check
497   
498   _last_pos = _indicated_pos;
499   _lastPosValid = !(_last_pos == SGGeod());
500 }
501
502 ///////////////////////////////////////////////////////////////////////////
503 // implement the RNAV interface 
504 SGGeod GPS::position()
505 {
506   if (!_dataValid) {
507     return SGGeod();
508   }
509   
510   return _indicated_pos;
511 }
512
513 double GPS::trackDeg()
514 {
515   return _last_true_track;
516 }
517
518 double GPS::groundSpeedKts()
519 {
520   return _last_speed_kts;
521 }
522
523 double GPS::vspeedFPM()
524 {
525   return _last_vertical_speed;
526 }
527
528 double GPS::magvarDeg()
529 {
530   return _magvar_node->getDoubleValue();
531 }
532
533 double GPS::overflightArmDistanceM()
534 {
535   return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
536 }
537
538 double GPS::selectedMagCourse()
539 {
540   return _selectedCourse;
541 }
542
543 ///////////////////////////////////////////////////////////////////////////
544
545 void
546 GPS::updateBasicData(double dt)
547 {
548   if (!_lastPosValid) {
549     return;
550   }
551   
552   double distance_m;
553   double track2_deg;
554   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
555     
556   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
557   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
558   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
559   
560   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
561   _last_speed_kts = speed_kt;
562   
563   SGGeod g = _indicated_pos;
564   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
565   double northSouthM = SGGeodesy::distanceM(_last_pos, g);
566   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
567   
568   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
569   _lastNSVelocity = nsMSec;
570   _northSouthVelocity->setDoubleValue(nsMSec);
571
572
573   g = _indicated_pos;
574   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
575   double eastWestM = SGGeodesy::distanceM(_last_pos, g);
576   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
577   
578   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
579   _lastEWVelocity = ewMSec;
580   _eastWestVelocity->setDoubleValue(ewMSec);
581   
582   double odometer = _odometer_node->getDoubleValue();
583   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
584   odometer = _trip_odometer_node->getDoubleValue();
585   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
586   
587   if (!_dataValid) {
588     SG_LOG(SG_INSTR, SG_INFO, "GPS setting data valid");
589     _dataValid = true;
590   }
591 }
592
593 void
594 GPS::updateTrackingBug()
595 {
596   double tracking_bug = _tracking_bug_node->getDoubleValue();
597   double true_bug_error = tracking_bug - getTrueTrack();
598   double magnetic_bug_error = tracking_bug - getMagTrack();
599
600   // Get the errors into the (-180,180) range.
601   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
602   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
603
604   _true_bug_error_node->setDoubleValue(true_bug_error);
605   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
606 }
607
608 void GPS::updateReferenceNavaid(double dt)
609 {
610   if (!_ref_navaid_set) {
611     _ref_navaid_elapsed += dt;
612     if (_ref_navaid_elapsed > 5.0) {
613
614       FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
615       FGPositionedRef nav = FGPositioned::findClosest(_indicated_pos, 400.0, &vorFilter);
616       if (!nav) {
617         SG_LOG(SG_INSTR, SG_INFO, "GPS couldn't find a reference navaid");
618         _ref_navaid_id_node->setStringValue("");
619         _ref_navaid_name_node->setStringValue("");
620         _ref_navaid_bearing_node->setDoubleValue(0.0);
621         _ref_navaid_mag_bearing_node->setDoubleValue(0.0);
622         _ref_navaid_distance_node->setDoubleValue(0.0);
623         _ref_navaid_frequency_node->setStringValue("");
624       } else if (nav != _ref_navaid) {
625         SG_LOG(SG_INSTR, SG_INFO, "GPS code selected new ref-navaid:" << nav->ident());
626         _listener->setGuard(true);
627         _ref_navaid_id_node->setStringValue(nav->ident().c_str());
628         _ref_navaid_name_node->setStringValue(nav->name().c_str());
629         FGNavRecord* vor = (FGNavRecord*) nav.ptr();
630         _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
631         _listener->setGuard(false);
632       } else {
633         // SG_LOG(SG_INSTR, SG_ALERT, "matched existing");
634       }
635       
636       _ref_navaid = nav;
637       // reset elapsed time (do not do that before updating the properties above, since their
638       // listeners may request another update (_ref_navaid_elapsed = 9999), which results in
639       // excessive load (FGPositioned::findClosest called in every update loop...)
640       _ref_navaid_elapsed = 0.0; 
641     }
642   }
643   
644   if (_ref_navaid) {
645     double trueCourse, distanceM, az2;
646     SGGeodesy::inverse(_indicated_pos, _ref_navaid->geod(), trueCourse, az2, distanceM);
647     _ref_navaid_distance_node->setDoubleValue(distanceM * SG_METER_TO_NM);
648     _ref_navaid_bearing_node->setDoubleValue(trueCourse);
649     _ref_navaid_mag_bearing_node->setDoubleValue(trueCourse - _magvar_node->getDoubleValue());
650   }
651 }
652
653 void GPS::referenceNavaidSet(const std::string& aNavaid)
654 {
655   _ref_navaid = NULL;
656   // allow setting an empty string to restore normal nearest-vor selection
657   if (aNavaid.size() > 0) {
658     FGPositioned::TypeFilter vorFilter(FGPositioned::VOR);
659     _ref_navaid = FGPositioned::findClosestWithIdent(aNavaid, 
660       _position.get(), &vorFilter);
661     
662     if (!_ref_navaid) {
663       SG_LOG(SG_INSTR, SG_ALERT, "GPS: unknown ref navaid:" << aNavaid);
664     }
665   }
666
667   if (_ref_navaid) {
668     _ref_navaid_set = true;
669     SG_LOG(SG_INSTR, SG_INFO, "GPS code set explict ref-navaid:" << _ref_navaid->ident());
670     _ref_navaid_id_node->setStringValue(_ref_navaid->ident().c_str());
671     _ref_navaid_name_node->setStringValue(_ref_navaid->name().c_str());
672     FGNavRecord* vor = (FGNavRecord*) _ref_navaid.ptr();
673     _ref_navaid_frequency_node->setDoubleValue(vor->get_freq() / 100.0);
674   } else {
675     _ref_navaid_set = false;
676     _ref_navaid_elapsed = 9999.0; // update next tick
677   }
678 }
679
680 void GPS::routeActivated()
681 {
682   if (_route_active_node->getBoolValue()) {
683     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
684     selectLegMode();
685     
686     // if we've already passed the current waypoint, sequence.
687     if (_dataValid && getWP1FromFlag()) {
688       SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
689       _routeMgr->sequence();
690     }
691   } else if (_mode == "leg") {
692     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
693     // select OBS mode, but keep current waypoint-as is
694     _mode = "obs";
695     wp1Changed();
696   }
697 }
698
699 void GPS::routeManagerSequenced()
700 {
701   if (_mode != "leg") {
702     SG_LOG(SG_INSTR, SG_INFO, "GPS ignoring route sequencing, not in LEG mode");
703     return;
704   }
705   
706   int index = _routeMgr->currentIndex(),
707     count = _routeMgr->numWaypts();
708   if ((index < 0) || (index >= count)) {
709     _currentWaypt=NULL;
710     _prevWaypt=NULL;
711     SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
712     return;
713   }
714   
715   SG_LOG(SG_INSTR, SG_INFO, "GPS waypoint index is now " << index);
716   
717   if (index > 0) {
718     _prevWaypt = _routeMgr->previousWaypt();
719     if (_prevWaypt->flag(WPT_DYNAMIC)) {
720       _wp0_position = _indicated_pos;
721     } else {
722       _wp0_position = _prevWaypt->position();
723     }
724   }
725   
726   _currentWaypt = _routeMgr->currentWaypt();
727
728   _desiredCourse = getLegMagCourse();
729   _desiredCourseNode->fireValueChanged();
730   wp1Changed();
731 }
732
733 void GPS::routeEdited()
734 {
735   if (_mode != "leg") {
736     return;
737   }
738   
739   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
740   routeManagerSequenced();
741 }
742
743 void GPS::routeFinished()
744 {
745   if (_mode != "leg") {
746     return;
747   }
748   
749   SG_LOG(SG_INSTR, SG_INFO, "GPS route finished, reverting to OBS");
750   // select OBS mode, but keep current waypoint-as is
751   _mode = "obs";
752   wp1Changed();
753 }
754
755 void GPS::updateTurn()
756 {
757   bool printProgress = false;
758   
759   if (_computeTurnData) {
760     if (_last_speed_kts < 60) {
761       // need valid leg course and sensible ground speed to compute the turn
762       return;
763     }
764     
765     computeTurnData();
766     printProgress = true;
767   }
768   
769   if (!_anticipateTurn) {
770     updateOverflight();
771     return;
772   }
773
774   updateTurnData();
775   // find bearing to turn centre
776   double bearing, az2, distanceM;
777   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
778   double progress = computeTurnProgress(bearing);
779   
780   if (printProgress) {
781     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
782   }
783   
784   if (!_inTurn && (progress > 0.0)) {
785     beginTurn();
786   }
787   
788   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
789     _turnSequenced = true;
790      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
791      _routeMgr->sequence();
792   }
793   
794   if (_inTurn && (progress >= 1.0)) {
795     endTurn();
796   }
797   
798   if (_inTurn) {
799     // drive deviation and desired course
800     double desiredCourse = bearing - copysign(90, _turnAngle);
801     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
802     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
803     double deviationDeg = desiredCourse - getMagTrack();
804     deviationNm = copysign(deviationNm, deviationDeg);
805     // FIXME
806     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
807     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
808     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
809   }
810 }
811
812 void GPS::updateOverflight()
813 {
814   if (!_wayptController->isDone()) {
815     return;
816   }
817   
818   if (_mode == "dto") {
819     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
820     
821     // check for wp1 being on active route - resume leg mode
822     if (_routeMgr->isRouteActive()) {
823       int index = _routeMgr->findWayptIndex(_currentWaypt->position());
824       if (index >= 0) {
825         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
826         _mode = "leg";
827         _routeMgr->jumpToIndex(index);
828       }
829     }
830     
831     if (_mode == "dto") {
832       // if we didn't enter leg mode, drop back to OBS mode
833       // select OBS mode, but keep current waypoint-as is
834       _mode = "obs";
835       wp1Changed();
836     }
837   } else if (_mode == "leg") {
838     SG_LOG(SG_INSTR, SG_INFO, "GPS doing overflight sequencing");
839     _routeMgr->sequence();
840   } else if (_mode == "obs") {
841     // nothing to do here, TO/FROM will update but that's fine
842   }
843   
844   _computeTurnData = true;
845 }
846
847 void GPS::beginTurn()
848 {
849   _inTurn = true;
850   _turnSequenced = false;
851   SG_LOG(SG_INSTR, SG_INFO, "begining turn");
852 }
853
854 void GPS::endTurn()
855 {
856   _inTurn = false;
857   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
858   _computeTurnData = true;
859 }
860
861 double GPS::computeTurnProgress(double aBearing) const
862 {
863   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
864   return (aBearing - startBearing) / _turnAngle;
865 }
866
867 void GPS::computeTurnData()
868 {
869   _computeTurnData = false;
870   if (_mode != "leg") { // and approach modes in the future
871     _anticipateTurn = false;
872     return;
873   }
874   
875   WayptRef next = _routeMgr->nextWaypt();
876   if (!next || next->flag(WPT_DYNAMIC)) {
877     _anticipateTurn = false;
878     return;
879   }
880   
881   if (!_config.turnAnticipationEnabled()) {
882     _anticipateTurn = false;
883     return;
884   }
885   
886   _turnStartBearing = _desiredCourse;
887 // compute next leg course
888   double crs, dist;
889   boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
890     
891
892 // compute offset bearing
893   _turnAngle = crs - _turnStartBearing;
894   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
895   double median = _turnStartBearing + (_turnAngle * 0.5);
896   double offsetBearing = median + copysign(90, _turnAngle);
897   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
898   
899   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
900     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
901     << ", offset=" << offsetBearing);
902
903   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
904
905   _turnPt = _currentWaypt->position();
906   _anticipateTurn = true;
907 }
908
909 void GPS::updateTurnData()
910 {
911   // depends on ground speed, so needs to be updated per-frame
912   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
913   
914   // compute the turn centre, based on the turn radius.
915   // key thing is to understand that we're working a right-angle triangle,
916   // where the right-angle is the point we start the turn. From that point,
917   // one side is the inbound course to the turn pt, and the other is the
918   // perpendicular line, of length 'r', to the turn centre.
919   // the triangle's hypotenuse, which we need to find, is the distance from the
920   // turn pt to the turn center (in the direction of the offset bearing)
921   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
922   
923   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
924   double d = _turnRadius / cos(halfTurnAngle);
925   
926  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
927  //   << " (cut distance=" << d - _turnRadius << ")");
928   
929   double median = _turnStartBearing + (_turnAngle * 0.5);
930   double offsetBearing = median + copysign(90, _turnAngle);
931   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
932   
933   double az2;
934   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
935 }
936
937 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
938 {
939         // turn time is seconds to execute a 360 turn. 
940   double turnTime = 360.0 / _config.turnRateDegSec();
941   
942   // c is ground distance covered in that time (circumference of the circle)
943         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
944   
945   // divide by 2PI to go from circumference -> radius
946         return c / (2 * M_PI);
947 }
948
949 void GPS::updateRouteData()
950 {
951   double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
952   // walk all waypoints from wp2 to route end, and sum
953   for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
954     //totalDistance += _routeMgr->get_waypoint(i).get_distance();
955   }
956   
957   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
958   if (_last_speed_kts > 1.0) {
959     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
960     _routeETE->setStringValue(makeTTWString(TTW));    
961   }
962 }
963
964 void GPS::driveAutopilot()
965 {
966   if (!_config.driveAutopilot() || !_realismSimpleGps->getBoolValue()) {
967     _apDrivingFlag->setBoolValue(false);
968     return;
969   }
970  
971   // compatability feature - allow the route-manager / GPS to drive the
972   // generic autopilot heading hold *in leg mode only* 
973   
974   bool drive = _mode == "leg";
975   _apDrivingFlag->setBoolValue(drive);
976   
977   if (drive) {
978     // FIXME: we want to set desired track, not heading, here
979     _apTrueHeading->setDoubleValue(getWP1Bearing());
980   }
981 }
982
983 void GPS::wp1Changed()
984 {
985   if (!_currentWaypt)
986     return;
987   if (_mode == "leg") {
988     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
989   } else if (_mode == "obs") {
990     _wayptController.reset(new OBSController(this, _currentWaypt));
991   } else if (_mode == "dto") {
992     _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
993   }
994
995   _wayptController->init();
996
997   if (_mode == "obs") {
998     _legDistanceNm = -1.0;
999   } else {
1000     _wayptController->update();
1001     _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1002   }
1003   
1004   if (!_config.driveAutopilot()) {
1005     return;
1006   }
1007   
1008   RouteRestriction ar = _currentWaypt->altitudeRestriction();
1009   double restrictAlt = _currentWaypt->altitudeFt();
1010   double alt = _indicated_pos.getElevationFt();
1011   if ((ar == RESTRICT_AT) ||
1012        ((ar == RESTRICT_ABOVE) && (alt < restrictAlt)) ||
1013        ((ar == RESTRICT_BELOW) && (alt > restrictAlt)))
1014   {
1015     SG_LOG(SG_AUTOPILOT, SG_INFO, "current waypt has altitude set, setting on AP");
1016     _apTargetAltitudeFt->setDoubleValue(restrictAlt);
1017   }
1018 }
1019
1020 /////////////////////////////////////////////////////////////////////////////
1021 // property getter/setters
1022
1023 void GPS::setSelectedCourse(double crs)
1024 {
1025   if (_selectedCourse == crs) {
1026     return;
1027   }
1028   
1029   _selectedCourse = crs;
1030   if ((_mode == "obs") || _config.courseSelectable()) {
1031     _desiredCourse = _selectedCourse;
1032     _desiredCourseNode->fireValueChanged();
1033   }
1034 }
1035
1036 double GPS::getLegDistance() const
1037 {
1038   if (!_dataValid || (_mode == "obs")) {
1039     return -1;
1040   }
1041   
1042   return _legDistanceNm;
1043 }
1044
1045 double GPS::getLegCourse() const
1046 {
1047   if (!_dataValid || !_wayptController.get()) {
1048     return -9999.0;
1049   }
1050   
1051   return _wayptController->targetTrackDeg();
1052 }
1053
1054 double GPS::getLegMagCourse() const
1055 {
1056   if (!_dataValid) {
1057     return 0.0;
1058   }
1059   
1060   double m = getLegCourse() - _magvar_node->getDoubleValue();
1061   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1062   return m;
1063 }
1064
1065 double GPS::getMagTrack() const
1066 {
1067   if (!_dataValid) {
1068     return 0.0;
1069   }
1070   
1071   double m = getTrueTrack() - _magvar_node->getDoubleValue();
1072   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
1073   return m;
1074 }
1075
1076 double GPS::getCDIDeflection() const
1077 {
1078   if (!_dataValid) {
1079     return 0.0;
1080   }
1081   
1082   double defl;
1083   if (_config.cdiDeflectionIsAngular()) {
1084     defl = getWP1CourseDeviation();
1085     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
1086   } else {
1087     double fullScale = _config.cdiDeflectionLinearPeg();
1088     double normError = getWP1CourseErrorNm() / fullScale;
1089     SG_CLAMP_RANGE(normError, -1.0, 1.0);
1090     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
1091   }
1092   
1093   return defl;
1094 }
1095
1096 const char* GPS::getWP0Ident() const
1097 {
1098   if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
1099     return "";
1100   }
1101   
1102   return _prevWaypt->ident().c_str();
1103 }
1104
1105 const char* GPS::getWP0Name() const
1106 {
1107   return "";
1108 }
1109
1110 const char* GPS::getWP1Ident() const
1111 {
1112   if ((!_dataValid)||(!_currentWaypt)) {
1113     return "";
1114   }
1115   
1116   return _currentWaypt->ident().c_str();
1117 }
1118
1119 const char* GPS::getWP1Name() const
1120 {
1121   return "";
1122 }
1123
1124 double GPS::getWP1Distance() const
1125 {
1126   if (!_dataValid || !_wayptController.get()) {
1127     return -1.0;
1128   }
1129   
1130   return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
1131 }
1132
1133 double GPS::getWP1TTW() const
1134 {
1135   if (!_dataValid || !_wayptController.get()) {
1136     return -1.0;
1137   }
1138   
1139   return _wayptController->timeToWaypt();
1140 }
1141
1142 const char* GPS::getWP1TTWString() const
1143 {
1144   double t = getWP1TTW();
1145   if (t <= 0.0) {
1146     return "";
1147   }
1148   
1149   return makeTTWString(t);
1150 }
1151
1152 double GPS::getWP1Bearing() const
1153 {
1154   if (!_dataValid || !_wayptController.get()) {
1155     return -9999.0;
1156   }
1157   
1158   return _wayptController->trueBearingDeg();
1159 }
1160
1161 double GPS::getWP1MagBearing() const
1162 {
1163   if (!_dataValid || !_wayptController.get()) {
1164     return -9999.0;
1165   }
1166
1167   double magBearing =  _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
1168   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
1169   return magBearing;
1170 }
1171
1172 double GPS::getWP1CourseDeviation() const
1173 {
1174   if (!_dataValid || !_wayptController.get()) {
1175     return 0.0;
1176   }
1177
1178   return _wayptController->courseDeviationDeg();
1179 }
1180
1181 double GPS::getWP1CourseErrorNm() const
1182 {
1183   if (!_dataValid || !_wayptController.get()) {
1184     return 0.0;
1185   }
1186   
1187   return _wayptController->xtrackErrorNm();
1188 }
1189
1190 bool GPS::getWP1ToFlag() const
1191 {
1192   if (!_dataValid || !_wayptController.get()) {
1193     return false;
1194   }
1195   
1196   return _wayptController->toFlag();
1197 }
1198
1199 bool GPS::getWP1FromFlag() const
1200 {
1201   if (!_dataValid || !_wayptController.get()) {
1202     return false;
1203   }
1204   
1205   return !getWP1ToFlag();
1206 }
1207
1208 double GPS::getScratchDistance() const
1209 {
1210   if (!_scratchValid) {
1211     return 0.0;
1212   }
1213   
1214   return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1215 }
1216
1217 double GPS::getScratchTrueBearing() const
1218 {
1219   if (!_scratchValid) {
1220     return 0.0;
1221   }
1222
1223   return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1224 }
1225
1226 double GPS::getScratchMagBearing() const
1227 {
1228   if (!_scratchValid) {
1229     return 0.0;
1230   }
1231   
1232   double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1233   SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1234   return crs;
1235 }
1236
1237 /////////////////////////////////////////////////////////////////////////////
1238 // command / scratch / search system
1239
1240 void GPS::setCommand(const char* aCmd)
1241 {
1242   SG_LOG(SG_INSTR, SG_INFO, "GPS command:" << aCmd);
1243   
1244   if (!strcmp(aCmd, "direct")) {
1245     directTo();
1246   } else if (!strcmp(aCmd, "obs")) {
1247     selectOBSMode();
1248   } else if (!strcmp(aCmd, "leg")) {
1249     selectLegMode();
1250   } else if (!strcmp(aCmd, "load-route-wpt")) {
1251     loadRouteWaypoint();
1252   } else if (!strcmp(aCmd, "nearest")) {
1253     loadNearest();
1254   } else if (!strcmp(aCmd, "search")) {
1255     _searchNames = false;
1256     search();
1257   } else if (!strcmp(aCmd, "search-names")) {
1258     _searchNames = true;
1259     search();
1260   } else if (!strcmp(aCmd, "next")) {
1261     nextResult();
1262   } else if (!strcmp(aCmd, "previous")) {
1263     previousResult();
1264   } else if (!strcmp(aCmd, "define-user-wpt")) {
1265     defineWaypoint();
1266   } else if (!strcmp(aCmd, "route-insert-before")) {
1267     int index = _scratchNode->getIntValue("index");
1268     if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1269       index = _routeMgr->numWaypts();
1270     } else if (index >= _routeMgr->numWaypts()) {
1271       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1272       return;
1273     }
1274     
1275     insertWaypointAtIndex(index);
1276   } else if (!strcmp(aCmd, "route-insert-after")) {
1277     int index = _scratchNode->getIntValue("index");
1278     if (index < 0 || (_routeMgr->numWaypts() == 0)) {
1279       index = _routeMgr->numWaypts();
1280     } else if (index >= _routeMgr->numWaypts()) {
1281       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1282       return;
1283     } else {
1284       ++index; 
1285     }
1286   
1287     insertWaypointAtIndex(index);
1288   } else if (!strcmp(aCmd, "route-delete")) {
1289     int index = _scratchNode->getIntValue("index");
1290     if (index < 0) {
1291       index = _routeMgr->numWaypts();
1292     } else if (index >= _routeMgr->numWaypts()) {
1293       SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1294       return;
1295     }
1296     
1297     removeWaypointAtIndex(index);
1298   } else {
1299     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1300   }
1301 }
1302
1303 void GPS::clearScratch()
1304 {
1305   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1306   _scratchValid = false;  
1307   _scratchNode->setStringValue("type", "");
1308   _scratchNode->setStringValue("query", "");
1309 }
1310
1311 bool GPS::isScratchPositionValid() const
1312 {
1313   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1314       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1315    return false;   
1316   }
1317   
1318   return true;
1319 }
1320
1321 void GPS::directTo()
1322 {  
1323   if (!isScratchPositionValid()) {
1324     return;
1325   }
1326   
1327   _prevWaypt = NULL;
1328   _wp0_position = _indicated_pos;
1329   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1330   _mode = "dto";
1331
1332   clearScratch();
1333   wp1Changed();
1334 }
1335
1336 void GPS::loadRouteWaypoint()
1337 {
1338   _scratchValid = false;
1339 //  if (!_routeMgr->isRouteActive()) {
1340 //    SG_LOG(SG_INSTR, SG_WARN, "GPS:loadWaypoint: no active route");
1341 //    return;
1342 //  }
1343   
1344   int index = _scratchNode->getIntValue("index", -9999);
1345   clearScratch();
1346   
1347   if ((index < 0) || (index >= _routeMgr->numWaypts())) { // no index supplied, use current wp
1348     index = _routeMgr->currentIndex();
1349   }
1350   
1351   _searchIsRoute = true;
1352   setScratchFromRouteWaypoint(index);
1353 }
1354
1355 void GPS::setScratchFromRouteWaypoint(int aIndex)
1356 {
1357   assert(_searchIsRoute);
1358   if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1359     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1360     return;
1361   }
1362   
1363   _searchResultIndex = aIndex;
1364   WayptRef wp = _routeMgr->wayptAtIndex(aIndex);
1365   _scratchNode->setStringValue("ident", wp->ident());
1366   _scratchPos = wp->position();
1367   _scratchValid = true;
1368   _scratchNode->setIntValue("index", aIndex);
1369 }
1370
1371 void GPS::loadNearest()
1372 {
1373   string sty(_scratchNode->getStringValue("type"));
1374   FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1375   if (ty == FGPositioned::INVALID) {
1376     SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1377     return;
1378   }
1379   
1380   auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1381   int limitCount = _scratchNode->getIntValue("max-results", 1);
1382   double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1383   
1384   SGGeod searchPos = _indicated_pos;
1385   if (isScratchPositionValid()) {
1386     searchPos = _scratchPos;
1387   }
1388   
1389   clearScratch(); // clear now, regardless of whether we find a match or not
1390     
1391   _searchResults = 
1392     FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1393   _searchResultIndex = 0;
1394   _searchIsRoute = false;
1395   
1396   if (_searchResults.empty()) {
1397     SG_LOG(SG_INSTR, SG_INFO, "GPS:loadNearest: no matches at all");
1398     return;
1399   }
1400   
1401   setScratchFromCachedSearchResult();
1402 }
1403
1404 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1405 {
1406   switch (aPos->type()) {
1407   case FGPositioned::AIRPORT:
1408   // heliport and seaport too?
1409   case FGPositioned::VOR:
1410   case FGPositioned::NDB:
1411   case FGPositioned::FIX:
1412   case FGPositioned::TACAN:
1413   case FGPositioned::WAYPOINT:
1414     return true;
1415   default:
1416     return false;
1417   }
1418 }
1419
1420 FGPositioned::Type GPS::SearchFilter::minType() const
1421 {
1422   return FGPositioned::AIRPORT;
1423 }
1424
1425 FGPositioned::Type GPS::SearchFilter::maxType() const
1426 {
1427   return FGPositioned::WAYPOINT;
1428 }
1429
1430 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1431 {
1432   if (aTy == FGPositioned::AIRPORT) {
1433     return new FGAirport::HardSurfaceFilter(_config.minRunwayLengthFt());
1434   }
1435   
1436   // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1437   if (aTy == FGPositioned::INVALID) {
1438     return new SearchFilter;
1439   }
1440   
1441   return new FGPositioned::TypeFilter(aTy);
1442 }
1443
1444 void GPS::search()
1445 {
1446   // parse search terms into local members, and exec the first search
1447   string sty(_scratchNode->getStringValue("type"));
1448   _searchType = FGPositioned::typeFromName(sty);
1449   _searchQuery = _scratchNode->getStringValue("query");
1450   if (_searchQuery.empty()) {
1451     SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1452     clearScratch();
1453     return;
1454   }
1455   
1456   _searchExact = _scratchNode->getBoolValue("exact", true);
1457   _searchResultIndex = 0;
1458   _searchIsRoute = false;
1459
1460   auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1461   if (_searchNames) {
1462     _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1463   } else {
1464     _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1465   }
1466   
1467   bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1468   if (orderByRange) {
1469     FGPositioned::sortByRange(_searchResults, _indicated_pos);
1470   }
1471   
1472   if (_searchResults.empty()) {
1473     clearScratch();
1474     return;
1475   }
1476   
1477   setScratchFromCachedSearchResult();
1478 }
1479
1480 bool GPS::getScratchHasNext() const
1481 {
1482   int lastResult;
1483   if (_searchIsRoute) {
1484     lastResult = _routeMgr->numWaypts() - 1;
1485   } else {
1486     lastResult = (int) _searchResults.size() - 1;
1487   }
1488
1489   if (lastResult < 0) { // search array might be empty
1490     return false;
1491   }
1492   
1493   return (_searchResultIndex < lastResult);
1494 }
1495
1496 void GPS::setScratchFromCachedSearchResult()
1497 {
1498   int index = _searchResultIndex;
1499   
1500   if ((index < 0) || (index >= (int) _searchResults.size())) {
1501     SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1502     return;
1503   }
1504   
1505   setScratchFromPositioned(_searchResults[index], index);
1506 }
1507
1508 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1509 {
1510   clearScratch();
1511   assert(aPos);
1512
1513   _scratchPos = aPos->geod();
1514   _scratchNode->setStringValue("name", aPos->name());
1515   _scratchNode->setStringValue("ident", aPos->ident());
1516   _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1517     
1518   if (aIndex >= 0) {
1519     _scratchNode->setIntValue("index", aIndex);
1520   }
1521   
1522   _scratchValid = true;
1523   _scratchNode->setIntValue("result-count", _searchResults.size());
1524   
1525   switch (aPos->type()) {
1526   case FGPositioned::VOR:
1527     _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1528     break;
1529   
1530   case FGPositioned::NDB:
1531     _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1532     break;
1533   
1534   case FGPositioned::AIRPORT:
1535     addAirportToScratch((FGAirport*)aPos);
1536     break;
1537   
1538   default:
1539       // no-op
1540       break;
1541   }
1542   
1543   // look for being on the route and set?
1544 }
1545
1546 void GPS::addAirportToScratch(FGAirport* aAirport)
1547 {
1548   for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1549     SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1550     FGRunway* rwy = aAirport->getRunwayByIndex(r);
1551     // TODO - filter out unsuitable runways in the future
1552     // based on config again
1553     
1554     rwyNd->setStringValue("id", rwy->ident().c_str());
1555     rwyNd->setIntValue("length-ft", rwy->lengthFt());
1556     rwyNd->setIntValue("width-ft", rwy->widthFt());
1557     rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1558     // map surface code to a string
1559     // TODO - lighting information
1560     
1561     if (rwy->ILS()) {
1562       rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1563     }
1564   } // of runways iteration
1565 }
1566
1567
1568 void GPS::selectOBSMode()
1569 {
1570   if (!isScratchPositionValid()) {
1571     return;
1572   }
1573   
1574   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to OBS mode");
1575   _mode = "obs";
1576
1577   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1578   _wp0_position = _indicated_pos;
1579   wp1Changed();
1580 }
1581
1582 void GPS::selectLegMode()
1583 {
1584   if (_mode == "leg") {
1585     return;
1586   }
1587   
1588   if (!_routeMgr->isRouteActive()) {
1589     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1590     return;
1591   }
1592
1593   SG_LOG(SG_INSTR, SG_INFO, "GPS switching to LEG mode");
1594   _mode = "leg";
1595   
1596   // depending on the situation, this will either get over-written 
1597   // in routeManagerSequenced or not; either way it does no harm to
1598   // set it here.
1599   _wp0_position = _indicated_pos;
1600
1601   // not really sequenced, but does all the work of updating wp0/1
1602   routeManagerSequenced();
1603 }
1604
1605 void GPS::nextResult()
1606 {
1607   if (!getScratchHasNext()) {
1608     return;
1609   }
1610   
1611   clearScratch();
1612   if (_searchIsRoute) {
1613     setScratchFromRouteWaypoint(++_searchResultIndex);
1614   } else {
1615     ++_searchResultIndex;
1616     setScratchFromCachedSearchResult();
1617   }
1618 }
1619
1620 void GPS::previousResult()
1621 {
1622   if (_searchResultIndex <= 0) {
1623     return;
1624   }
1625   
1626   clearScratch();
1627   --_searchResultIndex;
1628   
1629   if (_searchIsRoute) {
1630     setScratchFromRouteWaypoint(_searchResultIndex);
1631   } else {
1632     setScratchFromCachedSearchResult();
1633   }
1634 }
1635
1636 void GPS::defineWaypoint()
1637 {
1638   if (!isScratchPositionValid()) {
1639     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1640     return;
1641   }
1642   
1643   string ident = _scratchNode->getStringValue("ident");
1644   if (ident.size() < 2) {
1645     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1646     return;
1647   }
1648     
1649 // check for duplicate idents
1650   FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1651   FGPositioned::List dups = FGPositioned::findAllWithIdent(ident, &f);
1652   if (!dups.empty()) {
1653     SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1654   }
1655   
1656   SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1657   FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1658   _searchResults.clear();
1659   _searchResults.push_back(wpt);
1660   setScratchFromPositioned(wpt.get(), -1);
1661 }
1662
1663 void GPS::insertWaypointAtIndex(int aIndex)
1664 {
1665   // note we do allow index = routeMgr->size(), that's an append
1666   if ((aIndex < 0) || (aIndex > _routeMgr->numWaypts())) {
1667     throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1668   }
1669   
1670   if (!isScratchPositionValid()) {
1671     SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1672     return;
1673   }
1674   
1675   string ident = _scratchNode->getStringValue("ident");
1676
1677   WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1678   _routeMgr->insertWayptAtIndex(wpt, aIndex);
1679 }
1680
1681 void GPS::removeWaypointAtIndex(int aIndex)
1682 {
1683   if ((aIndex < 0) || (aIndex >= _routeMgr->numWaypts())) {
1684     throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1685   }
1686   
1687   _routeMgr->removeWayptAtIndex(aIndex);
1688 }
1689
1690 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1691   const char* lonStr, const char* latStr, const char* altStr)
1692 {
1693   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1694   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1695   
1696   if (altStr) {
1697     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1698   }
1699 }
1700
1701 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1702   const char* lonStr, const char* latStr, const char* altStr)
1703 {
1704   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1705   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1706   
1707   if (altStr) {
1708     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1709   }
1710 }
1711
1712 // end of gps.cxx