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