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