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