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