]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/gps.cxx
Restore GPS compatibility with 2.10
[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 <boost/tuple/tuple.hpp>
13
14 #include <memory>
15 #include <set>
16 #include <cstring>
17 #include <cstdio>
18
19 #include "Main/fg_props.hxx"
20 #include "Main/globals.hxx" // for get_subsystem
21 #include "Main/util.hxx" // for fgLowPass
22 #include "Navaids/positioned.hxx"
23 #include <Navaids/waypoint.hxx>
24 #include "Navaids/navrecord.hxx"
25 #include "Navaids/FlightPlan.hxx"
26 #include "Airports/airport.hxx"
27 #include "Airports/runways.hxx"
28 #include "Autopilot/route_mgr.hxx"
29
30 #include <simgear/math/sg_random.h>
31 #include <simgear/sg_inlines.h>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/structure/exception.hxx>
34
35 using std::auto_ptr;
36 using std::string;
37 using namespace flightgear;
38
39
40 static const char* makeTTWString(double TTW)
41 {
42   if ((TTW <= 0.0) || (TTW >= 356400.5)) { // 99 hours
43     return "--:--:--";
44   }
45       
46   unsigned int TTW_seconds = (int) (TTW + 0.5);
47   unsigned int TTW_minutes = 0;
48   unsigned int TTW_hours   = 0;
49   static char TTW_str[9];
50   TTW_hours   = TTW_seconds / 3600;
51   TTW_minutes = (TTW_seconds / 60) % 60;
52   TTW_seconds = TTW_seconds % 60;
53   snprintf(TTW_str, 9, "%02d:%02d:%02d",
54     TTW_hours, TTW_minutes, TTW_seconds);
55   return TTW_str;
56 }
57
58 ////////////////////////////////////////////////////////////////////////////
59 // configuration helper object
60
61 GPS::Config::Config() :
62   _enableTurnAnticipation(true),
63   _turnRate(3.0), // degrees-per-second, so 180 degree turn takes 60 seconds
64   _overflightArmDistance(1.0),
65   _waypointAlertTime(30.0),
66   _requireHardSurface(true),
67   _cdiMaxDeflectionNm(3.0), // linear mode, 3nm at the peg
68   _driveAutopilot(true),
69   _courseSelectable(false)
70 {
71   _enableTurnAnticipation = false;
72 }
73
74 void GPS::Config::bind(GPS* aOwner, SGPropertyNode* aCfg)
75 {
76   aOwner->tie(aCfg, "turn-rate-deg-sec", SGRawValuePointer<double>(&_turnRate));
77   aOwner->tie(aCfg, "turn-anticipation", SGRawValuePointer<bool>(&_enableTurnAnticipation));
78   aOwner->tie(aCfg, "wpt-alert-time", SGRawValuePointer<double>(&_waypointAlertTime));
79   aOwner->tie(aCfg, "hard-surface-runways-only", SGRawValuePointer<bool>(&_requireHardSurface));
80   aOwner->tie(aCfg, "cdi-max-deflection-nm", SGRawValuePointer<double>(&_cdiMaxDeflectionNm));
81   aOwner->tie(aCfg, "drive-autopilot", SGRawValuePointer<bool>(&_driveAutopilot));
82   aOwner->tie(aCfg, "course-selectable", SGRawValuePointer<bool>(&_courseSelectable));
83 }
84
85 ////////////////////////////////////////////////////////////////////////////
86
87 GPS::GPS ( SGPropertyNode *node, bool defaultGPSMode) :
88   _selectedCourse(0.0),
89   _desiredCourse(0.0),
90   _dataValid(false),
91   _lastPosValid(false),
92   _defaultGPSMode(defaultGPSMode),
93   _mode("init"),
94   _name(node->getStringValue("name", "gps")),
95   _num(node->getIntValue("number", 0)),
96   _computeTurnData(false),
97   _anticipateTurn(false),
98   _inTurn(false),
99   _callbackFlightPlanChanged(SGPropertyChangeCallback<GPS>(this,&GPS::routeManagerFlightPlanChanged,
100                                                            fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true))),
101   _callbackRouteActivated(SGPropertyChangeCallback<GPS>(this,&GPS::routeActivated,
102                                                       fgGetNode("/autopilot/route-manager/active", true)))
103 {
104   string branch = "/instrumentation/" + _name;
105   _gpsNode = fgGetNode(branch.c_str(), _num, true );
106   _scratchNode = _gpsNode->getChild("scratch", 0, true);
107   
108   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
109   _currentWayptNode = wp_node->getChild("wp", 1, true);
110 }
111
112 GPS::~GPS ()
113 {
114 }
115
116 void
117 GPS::init ()
118 {
119   _magvar_node = fgGetNode("/environment/magnetic-variation-deg", true);
120   _serviceable_node = _gpsNode->getChild("serviceable", 0, true);
121   _serviceable_node->setBoolValue(true);
122   _electrical_node = fgGetNode("/systems/electrical/outputs/gps", true);
123
124 // basic GPS outputs
125   _raim_node = _gpsNode->getChild("raim", 0, true);
126   _odometer_node = _gpsNode->getChild("odometer", 0, true);
127   _trip_odometer_node = _gpsNode->getChild("trip-odometer", 0, true);
128   _true_bug_error_node = _gpsNode->getChild("true-bug-error-deg", 0, true);
129   _magnetic_bug_error_node = _gpsNode->getChild("magnetic-bug-error-deg", 0, true);
130   _eastWestVelocity = _gpsNode->getChild("ew-velocity-msec", 0, true);
131   _northSouthVelocity = _gpsNode->getChild("ns-velocity-msec", 0, true);
132   
133 // waypoints
134   // for compatability, alias selected course down to wp/wp[1]/desired-course-deg
135   SGPropertyNode* wp1Crs = _currentWayptNode->getChild("desired-course-deg", 0, true);
136   wp1Crs->alias(_gpsNode->getChild("desired-course-deg", 0, true));
137
138   _tracking_bug_node = _gpsNode->getChild("tracking-bug", 0, true);
139     
140 // route properties
141   // should these move to the route manager?
142   _routeDistanceNm = _gpsNode->getChild("route-distance-nm", 0, true);
143   _routeETE = _gpsNode->getChild("ETE", 0, true);
144
145     
146 // navradio slaving properties
147   SGPropertyNode* toFlag = _gpsNode->getChild("to-flag", 0, true);
148   toFlag->alias(_currentWayptNode->getChild("to-flag"));
149   
150   SGPropertyNode* fromFlag = _gpsNode->getChild("from-flag", 0, true);
151   fromFlag->alias(_currentWayptNode->getChild("from-flag"));
152     
153 // autopilot drive properties
154   _apDrivingFlag = fgGetNode("/autopilot/settings/gps-driving-true-heading", true);
155   _apTrueHeading = fgGetNode("/autopilot/settings/true-heading-deg",true);
156     
157   clearOutput();
158 }
159
160 void
161 GPS::reinit ()
162 {
163   clearOutput();
164 }
165
166 void
167 GPS::bind()
168 {
169   _config.bind(this, _gpsNode->getChild("config", 0, true));
170
171 // basic GPS outputs
172   tie(_gpsNode, "selected-course-deg", SGRawValueMethods<GPS, double>
173     (*this, &GPS::getSelectedCourse, &GPS::setSelectedCourse));
174
175   tie(_gpsNode, "desired-course-deg", SGRawValueMethods<GPS, double>
176     (*this, &GPS::getDesiredCourse, NULL));
177   _desiredCourseNode = _gpsNode->getChild("desired-course-deg", 0, true);
178     
179   tieSGGeodReadOnly(_gpsNode, _indicated_pos, "indicated-longitude-deg", 
180         "indicated-latitude-deg", "indicated-altitude-ft");
181
182   tie(_gpsNode, "indicated-vertical-speed", SGRawValueMethods<GPS, double>
183     (*this, &GPS::getVerticalSpeed, NULL));
184   tie(_gpsNode, "indicated-track-true-deg", SGRawValueMethods<GPS, double>
185     (*this, &GPS::getTrueTrack, NULL));
186   tie(_gpsNode, "indicated-track-magnetic-deg", SGRawValueMethods<GPS, double>
187     (*this, &GPS::getMagTrack, NULL));
188   tie(_gpsNode, "indicated-ground-speed-kt", SGRawValueMethods<GPS, double>
189     (*this, &GPS::getGroundspeedKts, NULL));
190   
191 // command system
192   tie(_gpsNode, "mode", SGRawValueMethods<GPS, const char*>(*this, &GPS::getMode, NULL));
193   tie(_gpsNode, "command", SGRawValueMethods<GPS, const char*>(*this, &GPS::getCommand, &GPS::setCommand));
194   tieSGGeod(_scratchNode, _scratchPos, "longitude-deg", "latitude-deg", "altitude-ft");
195   
196 #if FG_210_COMPAT
197     tie(_scratchNode, "valid", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchValid, NULL));
198     tie(_scratchNode, "distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchDistance, NULL));
199     tie(_scratchNode, "true-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchTrueBearing, NULL));
200     tie(_scratchNode, "mag-bearing-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getScratchMagBearing, NULL));
201     tie(_scratchNode, "has-next", SGRawValueMethods<GPS, bool>(*this, &GPS::getScratchHasNext, NULL));
202     _scratchValid = false;
203     
204     _scratchNode->setStringValue("type", "");
205     _scratchNode->setStringValue("query", "");
206 #endif
207     
208   SGPropertyNode *wp_node = _gpsNode->getChild("wp", 0, true);
209   SGPropertyNode* wp0_node = wp_node->getChild("wp", 0, true);
210   tieSGGeodReadOnly(wp0_node, _wp0_position, "longitude-deg", "latitude-deg", "altitude-ft");
211   tie(wp0_node, "ID", SGRawValueMethods<GPS, const char*>
212       (*this, &GPS::getWP0Ident, NULL));
213     
214     
215   tie(_currentWayptNode, "ID", SGRawValueMethods<GPS, const char*>
216     (*this, &GPS::getWP1Ident, NULL));
217   
218   tie(_currentWayptNode, "distance-nm", SGRawValueMethods<GPS, double>
219     (*this, &GPS::getWP1Distance, NULL));
220   tie(_currentWayptNode, "bearing-true-deg", SGRawValueMethods<GPS, double>
221     (*this, &GPS::getWP1Bearing, NULL));
222   tie(_currentWayptNode, "bearing-mag-deg", SGRawValueMethods<GPS, double>
223     (*this, &GPS::getWP1MagBearing, NULL));
224   tie(_currentWayptNode, "TTW-sec", SGRawValueMethods<GPS, double>
225     (*this, &GPS::getWP1TTW, NULL));
226   tie(_currentWayptNode, "TTW", SGRawValueMethods<GPS, const char*>
227     (*this, &GPS::getWP1TTWString, NULL));
228   
229   tie(_currentWayptNode, "course-deviation-deg", SGRawValueMethods<GPS, double>
230     (*this, &GPS::getWP1CourseDeviation, NULL));
231   tie(_currentWayptNode, "course-error-nm", SGRawValueMethods<GPS, double>
232     (*this, &GPS::getWP1CourseErrorNm, NULL));
233   tie(_currentWayptNode, "to-flag", SGRawValueMethods<GPS, bool>
234     (*this, &GPS::getWP1ToFlag, NULL));
235   tie(_currentWayptNode, "from-flag", SGRawValueMethods<GPS, bool>
236     (*this, &GPS::getWP1FromFlag, NULL));
237
238 // leg properties (only valid in DTO/LEG modes, not OBS)
239   tie(wp_node, "leg-distance-nm", SGRawValueMethods<GPS, double>(*this, &GPS::getLegDistance, NULL));
240   tie(wp_node, "leg-true-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegCourse, NULL));
241   tie(wp_node, "leg-mag-course-deg", SGRawValueMethods<GPS, double>(*this, &GPS::getLegMagCourse, NULL));
242
243 // navradio slaving properties  
244   tie(_gpsNode, "cdi-deflection", SGRawValueMethods<GPS,double>
245     (*this, &GPS::getCDIDeflection));
246 }
247
248 void
249 GPS::unbind()
250 {
251   _tiedProperties.Untie();
252 }
253
254 void
255 GPS::clearOutput()
256 {
257   _dataValid = false;
258   _last_speed_kts = 0.0;
259   _last_pos = SGGeod();
260   _lastPosValid = false;
261   _indicated_pos = SGGeod();
262   _last_vertical_speed = 0.0;
263   _last_true_track = 0.0;
264   _lastEWVelocity = _lastNSVelocity = 0.0;
265   _currentWaypt = _prevWaypt = NULL;
266   _legDistanceNm = -1.0;
267   
268   _raim_node->setDoubleValue(0.0);
269   _indicated_pos = SGGeod();
270   _odometer_node->setDoubleValue(0);
271   _trip_odometer_node->setDoubleValue(0);
272   _tracking_bug_node->setDoubleValue(0);
273   _true_bug_error_node->setDoubleValue(0);
274   _magnetic_bug_error_node->setDoubleValue(0);
275   _northSouthVelocity->setDoubleValue(0.0);
276   _eastWestVelocity->setDoubleValue(0.0);
277 }
278
279 void
280 GPS::update (double delta_time_sec)
281 {
282   if (!_defaultGPSMode) {
283     // If it's off, don't bother.
284     if (!_serviceable_node->getBoolValue() || !_electrical_node->getBoolValue()) {
285       clearOutput();
286       return;
287     }
288   }
289   
290   if (delta_time_sec <= 0.0) {
291     return; // paused, don't bother
292   }    
293   
294   _raim_node->setDoubleValue(1.0);
295   _indicated_pos = globals->get_aircraft_position();
296   updateBasicData(delta_time_sec);
297
298   if (_dataValid) {
299     if (_wayptController.get()) {
300       _wayptController->update();
301       SGGeod p(_wayptController->position());
302       _currentWayptNode->setDoubleValue("longitude-deg", p.getLongitudeDeg());
303       _currentWayptNode->setDoubleValue("latitude-deg", p.getLatitudeDeg());
304       _currentWayptNode->setDoubleValue("altitude-ft", p.getElevationFt());
305       
306       _desiredCourse = getLegMagCourse();
307       
308       updateTurn();
309       updateRouteData();
310     }
311
312     
313     updateTrackingBug();
314     driveAutopilot();
315   }
316   
317   if (_dataValid && (_mode == "init")) {
318     // will select LEG mode if the route is active
319     routeManagerFlightPlanChanged(NULL);
320     
321     FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
322     if (!routeMgr->isRouteActive()) {
323       // initialise in OBS mode, with waypt set to the nearest airport.
324       // keep in mind at this point, _dataValid is not set
325       auto_ptr<FGPositioned::Filter> f(new FGAirport::HardSurfaceFilter());
326       FGPositionedRef apt = FGPositioned::findClosest(_indicated_pos, 20.0, f.get());
327       if (apt) {
328         selectOBSMode(new flightgear::NavaidWaypoint(apt, NULL));
329       }
330     }
331
332     if (_mode != "init")
333     {
334       // allow a realistic delay in the future, here
335     }
336   } // of init mode check
337   
338   _last_pos = _indicated_pos;
339   _lastPosValid = !(_last_pos == SGGeod());
340 }
341
342 void GPS::routeManagerFlightPlanChanged(SGPropertyNode*)
343 {
344   if (_route) {
345     _route->removeDelegate(this);
346   }
347   
348   SG_LOG(SG_INSTR, SG_INFO, "GPS saw route-manager flight-plan replaced.");
349   FGRouteMgr* routeMgr = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
350   _route = routeMgr->flightPlan();
351   if (_route) {
352     _route->addDelegate(this);
353   }
354   
355   if (routeMgr->isRouteActive()) {
356     selectLegMode();
357   } else {
358     selectOBSMode(_currentWaypt); // revert to OBS on current waypoint
359   }
360 }
361
362 void GPS::routeActivated(SGPropertyNode* aNode)
363 {
364   bool isActive = aNode->getBoolValue();
365   if (isActive) {
366     SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, switching to LEG mode");
367     selectLegMode();
368     
369     // if we've already passed the current waypoint, sequence.
370     if (_dataValid && getWP1FromFlag()) {
371       SG_LOG(SG_INSTR, SG_INFO, "GPS::route activated, FROM wp1, sequencing");
372       sequence();
373     }
374   } else if (_mode == "leg") {
375     SG_LOG(SG_INSTR, SG_INFO, "GPS::route deactivated, switching to OBS mode");
376     selectOBSMode(_currentWaypt);
377   }
378 }
379
380 ///////////////////////////////////////////////////////////////////////////
381 // implement the RNAV interface 
382 SGGeod GPS::position()
383 {
384   if (!_dataValid) {
385     return SGGeod();
386   }
387   
388   return _indicated_pos;
389 }
390
391 double GPS::trackDeg()
392 {
393   return _last_true_track;
394 }
395
396 double GPS::groundSpeedKts()
397 {
398   return _last_speed_kts;
399 }
400
401 double GPS::vspeedFPM()
402 {
403   return _last_vertical_speed;
404 }
405
406 double GPS::magvarDeg()
407 {
408   return _magvar_node->getDoubleValue();
409 }
410
411 double GPS::overflightArmDistanceM()
412 {
413   return _config.overflightArmDistanceNm() * SG_NM_TO_METER;
414 }
415
416 double GPS::selectedMagCourse()
417 {
418   return _selectedCourse;
419 }
420
421 ///////////////////////////////////////////////////////////////////////////
422
423 void
424 GPS::updateBasicData(double dt)
425 {
426   if (!_lastPosValid) {
427     return;
428   }
429   
430   double distance_m;
431   double track2_deg;
432   SGGeodesy::inverse(_last_pos, _indicated_pos, _last_true_track, track2_deg, distance_m );
433     
434   double speed_kt = ((distance_m * SG_METER_TO_NM) * ((1 / dt) * 3600.0));
435   double vertical_speed_mpm = ((_indicated_pos.getElevationM() - _last_pos.getElevationM()) * 60 / dt);
436   _last_vertical_speed = vertical_speed_mpm * SG_METER_TO_FEET;
437   
438   speed_kt = fgGetLowPass(_last_speed_kts, speed_kt, dt/10.0);
439   _last_speed_kts = speed_kt;
440   
441   SGGeod g = _indicated_pos;
442   g.setLongitudeDeg(_last_pos.getLongitudeDeg());
443   double northSouthM = SGGeodesy::distanceM(_last_pos, g);
444   northSouthM = copysign(northSouthM, _indicated_pos.getLatitudeDeg() - _last_pos.getLatitudeDeg());
445   
446   double nsMSec = fgGetLowPass(_lastNSVelocity, northSouthM / dt, dt/2.0);
447   _lastNSVelocity = nsMSec;
448   _northSouthVelocity->setDoubleValue(nsMSec);
449
450
451   g = _indicated_pos;
452   g.setLatitudeDeg(_last_pos.getLatitudeDeg());
453   double eastWestM = SGGeodesy::distanceM(_last_pos, g);
454   eastWestM = copysign(eastWestM, _indicated_pos.getLongitudeDeg() - _last_pos.getLongitudeDeg());
455   
456   double ewMSec = fgGetLowPass(_lastEWVelocity, eastWestM / dt, dt/2.0);
457   _lastEWVelocity = ewMSec;
458   _eastWestVelocity->setDoubleValue(ewMSec);
459   
460   double odometer = _odometer_node->getDoubleValue();
461   _odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
462   odometer = _trip_odometer_node->getDoubleValue();
463   _trip_odometer_node->setDoubleValue(odometer + distance_m * SG_METER_TO_NM);
464   
465   if (!_dataValid) {
466     _dataValid = true;
467   }
468 }
469
470 void
471 GPS::updateTrackingBug()
472 {
473   double tracking_bug = _tracking_bug_node->getDoubleValue();
474   double true_bug_error = tracking_bug - getTrueTrack();
475   double magnetic_bug_error = tracking_bug - getMagTrack();
476
477   // Get the errors into the (-180,180) range.
478   SG_NORMALIZE_RANGE(true_bug_error, -180.0, 180.0);
479   SG_NORMALIZE_RANGE(magnetic_bug_error, -180.0, 180.0);
480
481   _true_bug_error_node->setDoubleValue(true_bug_error);
482   _magnetic_bug_error_node->setDoubleValue(magnetic_bug_error);
483 }
484
485 void GPS::endOfFlightPlan()
486 {
487   selectOBSMode(_currentWaypt);
488 }
489
490 void GPS::currentWaypointChanged()
491 {
492   if (!_route) {
493     return;
494   }
495   
496   int index = _route->currentIndex(),
497     count = _route->numLegs();
498   if ((index < 0) || (index >= count)) {
499     _currentWaypt=NULL;
500     _prevWaypt=NULL;
501     // no active leg on the route
502     return;
503   }
504     
505   if (index > 0) {
506     _prevWaypt = _route->previousLeg()->waypoint();
507     if (_prevWaypt->flag(WPT_DYNAMIC)) {
508       _wp0_position = _indicated_pos;
509     } else {
510       _wp0_position = _prevWaypt->position();
511     }
512   }
513   
514   _currentWaypt = _route->currentLeg()->waypoint();
515   _desiredCourse = getLegMagCourse();
516   _desiredCourseNode->fireValueChanged();
517   wp1Changed();
518 }
519
520
521 void GPS::waypointsChanged()
522 {
523   if (_mode != "leg") {
524     return;
525   }
526   
527   SG_LOG(SG_INSTR, SG_INFO, "GPS route edited while in LEG mode, updating waypoints");
528   currentWaypointChanged();
529 }
530
531 void GPS::cleared()
532 {
533     if (_mode != "leg") {
534         return;
535     }
536     
537     selectOBSMode(_currentWaypt);
538 }
539
540 void GPS::sequence()
541 {
542     if (!_route) {
543         return;
544     }
545   
546     int nextIndex = _route->currentIndex() + 1;
547     if (nextIndex >= _route->numLegs()) {
548         SG_LOG(SG_INSTR, SG_INFO, "sequenced final leg, end of route");
549         _route->finish();
550         selectOBSMode(_currentWaypt);
551         return;
552     }
553     
554     // will callback into currentWaypointChanged
555     _route->setCurrentIndex(nextIndex);
556 }
557
558 void GPS::updateTurn()
559 {
560   bool printProgress = false;
561   
562   if (_computeTurnData) {
563     if (_last_speed_kts < 10) {
564       // need valid leg course and sensible ground speed to compute the turn
565       return;
566     }
567     
568     computeTurnData();
569     printProgress = true;
570   }
571   
572   if (!_anticipateTurn) {
573     updateOverflight();
574     return;
575   }
576
577   updateTurnData();
578   // find bearing to turn centre
579   double bearing, az2, distanceM;
580   SGGeodesy::inverse(_indicated_pos, _turnCentre, bearing, az2, distanceM);
581   double progress = computeTurnProgress(bearing);
582   
583   if (printProgress) {
584     SG_LOG(SG_INSTR, SG_INFO,"turn progress=" << progress);
585   }
586   
587   if (!_inTurn && (progress > 0.0)) {
588     beginTurn();
589   }
590   
591   if (_inTurn && !_turnSequenced && (progress > 0.5)) {
592     _turnSequenced = true;
593      SG_LOG(SG_INSTR, SG_INFO, "turn passed midpoint, sequencing");
594      sequence();
595   }
596   
597   if (_inTurn && (progress >= 1.0)) {
598     endTurn();
599   }
600   
601   if (_inTurn) {
602     // drive deviation and desired course
603     double desiredCourse = bearing - copysign(90, _turnAngle);
604     SG_NORMALIZE_RANGE(desiredCourse, 0.0, 360.0);
605     double deviationNm = (distanceM * SG_METER_TO_NM) - _turnRadius;
606     double deviationDeg = desiredCourse - getMagTrack();
607     deviationNm = copysign(deviationNm, deviationDeg);
608     // FIXME
609     //_wp1_course_deviation_node->setDoubleValue(deviationDeg);
610     //_wp1_course_error_nm_node->setDoubleValue(deviationNm);
611     //_cdiDeflectionNode->setDoubleValue(deviationDeg);
612   }
613 }
614
615 void GPS::updateOverflight()
616 {
617   if (!_wayptController->isDone()) {
618     return;
619   }
620   
621   if (_mode == "dto") {
622     SG_LOG(SG_INSTR, SG_INFO, "GPS DTO reached destination point");
623     
624     // check for wp1 being on active route - resume leg mode
625     if (_route) {
626       int index = _route->findWayptIndex(_currentWaypt->position());
627       if (index >= 0) {
628         SG_LOG(SG_INSTR, SG_INFO, "GPS DTO, resuming LEG mode at wp:" << index);
629         _mode = "leg";
630         _route->setCurrentIndex(index);
631         sequence(); // and sequence to the next point
632       }
633     }
634     
635     if (_mode == "dto") {
636       // if we didn't enter leg mode, drop back to OBS mode
637       // select OBS mode, but keep current waypoint-as is
638       _mode = "obs";
639       wp1Changed();
640     }
641   } else if (_mode == "leg") {
642     SG_LOG(SG_INSTR, SG_DEBUG, "GPS doing overflight sequencing");
643     sequence();
644   } else if (_mode == "obs") {
645     // nothing to do here, TO/FROM will update but that's fine
646   }
647   
648   _computeTurnData = true;
649 }
650
651 void GPS::beginTurn()
652 {
653   _inTurn = true;
654   _turnSequenced = false;
655   SG_LOG(SG_INSTR, SG_INFO, "beginning turn");
656 }
657
658 void GPS::endTurn()
659 {
660   _inTurn = false;
661   SG_LOG(SG_INSTR, SG_INFO, "ending turn");
662   _computeTurnData = true;
663 }
664
665 double GPS::computeTurnProgress(double aBearing) const
666 {
667   double startBearing = _turnStartBearing + copysign(90, _turnAngle);
668   return (aBearing - startBearing) / _turnAngle;
669 }
670
671 void GPS::computeTurnData()
672 {
673   _computeTurnData = false;
674   if ((_mode != "leg") || !_route->nextLeg()) {
675     _anticipateTurn = false;
676     return;
677   }
678   
679   WayptRef next = _route->nextLeg()->waypoint();
680   if (next->flag(WPT_DYNAMIC) || !_config.turnAnticipationEnabled()) {
681     _anticipateTurn = false;
682     return;
683   }
684   
685   _turnStartBearing = _desiredCourse;
686 // compute next leg course
687   double crs, dist;
688   boost::tie(crs, dist) = next->courseAndDistanceFrom(_currentWaypt->position());
689     
690
691 // compute offset bearing
692   _turnAngle = crs - _turnStartBearing;
693   SG_NORMALIZE_RANGE(_turnAngle, -180.0, 180.0);
694   double median = _turnStartBearing + (_turnAngle * 0.5);
695   double offsetBearing = median + copysign(90, _turnAngle);
696   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
697   
698   SG_LOG(SG_INSTR, SG_INFO, "GPS computeTurnData: in=" << _turnStartBearing <<
699     ", out=" << crs << "; turnAngle=" << _turnAngle << ", median=" << median 
700     << ", offset=" << offsetBearing);
701
702   SG_LOG(SG_INSTR, SG_INFO, "next leg is now:" << _currentWaypt->ident() << "->" << next->ident());
703
704   _turnPt = _currentWaypt->position();
705   _anticipateTurn = true;
706 }
707
708 void GPS::updateTurnData()
709 {
710   // depends on ground speed, so needs to be updated per-frame
711   _turnRadius = computeTurnRadiusNm(_last_speed_kts);
712   
713   // compute the turn centre, based on the turn radius.
714   // key thing is to understand that we're working a right-angle triangle,
715   // where the right-angle is the point we start the turn. From that point,
716   // one side is the inbound course to the turn pt, and the other is the
717   // perpendicular line, of length 'r', to the turn centre.
718   // the triangle's hypotenuse, which we need to find, is the distance from the
719   // turn pt to the turn center (in the direction of the offset bearing)
720   // note that d - _turnRadius tell us how much we're 'cutting' the corner.
721   
722   double halfTurnAngle = fabs(_turnAngle * 0.5) * SG_DEGREES_TO_RADIANS;
723   double d = _turnRadius / cos(halfTurnAngle);
724   
725  // SG_LOG(SG_INSTR, SG_INFO, "turnRadius=" << _turnRadius << ", d=" << d
726  //   << " (cut distance=" << d - _turnRadius << ")");
727   
728   double median = _turnStartBearing + (_turnAngle * 0.5);
729   double offsetBearing = median + copysign(90, _turnAngle);
730   SG_NORMALIZE_RANGE(offsetBearing, 0.0, 360.0);
731   
732   double az2;
733   SGGeodesy::direct(_turnPt, offsetBearing, d * SG_NM_TO_METER, _turnCentre, az2); 
734 }
735
736 double GPS::computeTurnRadiusNm(double aGroundSpeedKts) const
737 {
738         // turn time is seconds to execute a 360 turn. 
739   double turnTime = 360.0 / _config.turnRateDegSec();
740   
741   // c is ground distance covered in that time (circumference of the circle)
742         double c = turnTime * (aGroundSpeedKts / 3600.0); // convert knts to nm/sec
743   
744   // divide by 2PI to go from circumference -> radius
745         return c / (2 * M_PI);
746 }
747
748 void GPS::updateRouteData()
749 {
750   double totalDistance = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
751   // walk all waypoints from wp2 to route end, and sum
752  // for (int i=_routeMgr->currentIndex()+1; i<_routeMgr->numWaypts(); ++i) {
753     //totalDistance += _routeMgr->get_waypoint(i).get_distance();
754   //}
755   
756   _routeDistanceNm->setDoubleValue(totalDistance * SG_METER_TO_NM);
757   if (_last_speed_kts > 1.0) {
758     double TTW = ((totalDistance * SG_METER_TO_NM) / _last_speed_kts) * 3600.0;
759     _routeETE->setStringValue(makeTTWString(TTW));    
760   }
761 }
762
763 void GPS::driveAutopilot()
764 {
765   if (!_config.driveAutopilot() || !_defaultGPSMode) {
766     _apDrivingFlag->setBoolValue(false);
767     return;
768   }
769  
770   // compatability feature - allow the route-manager / GPS to drive the
771   // generic autopilot heading hold *in leg mode only* 
772   
773   bool drive = _mode == "leg";
774   _apDrivingFlag->setBoolValue(drive);
775   
776   if (drive) {
777     // FIXME: we want to set desired track, not heading, here
778     _apTrueHeading->setDoubleValue(getWP1Bearing());
779   }
780 }
781
782 void GPS::wp1Changed()
783 {
784   if (!_currentWaypt)
785     return;
786   if (_mode == "leg") {
787     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
788   } else if (_mode == "obs") {
789     _wayptController.reset(new OBSController(this, _currentWaypt));
790   } else if (_mode == "dto") {
791     _wayptController.reset(new DirectToController(this, _currentWaypt, _wp0_position));
792   }
793
794   _wayptController->init();
795
796   if (_mode == "obs") {
797     _legDistanceNm = -1.0;
798   } else {
799     _wayptController->update();
800     _legDistanceNm = _wayptController->distanceToWayptM() * SG_METER_TO_NM;
801   }
802 }
803
804 /////////////////////////////////////////////////////////////////////////////
805 // property getter/setters
806
807 void GPS::setSelectedCourse(double crs)
808 {
809   if (_selectedCourse == crs) {
810     return;
811   }
812   
813   _selectedCourse = crs;
814   if ((_mode == "obs") || _config.courseSelectable()) {
815     _desiredCourse = _selectedCourse;
816     _desiredCourseNode->fireValueChanged();
817   }
818 }
819
820 double GPS::getLegDistance() const
821 {
822   if (!_dataValid || (_mode == "obs")) {
823     return -1;
824   }
825   
826   return _legDistanceNm;
827 }
828
829 double GPS::getLegCourse() const
830 {
831   if (!_dataValid || !_wayptController.get()) {
832     return -9999.0;
833   }
834   
835   return _wayptController->targetTrackDeg();
836 }
837
838 double GPS::getLegMagCourse() const
839 {
840   if (!_dataValid) {
841     return 0.0;
842   }
843   
844   double m = getLegCourse() - _magvar_node->getDoubleValue();
845   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
846   return m;
847 }
848
849 double GPS::getMagTrack() const
850 {
851   if (!_dataValid) {
852     return 0.0;
853   }
854   
855   double m = getTrueTrack() - _magvar_node->getDoubleValue();
856   SG_NORMALIZE_RANGE(m, 0.0, 360.0);
857   return m;
858 }
859
860 double GPS::getCDIDeflection() const
861 {
862   if (!_dataValid) {
863     return 0.0;
864   }
865   
866   double defl;
867   if (_config.cdiDeflectionIsAngular()) {
868     defl = getWP1CourseDeviation();
869     SG_CLAMP_RANGE(defl, -10.0, 10.0); // as in navradio.cxx
870   } else {
871     double fullScale = _config.cdiDeflectionLinearPeg();
872     double normError = getWP1CourseErrorNm() / fullScale;
873     SG_CLAMP_RANGE(normError, -1.0, 1.0);
874     defl = normError * 10.0; // re-scale to navradio limits, i.e [-10.0 .. 10.0]
875   }
876   
877   return defl;
878 }
879
880 const char* GPS::getWP0Ident() const
881 {
882   if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
883     return "";
884   }
885   
886   return _prevWaypt->ident().c_str();
887 }
888
889 const char* GPS::getWP0Name() const
890 {
891   return "";
892 }
893
894 const char* GPS::getWP1Ident() const
895 {
896   if ((!_dataValid)||(!_currentWaypt)) {
897     return "";
898   }
899   
900   return _currentWaypt->ident().c_str();
901 }
902
903 const char* GPS::getWP1Name() const
904 {
905   return "";
906 }
907
908 double GPS::getWP1Distance() const
909 {
910   if (!_dataValid || !_wayptController.get()) {
911     return -1.0;
912   }
913   
914   return _wayptController->distanceToWayptM() * SG_METER_TO_NM;
915 }
916
917 double GPS::getWP1TTW() const
918 {
919   if (!_dataValid || !_wayptController.get()) {
920     return -1.0;
921   }
922   
923   return _wayptController->timeToWaypt();
924 }
925
926 const char* GPS::getWP1TTWString() const
927 {
928   double t = getWP1TTW();
929   if (t <= 0.0) {
930     return "";
931   }
932   
933   return makeTTWString(t);
934 }
935
936 double GPS::getWP1Bearing() const
937 {
938   if (!_dataValid || !_wayptController.get()) {
939     return -9999.0;
940   }
941   
942   return _wayptController->trueBearingDeg();
943 }
944
945 double GPS::getWP1MagBearing() const
946 {
947   if (!_dataValid || !_wayptController.get()) {
948     return -9999.0;
949   }
950
951   double magBearing =  _wayptController->trueBearingDeg() - _magvar_node->getDoubleValue();
952   SG_NORMALIZE_RANGE(magBearing, 0.0, 360.0);
953   return magBearing;
954 }
955
956 double GPS::getWP1CourseDeviation() const
957 {
958   if (!_dataValid || !_wayptController.get()) {
959     return 0.0;
960   }
961
962   return _wayptController->courseDeviationDeg();
963 }
964
965 double GPS::getWP1CourseErrorNm() const
966 {
967   if (!_dataValid || !_wayptController.get()) {
968     return 0.0;
969   }
970   
971   return _wayptController->xtrackErrorNm();
972 }
973
974 bool GPS::getWP1ToFlag() const
975 {
976   if (!_dataValid || !_wayptController.get()) {
977     return false;
978   }
979   
980   return _wayptController->toFlag();
981 }
982
983 bool GPS::getWP1FromFlag() const
984 {
985   if (!_dataValid || !_wayptController.get()) {
986     return false;
987   }
988   
989   return !getWP1ToFlag();
990 }
991
992 #if FG_210_COMPAT
993 double GPS::getScratchDistance() const
994 {
995     if (!_scratchValid) {
996         return 0.0;
997     }
998     
999     return SGGeodesy::distanceNm(_indicated_pos, _scratchPos);
1000 }
1001
1002 double GPS::getScratchTrueBearing() const
1003 {
1004     if (!_scratchValid) {
1005         return 0.0;
1006     }
1007     
1008     return SGGeodesy::courseDeg(_indicated_pos, _scratchPos);
1009 }
1010
1011 double GPS::getScratchMagBearing() const
1012 {
1013     if (!_scratchValid) {
1014         return 0.0;
1015     }
1016     
1017     double crs = getScratchTrueBearing() - _magvar_node->getDoubleValue();
1018     SG_NORMALIZE_RANGE(crs, 0.0, 360.0);
1019     return crs;
1020 }
1021
1022 #endif
1023
1024 /////////////////////////////////////////////////////////////////////////////
1025 // scratch system
1026
1027 void GPS::setCommand(const char* aCmd)
1028 {
1029   SG_LOG(SG_INSTR, SG_DEBUG, "GPS command:" << aCmd);
1030   
1031   if (!strcmp(aCmd, "direct")) {
1032     directTo();
1033   } else if (!strcmp(aCmd, "obs")) {
1034     selectOBSMode(NULL);
1035   } else if (!strcmp(aCmd, "leg")) {
1036     selectLegMode();
1037 #if FG_210_COMPAT
1038   } else if (!strcmp(aCmd, "load-route-wpt")) {
1039       loadRouteWaypoint();
1040   } else if (!strcmp(aCmd, "nearest")) {
1041       loadNearest();
1042   } else if (!strcmp(aCmd, "search")) {
1043       _searchNames = false;
1044       search();
1045   } else if (!strcmp(aCmd, "search-names")) {
1046       _searchNames = true;
1047       search();
1048   } else if (!strcmp(aCmd, "next")) {
1049       nextResult();
1050   } else if (!strcmp(aCmd, "previous")) {
1051       previousResult();
1052   } else if (!strcmp(aCmd, "define-user-wpt")) {
1053       defineWaypoint();
1054   } else if (!strcmp(aCmd, "route-insert-before")) {
1055       int index = _scratchNode->getIntValue("index");
1056       if (index < 0 || (_route->numLegs() == 0)) {
1057           index = _route->numLegs();
1058       } else if (index >= _route->numLegs()) {
1059           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-before, bad index:" << index);
1060           return;
1061       }
1062       
1063       insertWaypointAtIndex(index);
1064   } else if (!strcmp(aCmd, "route-insert-after")) {
1065       int index = _scratchNode->getIntValue("index");
1066       if (index < 0 || (_route->numLegs() == 0)) {
1067           index = _route->numLegs();
1068       } else if (index >= _route->numLegs()) {
1069           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-insert-after, bad index:" << index);
1070           return;
1071       } else {
1072           ++index;
1073       }
1074       
1075       insertWaypointAtIndex(index);
1076   } else if (!strcmp(aCmd, "route-delete")) {
1077       int index = _scratchNode->getIntValue("index");
1078       if (index < 0) {
1079           index = _route->numLegs();
1080       } else if (index >= _route->numLegs()) {
1081           SG_LOG(SG_INSTR, SG_WARN, "GPS:route-delete, bad index:" << index);
1082           return;
1083       }
1084       
1085       removeWaypointAtIndex(index);
1086 #endif
1087   } else {
1088     SG_LOG(SG_INSTR, SG_WARN, "GPS:unrecognized command:" << aCmd);
1089   }
1090 }
1091
1092 void GPS::clearScratch()
1093 {
1094   _scratchPos = SGGeod::fromDegFt(-9999.0, -9999.0, -9999.0);
1095   _scratchNode->setBoolValue("valid", false);
1096 #if FG_210_COMPAT
1097     _scratchNode->setStringValue("type", "");
1098     _scratchNode->setStringValue("query", "");
1099 #endif
1100 }
1101
1102 bool GPS::isScratchPositionValid() const
1103 {
1104   if ((_scratchPos.getLongitudeDeg() < -9990.0) ||
1105       (_scratchPos.getLatitudeDeg() < -9990.0)) {
1106    return false;   
1107   }
1108   
1109   return true;
1110 }
1111
1112 void GPS::directTo()
1113 {  
1114   if (!isScratchPositionValid()) {
1115     return;
1116   }
1117   
1118   _prevWaypt = NULL;
1119   _wp0_position = _indicated_pos;
1120   _currentWaypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1121   _mode = "dto";
1122
1123   clearScratch();
1124   wp1Changed();
1125 }
1126
1127 void GPS::selectOBSMode(flightgear::Waypt* waypt)
1128 {
1129   if (!waypt) {
1130     // initialise from scratch
1131     if (!isScratchPositionValid()) {
1132       return;
1133     }
1134     
1135     waypt = new BasicWaypt(_scratchPos, _scratchNode->getStringValue("ident"), NULL);
1136   }
1137   
1138   _mode = "obs";
1139   _currentWaypt = waypt;
1140   _wp0_position = _indicated_pos;
1141   wp1Changed();
1142 }
1143
1144 void GPS::selectLegMode()
1145 {
1146   if (_mode == "leg") {
1147     return;
1148   }
1149   
1150   if (!_route) {
1151     SG_LOG(SG_INSTR, SG_WARN, "GPS:selectLegMode: no active route");
1152     return;
1153   }
1154
1155   _mode = "leg";  
1156   // depending on the situation, this will either get over-written 
1157   // in routeManagerSequenced or not; either way it does no harm to
1158   // set it here.
1159   _wp0_position = _indicated_pos;
1160
1161   // not really sequenced, but does all the work of updating wp0/1
1162   currentWaypointChanged();
1163 }
1164
1165 #if FG_210_COMPAT
1166
1167 void GPS::loadRouteWaypoint()
1168 {
1169     _scratchValid = false;    
1170     int index = _scratchNode->getIntValue("index", -9999);
1171     clearScratch();
1172     
1173     if ((index < 0) || (index >= _route->numLegs())) { // no index supplied, use current wp
1174         index = _route->currentIndex();
1175     }
1176     
1177     _searchIsRoute = true;
1178     setScratchFromRouteWaypoint(index);
1179 }
1180
1181 void GPS::setScratchFromRouteWaypoint(int aIndex)
1182 {
1183     assert(_searchIsRoute);
1184     if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1185         SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromRouteWaypoint: route-index out of bounds");
1186         return;
1187     }
1188     
1189     _searchResultIndex = aIndex;
1190     WayptRef wp = _route->legAtIndex(aIndex)->waypoint();
1191     _scratchNode->setStringValue("ident", wp->ident());
1192     _scratchPos = wp->position();
1193     _scratchValid = true;
1194     _scratchNode->setIntValue("index", aIndex);
1195 }
1196
1197 void GPS::loadNearest()
1198 {
1199     string sty(_scratchNode->getStringValue("type"));
1200     FGPositioned::Type ty = FGPositioned::typeFromName(sty);
1201     if (ty == FGPositioned::INVALID) {
1202         SG_LOG(SG_INSTR, SG_WARN, "GPS:loadNearest: request type is invalid:" << sty);
1203         return;
1204     }
1205     
1206     auto_ptr<FGPositioned::Filter> f(createFilter(ty));
1207     int limitCount = _scratchNode->getIntValue("max-results", 1);
1208     double cutoffDistance = _scratchNode->getDoubleValue("cutoff-nm", 400.0);
1209     
1210     SGGeod searchPos = _indicated_pos;
1211     if (isScratchPositionValid()) {
1212         searchPos = _scratchPos;
1213     }
1214     
1215     clearScratch(); // clear now, regardless of whether we find a match or not
1216     
1217     _searchResults =
1218     FGPositioned::findClosestN(searchPos, limitCount, cutoffDistance, f.get());
1219     _searchResultIndex = 0;
1220     _searchIsRoute = false;
1221     
1222     if (_searchResults.empty()) {
1223         return;
1224     }
1225     
1226     setScratchFromCachedSearchResult();
1227 }
1228
1229 bool GPS::SearchFilter::pass(FGPositioned* aPos) const
1230 {
1231     switch (aPos->type()) {
1232         case FGPositioned::AIRPORT:
1233             // heliport and seaport too?
1234         case FGPositioned::VOR:
1235         case FGPositioned::NDB:
1236         case FGPositioned::FIX:
1237         case FGPositioned::TACAN:
1238         case FGPositioned::WAYPOINT:
1239             return true;
1240         default:
1241             return false;
1242     }
1243 }
1244
1245 FGPositioned::Type GPS::SearchFilter::minType() const
1246 {
1247     return FGPositioned::AIRPORT;
1248 }
1249
1250 FGPositioned::Type GPS::SearchFilter::maxType() const
1251 {
1252     return FGPositioned::VOR;
1253 }
1254
1255 FGPositioned::Filter* GPS::createFilter(FGPositioned::Type aTy)
1256 {
1257     if (aTy == FGPositioned::AIRPORT) {
1258         return new FGAirport::HardSurfaceFilter();
1259     }
1260     
1261     // if we were passed INVALID, assume it means 'all types interesting to a GPS'
1262     if (aTy == FGPositioned::INVALID) {
1263         return new SearchFilter;
1264     }
1265     
1266     return new FGPositioned::TypeFilter(aTy);
1267 }
1268
1269 void GPS::search()
1270 {
1271     // parse search terms into local members, and exec the first search
1272     string sty(_scratchNode->getStringValue("type"));
1273     _searchType = FGPositioned::typeFromName(sty);
1274     _searchQuery = _scratchNode->getStringValue("query");
1275     if (_searchQuery.empty()) {
1276         SG_LOG(SG_INSTR, SG_WARN, "empty GPS search query");
1277         clearScratch();
1278         return;
1279     }
1280     
1281     _searchExact = _scratchNode->getBoolValue("exact", true);
1282     _searchResultIndex = 0;
1283     _searchIsRoute = false;
1284     
1285     auto_ptr<FGPositioned::Filter> f(createFilter(_searchType));
1286     if (_searchNames) {
1287         _searchResults = FGPositioned::findAllWithName(_searchQuery, f.get(), _searchExact);
1288     } else {
1289         _searchResults = FGPositioned::findAllWithIdent(_searchQuery, f.get(), _searchExact);
1290     }
1291     
1292     bool orderByRange = _scratchNode->getBoolValue("order-by-distance", true);
1293     if (orderByRange) {
1294         FGPositioned::sortByRange(_searchResults, _indicated_pos);
1295     }
1296     
1297     if (_searchResults.empty()) {
1298         clearScratch();
1299         return;
1300     }
1301     
1302     setScratchFromCachedSearchResult();
1303 }
1304
1305 bool GPS::getScratchHasNext() const
1306 {
1307     int lastResult;
1308     if (_searchIsRoute) {
1309         lastResult = _route->numLegs() - 1;
1310     } else {
1311         lastResult = (int) _searchResults.size() - 1;
1312     }
1313     
1314     if (lastResult < 0) { // search array might be empty
1315         return false;
1316     }
1317     
1318     return (_searchResultIndex < lastResult);
1319 }
1320
1321 void GPS::setScratchFromCachedSearchResult()
1322 {
1323     int index = _searchResultIndex;
1324     
1325     if ((index < 0) || (index >= (int) _searchResults.size())) {
1326         SG_LOG(SG_INSTR, SG_WARN, "GPS:setScratchFromCachedSearchResult: index out of bounds:" << index);
1327         return;
1328     }
1329     
1330     setScratchFromPositioned(_searchResults[index], index);
1331 }
1332
1333 void GPS::setScratchFromPositioned(FGPositioned* aPos, int aIndex)
1334 {
1335     clearScratch();
1336     assert(aPos);
1337     
1338     _scratchPos = aPos->geod();
1339     _scratchNode->setStringValue("name", aPos->name());
1340     _scratchNode->setStringValue("ident", aPos->ident());
1341     _scratchNode->setStringValue("type", FGPositioned::nameForType(aPos->type()));
1342     
1343     if (aIndex >= 0) {
1344         _scratchNode->setIntValue("index", aIndex);
1345     }
1346     
1347     _scratchValid = true;
1348     _scratchNode->setIntValue("result-count", _searchResults.size());
1349     
1350     switch (aPos->type()) {
1351         case FGPositioned::VOR:
1352             _scratchNode->setDoubleValue("frequency-mhz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1353             break;
1354             
1355         case FGPositioned::NDB:
1356             _scratchNode->setDoubleValue("frequency-khz", static_cast<FGNavRecord*>(aPos)->get_freq() / 100.0);
1357             break;
1358             
1359         case FGPositioned::AIRPORT:
1360             addAirportToScratch((FGAirport*)aPos);
1361             break;
1362             
1363         default:
1364             // no-op
1365             break;
1366     }
1367     
1368     // look for being on the route and set?
1369 }
1370
1371 void GPS::addAirportToScratch(FGAirport* aAirport)
1372 {
1373     for (unsigned int r=0; r<aAirport->numRunways(); ++r) {
1374         SGPropertyNode* rwyNd = _scratchNode->getChild("runways", r, true);
1375         FGRunway* rwy = aAirport->getRunwayByIndex(r);
1376         // TODO - filter out unsuitable runways in the future
1377         // based on config again
1378         
1379         rwyNd->setStringValue("id", rwy->ident().c_str());
1380         rwyNd->setIntValue("length-ft", rwy->lengthFt());
1381         rwyNd->setIntValue("width-ft", rwy->widthFt());
1382         rwyNd->setIntValue("heading-deg", rwy->headingDeg());
1383         // map surface code to a string
1384         // TODO - lighting information
1385         
1386         if (rwy->ILS()) {
1387             rwyNd->setDoubleValue("ils-frequency-mhz", rwy->ILS()->get_freq() / 100.0);
1388         }
1389     } // of runways iteration
1390 }
1391
1392 void GPS::nextResult()
1393 {
1394     if (!getScratchHasNext()) {
1395         return;
1396     }
1397     
1398     clearScratch();
1399     if (_searchIsRoute) {
1400         setScratchFromRouteWaypoint(++_searchResultIndex);
1401     } else {
1402         ++_searchResultIndex;
1403         setScratchFromCachedSearchResult();
1404     }
1405 }
1406
1407 void GPS::previousResult()
1408 {
1409     if (_searchResultIndex <= 0) {
1410         return;
1411     }
1412     
1413     clearScratch();
1414     --_searchResultIndex;
1415     
1416     if (_searchIsRoute) {
1417         setScratchFromRouteWaypoint(_searchResultIndex);
1418     } else {
1419         setScratchFromCachedSearchResult();
1420     }
1421 }
1422
1423 void GPS::defineWaypoint()
1424 {
1425     if (!isScratchPositionValid()) {
1426         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: invalid lat/lon");
1427         return;
1428     }
1429     
1430     string ident = _scratchNode->getStringValue("ident");
1431     if (ident.size() < 2) {
1432         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: waypoint identifier must be at least two characters");
1433         return;
1434     }
1435     
1436     // check for duplicate idents
1437     FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1438     FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1439     if (!dups.empty()) {
1440         SG_LOG(SG_INSTR, SG_WARN, "GPS:defineWaypoint: non-unique waypoint identifier, ho-hum");
1441     }
1442     
1443     SG_LOG(SG_INSTR, SG_INFO, "GPS:defineWaypoint: creating waypoint:" << ident);
1444     FGPositionedRef wpt = FGPositioned::createUserWaypoint(ident, _scratchPos);
1445     _searchResults.clear();
1446     _searchResults.push_back(wpt);
1447     setScratchFromPositioned(wpt.get(), -1);
1448 }
1449
1450 void GPS::insertWaypointAtIndex(int aIndex)
1451 {
1452     // note we do allow index = routeMgr->size(), that's an append
1453     if ((aIndex < 0) || (aIndex > _route->numLegs())) {
1454         throw sg_range_exception("GPS::insertWaypointAtIndex: index out of bounds");
1455     }
1456     
1457     if (!isScratchPositionValid()) {
1458         SG_LOG(SG_INSTR, SG_WARN, "GPS:insertWaypointAtIndex: invalid lat/lon");
1459         return;
1460     }
1461     
1462     string ident = _scratchNode->getStringValue("ident");
1463     
1464     WayptRef wpt = new BasicWaypt(_scratchPos, ident, NULL);
1465     _route->insertWayptAtIndex(wpt, aIndex);
1466 }
1467
1468 void GPS::removeWaypointAtIndex(int aIndex)
1469 {
1470     if ((aIndex < 0) || (aIndex >= _route->numLegs())) {
1471         throw sg_range_exception("GPS::removeWaypointAtIndex: index out of bounds");
1472     }
1473     
1474     _route->deleteIndex(aIndex);
1475 }
1476
1477
1478 #endif // of FG_210_COMPAT
1479
1480 void GPS::tieSGGeod(SGPropertyNode* aNode, SGGeod& aRef, 
1481   const char* lonStr, const char* latStr, const char* altStr)
1482 {
1483   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, &SGGeod::setLongitudeDeg));
1484   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, &SGGeod::setLatitudeDeg));
1485   
1486   if (altStr) {
1487     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, &SGGeod::setElevationFt));
1488   }
1489 }
1490
1491 void GPS::tieSGGeodReadOnly(SGPropertyNode* aNode, SGGeod& aRef, 
1492   const char* lonStr, const char* latStr, const char* altStr)
1493 {
1494   tie(aNode, lonStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLongitudeDeg, NULL));
1495   tie(aNode, latStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getLatitudeDeg, NULL));
1496   
1497   if (altStr) {
1498     tie(aNode, altStr, SGRawValueMethods<SGGeod, double>(aRef, &SGGeod::getElevationFt, NULL));
1499   }
1500 }
1501
1502 // end of gps.cxx