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