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