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