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