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