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