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