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