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