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