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