]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/dclgps.cxx
Merge branch 'maint' into next
[flightgear.git] / src / Instrumentation / dclgps.cxx
1 // dclgps.cxx - a class to extend the operation of FG's current GPS
2 // code, and provide support for a KLN89-specific instrument.  It
3 // is envisioned that eventually this file and class will be split
4 // up between current FG code and new KLN89-specific code and removed.
5 //
6 // Written by David Luff, started 2005.
7 //
8 // Copyright (C) 2005 - David C Luff:  daveluff --AT-- ntlworld --D0T-- com
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #include "dclgps.hxx"
27
28 #include <simgear/sg_inlines.h>
29 #include <simgear/structure/commands.hxx>
30 #include <simgear/timing/sg_time.hxx>
31 #include <simgear/magvar/magvar.hxx>
32
33 #include <Main/fg_props.hxx>
34 #include <Navaids/fix.hxx>
35 #include <Navaids/navrecord.hxx>
36 #include <Airports/simple.hxx>
37
38 #include <iostream>
39
40 using namespace std;
41
42 // Command callbacks for FlightGear
43
44 static bool do_kln89_msg_pressed(const SGPropertyNode* arg) {
45         //cout << "do_kln89_msg_pressed called!\n";
46         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
47         gps->MsgPressed();
48         return(true);
49 }
50
51 static bool do_kln89_obs_pressed(const SGPropertyNode* arg) {
52         //cout << "do_kln89_obs_pressed called!\n";
53         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
54         gps->OBSPressed();
55         return(true);
56 }
57
58 static bool do_kln89_alt_pressed(const SGPropertyNode* arg) {
59         //cout << "do_kln89_alt_pressed called!\n";
60         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
61         gps->AltPressed();
62         return(true);
63 }
64
65 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
66         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
67         gps->NrstPressed();
68         return(true);
69 }
70
71 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
72         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
73         gps->DtoPressed();
74         return(true);
75 }
76
77 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
78         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
79         gps->ClrPressed();
80         return(true);
81 }
82
83 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
84         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
85         gps->EntPressed();
86         return(true);
87 }
88
89 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
90         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
91         gps->CrsrPressed();
92         return(true);
93 }
94
95 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
96         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
97         gps->Knob1Left1();
98         return(true);
99 }
100
101 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
102         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
103         gps->Knob1Right1();
104         return(true);
105 }
106
107 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
108         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
109         gps->Knob2Left1();
110         return(true);
111 }
112
113 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
114         DCLGPS* gps = (DCLGPS*)globals->get_subsystem("kln89");
115         gps->Knob2Right1();
116         return(true);
117 }
118
119 // End command callbacks
120
121 GPSWaypoint::GPSWaypoint() {
122     appType = GPS_APP_NONE;
123 }
124
125 GPSWaypoint::GPSWaypoint(const std::string& aIdent, float aLat, float aLon, GPSWpType aType) :
126   id(aIdent),
127   lat(aLat),
128   lon(aLon),
129   type(aType),
130   appType(GPS_APP_NONE)
131 {
132 }
133
134 GPSWaypoint::~GPSWaypoint() {}
135
136 string GPSWaypoint::GetAprId() {
137         if(appType == GPS_IAF) return(id + 'i');
138         else if(appType == GPS_FAF) return(id + 'f');
139         else if(appType == GPS_MAP) return(id + 'm');
140         else if(appType == GPS_MAHP) return(id + 'h');
141         else return(id);
142 }
143
144 static GPSWpType
145 GPSWpTypeFromFGPosType(FGPositioned::Type aType)
146 {
147   switch (aType) {
148   case FGPositioned::AIRPORT:
149   case FGPositioned::SEAPORT:
150   case FGPositioned::HELIPORT:
151     return GPS_WP_APT;
152   
153   case FGPositioned::VOR:
154     return GPS_WP_VOR;
155   
156   case FGPositioned::NDB:
157     return GPS_WP_NDB;
158   
159   case FGPositioned::WAYPOINT:
160     return GPS_WP_USR;
161   
162   case FGPositioned::FIX:
163     return GPS_WP_INT;
164   
165   default:
166     return GPS_WP_USR;
167   }
168 }
169
170 GPSWaypoint* GPSWaypoint::createFromPositioned(const FGPositioned* aPos)
171 {
172   if (!aPos) {
173     return NULL; // happens if find returns no match
174   }
175   
176   return new GPSWaypoint(aPos->ident(), 
177     aPos->latitude() * SG_DEGREES_TO_RADIANS,
178     aPos->longitude() * SG_DEGREES_TO_RADIANS,
179     GPSWpTypeFromFGPosType(aPos->type())
180   );
181 }
182
183 ostream& operator << (ostream& os, GPSAppWpType type) {
184         switch(type) {
185                 case(GPS_IAF):       return(os << "IAF");
186                 case(GPS_IAP):       return(os << "IAP");
187                 case(GPS_FAF):       return(os << "FAF");
188                 case(GPS_MAP):       return(os << "MAP");
189                 case(GPS_MAHP):      return(os << "MAHP");
190                 case(GPS_HDR):       return(os << "HEADER");
191                 case(GPS_FENCE):     return(os << "FENCE");
192                 case(GPS_APP_NONE):  return(os << "NONE");
193         }
194         return(os << "ERROR - Unknown switch in GPSAppWpType operator << ");
195 }
196
197 FGIAP::FGIAP() {
198 }
199
200 FGIAP::~FGIAP() {
201 }
202
203 FGNPIAP::FGNPIAP() {
204 }
205
206 FGNPIAP::~FGNPIAP() {
207 }
208
209 ClockTime::ClockTime() {
210     _hr = 0;
211     _min = 0;
212 }
213
214 ClockTime::ClockTime(int hr, int min) {
215     while(hr < 0) { hr += 24; }
216     _hr = hr % 24;
217     while(min < 0) { min += 60; }
218     while(min > 60) { min -= 60; }
219         _min = min;
220 }
221
222 ClockTime::~ClockTime() {
223 }
224
225 GPSPage::GPSPage(DCLGPS* parent) {
226         _parent = parent;
227         _subPage = 0;
228 }
229
230 GPSPage::~GPSPage() {
231 }
232
233 void GPSPage::Update(double dt) {}
234
235 void GPSPage::Knob1Left1() {}
236 void GPSPage::Knob1Right1() {}
237
238 void GPSPage::Knob2Left1() {
239         _parent->_activePage->LooseFocus();
240         _subPage--;
241         if(_subPage < 0) _subPage = _nSubPages - 1;
242 }
243
244 void GPSPage::Knob2Right1() {
245         _parent->_activePage->LooseFocus();
246         _subPage++;
247         if(_subPage >= _nSubPages) _subPage = 0;
248 }
249
250 void GPSPage::CrsrPressed() {}
251 void GPSPage::EntPressed() {}
252 void GPSPage::ClrPressed() {}
253 void GPSPage::DtoPressed() {}
254 void GPSPage::NrstPressed() {}
255 void GPSPage::AltPressed() {}
256 void GPSPage::OBSPressed() {}
257 void GPSPage::MsgPressed() {}
258
259 string GPSPage::GPSitoa(int n) {
260         char buf[4];
261         // TODO - sanity check n!
262         sprintf(buf, "%i", n);
263         string s = buf;
264         return(s);
265 }
266
267 void GPSPage::CleanUp() {}
268 void GPSPage::LooseFocus() {}
269 void GPSPage::SetId(const string& s) {}
270
271 // ------------------------------------------------------------------------------------- //
272
273 DCLGPS::DCLGPS(RenderArea2D* instrument) {
274         _instrument = instrument;
275         _nFields = 1;
276         _maxFields = 2;
277         _pages.clear();
278         
279         // Units - lets default to US units - FG can set them to other units from config during startup if desired.
280         _altUnits = GPS_ALT_UNITS_FT;
281         _baroUnits = GPS_PRES_UNITS_IN;
282         _velUnits = GPS_VEL_UNITS_KT;
283         _distUnits = GPS_DIST_UNITS_NM;
284
285         _lon_node = fgGetNode("/instrumentation/gps/indicated-longitude-deg", true);
286         _lat_node = fgGetNode("/instrumentation/gps/indicated-latitude-deg", true);
287         _alt_node = fgGetNode("/instrumentation/gps/indicated-altitude-ft", true);
288         _grnd_speed_node = fgGetNode("/instrumentation/gps/indicated-ground-speed-kt", true);
289         _true_track_node = fgGetNode("/instrumentation/gps/indicated-track-true-deg", true);
290         _mag_track_node = fgGetNode("/instrumentation/gps/indicated-track-magnetic-deg", true);
291         
292         // Use FG's position values at construction in case FG's gps has not run first update yet.
293         _lon = fgGetDouble("/position/longitude-deg") * SG_DEGREES_TO_RADIANS;
294         _lat = fgGetDouble("/position/latitude-deg") * SG_DEGREES_TO_RADIANS;
295         _alt = fgGetDouble("/position/altitude-ft");
296         // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
297         // gps code and not our own.
298         _gpsLon = _lon;
299         _gpsLat = _lat;
300         _checkLon = _gpsLon;
301         _checkLat = _gpsLat;
302         _groundSpeed_ms = 0.0;
303         _groundSpeed_kts = 0.0;
304         _track = 0.0;
305         _magTrackDeg = 0.0;
306         
307         // Sensible defaults.  These can be overriden by derived classes if desired.
308         _cdiScales.clear();
309         _cdiScales.push_back(5.0);
310         _cdiScales.push_back(1.0);
311         _cdiScales.push_back(0.3);
312         _currentCdiScaleIndex = 0;
313         _targetCdiScaleIndex = 0;
314         _sourceCdiScaleIndex = 0;
315         _cdiScaleTransition = false;
316         _currentCdiScale = 5.0;
317         
318         _cleanUpPage = -1;
319         
320         _activeWaypoint.id.clear();
321         _dist2Act = 0.0;
322         _crosstrackDist = 0.0;
323         _headingBugTo = true;
324         _navFlagged = true;
325         _waypointAlert = false;
326         _departed = false;
327         _departureTimeString = "----";
328         _elapsedTime = 0.0;
329         _powerOnTime.set_hr(0);
330         _powerOnTime.set_min(0);
331         _powerOnTimerSet = false;
332         _alarmSet = false;
333         
334         // Configuration Initialisation
335         // Should this be in kln89.cxx ?
336         _turnAnticipationEnabled = false;
337         _suaAlertEnabled = false;
338         _altAlertEnabled = false;
339         
340         _time = new SGTime;
341         
342         _messageStack.clear();
343         
344         _dto = false;
345         
346         _approachLoaded = false;
347         _approachArm = false;
348         _approachReallyArmed = false;
349         _approachActive = false;
350         _approachFP = new GPSFlightPlan;
351 }
352
353 DCLGPS::~DCLGPS() {
354         delete _time;
355   delete _approachFP;           // Don't need to delete the waypoints inside since they point to
356                                                         // the waypoints in the approach database.
357         // TODO - may need to delete the approach database!!
358 }
359
360 void DCLGPS::draw() {
361         //cout << "draw called!\n";
362         _instrument->draw();
363 }
364
365 void DCLGPS::init() {
366         globals->get_commands()->addCommand("kln89_msg_pressed", do_kln89_msg_pressed);
367         globals->get_commands()->addCommand("kln89_obs_pressed", do_kln89_obs_pressed);
368         globals->get_commands()->addCommand("kln89_alt_pressed", do_kln89_alt_pressed);
369         globals->get_commands()->addCommand("kln89_nrst_pressed", do_kln89_nrst_pressed);
370         globals->get_commands()->addCommand("kln89_dto_pressed", do_kln89_dto_pressed);
371         globals->get_commands()->addCommand("kln89_clr_pressed", do_kln89_clr_pressed);
372         globals->get_commands()->addCommand("kln89_ent_pressed", do_kln89_ent_pressed);
373         globals->get_commands()->addCommand("kln89_crsr_pressed", do_kln89_crsr_pressed);
374         globals->get_commands()->addCommand("kln89_knob1left1", do_kln89_knob1left1);
375         globals->get_commands()->addCommand("kln89_knob1right1", do_kln89_knob1right1);
376         globals->get_commands()->addCommand("kln89_knob2left1", do_kln89_knob2left1);
377         globals->get_commands()->addCommand("kln89_knob2right1", do_kln89_knob2right1);
378                 
379         // Not sure if this should be here, but OK for now.
380         CreateDefaultFlightPlans();
381 }
382
383 void DCLGPS::bind() {
384         fgTie("/instrumentation/gps/waypoint-alert", this, &DCLGPS::GetWaypointAlert);
385         fgTie("/instrumentation/gps/leg-mode", this, &DCLGPS::GetLegMode);
386         fgTie("/instrumentation/gps/obs-mode", this, &DCLGPS::GetOBSMode);
387         fgTie("/instrumentation/gps/approach-arm", this, &DCLGPS::GetApproachArm);
388         fgTie("/instrumentation/gps/approach-active", this, &DCLGPS::GetApproachActive);
389         fgTie("/instrumentation/gps/cdi-deflection", this, &DCLGPS::GetCDIDeflection);
390         fgTie("/instrumentation/gps/to-flag", this, &DCLGPS::GetToFlag);
391 }
392
393 void DCLGPS::unbind() {
394         fgUntie("/instrumentation/gps/waypoint-alert");
395         fgUntie("/instrumentation/gps/leg-mode");
396         fgUntie("/instrumentation/gps/obs-mode");
397         fgUntie("/instrumentation/gps/approach-arm");
398         fgUntie("/instrumentation/gps/approach-active");
399         fgUntie("/instrumentation/gps/cdi-deflection");
400 }
401
402 void DCLGPS::update(double dt) {
403         //cout << "update called!\n";
404         
405         _lon = _lon_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
406         _lat = _lat_node->getDoubleValue() * SG_DEGREES_TO_RADIANS;
407         _alt = _alt_node->getDoubleValue();
408         _groundSpeed_kts = _grnd_speed_node->getDoubleValue();
409         _groundSpeed_ms = _groundSpeed_kts * 0.5144444444;
410         _track = _true_track_node->getDoubleValue();
411         _magTrackDeg = _mag_track_node->getDoubleValue();
412         // Note - we can depriciate _gpsLat and _gpsLon if we implement error handling in FG
413         // gps code and not our own.
414         _gpsLon = _lon;
415         _gpsLat = _lat;
416         // Check for abnormal position slew
417         if(GetGreatCircleDistance(_gpsLat, _gpsLon, _checkLat, _checkLon) > 1.0) {
418                 OrientateToActiveFlightPlan();
419         }
420         _checkLon = _gpsLon;
421         _checkLat = _gpsLat;
422         
423         // TODO - check for unit power before running this.
424         if(!_powerOnTimerSet) {
425                 SetPowerOnTimer();
426         } 
427         
428         // Check if an alarm timer has expired
429         if(_alarmSet) {
430                 if(_alarmTime.hr() == atoi(fgGetString("/instrumentation/clock/indicated-hour"))
431                 && _alarmTime.min() == atoi(fgGetString("/instrumentation/clock/indicated-min"))) {
432                         _messageStack.push_back("*Timer Expired");
433                         _alarmSet = false;
434                 }
435         }
436         
437         if(!_departed) {
438                 if(_groundSpeed_kts > 30.0) {
439                         _departed = true;
440                         string th = fgGetString("/instrumentation/clock/indicated-hour");
441                         string tm = fgGetString("/instrumentation/clock/indicated-min");
442                         if(th.size() == 1) th = "0" + th;
443                         if(tm.size() == 1) tm = "0" + tm;
444                         _departureTimeString = th + tm;
445                 }
446         } else {
447                 // TODO - check - is this prone to drift error over time?
448                 // Should we difference the departure and current times?
449                 // What about when the user resets the time of day from the menu?
450                 _elapsedTime += dt;
451         }
452
453         _time->update(_gpsLon * SG_DEGREES_TO_RADIANS, _gpsLat * SG_DEGREES_TO_RADIANS, 0, 0);
454         // FIXME - currently all the below assumes leg mode and no DTO or OBS cancelled.
455         if(_activeFP->IsEmpty()) {
456                 // Not sure if we need to reset these each update or only when fp altered
457                 _activeWaypoint.id.clear();
458                 _navFlagged = true;
459         } else if(_activeFP->waypoints.size() == 1) {
460                 _activeWaypoint.id.clear();
461         } else {
462                 _navFlagged = false;
463                 if(_activeWaypoint.id.empty() || _fromWaypoint.id.empty()) {
464                         //cout << "Error, in leg mode with flightplan of 2 or more waypoints, but either active or from wp is NULL!\n";
465                         OrientateToActiveFlightPlan();
466                 }
467                 
468                 // Approach stuff
469                 if(_approachLoaded) {
470                         if(!_approachReallyArmed && !_approachActive) {
471                                 // arm if within 30nm of airport.
472                                 // TODO - let user cancel approach arm using external GPS-APR switch
473                                 bool multi;
474                                 const FGAirport* ap = FindFirstAptById(_approachID, multi, true);
475                                 if(ap != NULL) {
476                                         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, ap->getLatitude() * SG_DEGREES_TO_RADIANS, ap->getLongitude() * SG_DEGREES_TO_RADIANS);
477                                         if(d <= 30) {
478                                                 _approachArm = true;
479                                                 _approachReallyArmed = true;
480                                                 _messageStack.push_back("*Press ALT To Set Baro");
481                                                 // Not sure what we do if the user has already set CDI to 0.3 nm?
482                                                 _targetCdiScaleIndex = 1;
483                                                 if(_currentCdiScaleIndex == 1) {
484                                                         // No problem!
485                                                 } else if(_currentCdiScaleIndex == 0) {
486                                                         _sourceCdiScaleIndex = 0;
487                                                         _cdiScaleTransition = true;
488                                                         _cdiTransitionTime = 30.0;
489                                                         _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
490                                                 }
491                                         }
492                                 }
493                         } else {
494                                 // Check for approach active - we can only activate approach if it is really armed.
495                                 if(_activeWaypoint.appType == GPS_FAF) {
496                                         //cout << "Active waypoint is FAF, id is " << _activeWaypoint.id << '\n';
497                                         if(GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) <= 2.0 && !_obsMode) {
498                                                 // Assume heading is OK for now
499                                                 _approachArm = false;   // TODO - check - maybe arm is left on when actv comes on?
500                                                 _approachReallyArmed = false;
501                                                 _approachActive = true;
502                                                 _targetCdiScaleIndex = 2;
503                                                 if(_currentCdiScaleIndex == 2) {
504                                                         // No problem!
505                                                 } else if(_currentCdiScaleIndex == 1) {
506                                                         _sourceCdiScaleIndex = 1;
507                                                         _cdiScaleTransition = true;
508                                                         _cdiTransitionTime = 30.0;      // TODO - compress it if time to FAF < 30sec
509                                                         _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
510                                                 } else {
511                                                         // Abort going active?
512                                                         _approachActive = false;
513                                                 }
514                                         }
515                                 }
516                         }
517                 }
518                 
519                 // CDI scale transition stuff
520                 if(_cdiScaleTransition) {
521                         if(fabs(_currentCdiScale - _cdiScales[_targetCdiScaleIndex]) < 0.001) {
522                                 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
523                                 _currentCdiScaleIndex = _targetCdiScaleIndex;
524                                 _cdiScaleTransition = false;
525                         } else {
526                                 double scaleDiff = (_targetCdiScaleIndex > _sourceCdiScaleIndex 
527                                                     ? _cdiScales[_sourceCdiScaleIndex] - _cdiScales[_targetCdiScaleIndex]
528                                                                         : _cdiScales[_targetCdiScaleIndex] - _cdiScales[_sourceCdiScaleIndex]);
529                                 //cout << "ScaleDiff = " << scaleDiff << '\n';
530                                 if(_targetCdiScaleIndex > _sourceCdiScaleIndex) {
531                                         // Scaling down eg. 5nm -> 1nm
532                                         _currentCdiScale -= (scaleDiff * dt / _cdiTransitionTime);
533                                         if(_currentCdiScale < _cdiScales[_targetCdiScaleIndex]) {
534                                                 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
535                                                 _currentCdiScaleIndex = _targetCdiScaleIndex;
536                                                 _cdiScaleTransition = false;
537                                         }
538                                 } else {
539                                         _currentCdiScale += (scaleDiff * dt / _cdiTransitionTime);
540                                         if(_currentCdiScale > _cdiScales[_targetCdiScaleIndex]) {
541                                                 _currentCdiScale = _cdiScales[_targetCdiScaleIndex];
542                                                 _currentCdiScaleIndex = _targetCdiScaleIndex;
543                                                 _cdiScaleTransition = false;
544                                         }
545                                 }
546                                 //cout << "_currentCdiScale = " << _currentCdiScale << '\n';
547                         }
548                 } else {
549                         _currentCdiScale = _cdiScales[_currentCdiScaleIndex];
550                 }
551                 
552                 
553                 // Urgh - I've been setting the heading bug based on DTK,
554                 // bug I think it should be based on heading re. active waypoint
555                 // based on what the sim does after the final waypoint is passed.
556                 // (DTK remains the same, but if track is held == DTK heading bug
557                 // reverses to from once wp is passed).
558                 /*
559                 if(_fromWaypoint != NULL) {
560                         // TODO - how do we handle the change of track with distance over long legs?
561                         _dtkTrue = GetGreatCircleCourse(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon) * SG_RADIANS_TO_DEGREES;
562                         _dtkMag = GetMagHeadingFromTo(_fromWaypoint->lat, _fromWaypoint->lon, _activeWaypoint->lat, _activeWaypoint->lon);
563                         // Don't change the heading bug if speed is too low otherwise it flickers to/from at rest
564                         if(_groundSpeed_ms > 5) {
565                                 //cout << "track = " << _track << ", dtk = " << _dtkTrue << '\n'; 
566                                 double courseDev = _track - _dtkTrue;
567                                 //cout << "courseDev = " << courseDev << ", normalized = ";
568                                 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
569                                 //cout << courseDev << '\n';
570                                 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
571                         }
572                 } else {
573                         _dtkTrue = 0.0;
574                         _dtkMag = 0.0;
575                         // TODO - in DTO operation the position of initiation of DTO defines the "from waypoint".
576                 }
577                 */
578                 if(!_activeWaypoint.id.empty()) {
579                         double hdgTrue = GetGreatCircleCourse(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
580                         if(_groundSpeed_ms > 5) {
581                                 //cout << "track = " << _track << ", hdgTrue = " << hdgTrue << '\n'; 
582                                 double courseDev = _track - hdgTrue;
583                                 //cout << "courseDev = " << courseDev << ", normalized = ";
584                                 SG_NORMALIZE_RANGE(courseDev, -180.0, 180.0);
585                                 //cout << courseDev << '\n';
586                                 _headingBugTo = (fabs(courseDev) > 90.0 ? false : true);
587                         }
588                         if(!_fromWaypoint.id.empty()) {
589                                 _dtkTrue = GetGreatCircleCourse(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_RADIANS_TO_DEGREES;
590                                 _dtkMag = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
591                         } else {
592                                 _dtkTrue = 0.0;
593                                 _dtkMag = 0.0;
594                         }
595                 }
596                 
597                 _dist2Act = GetGreatCircleDistance(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon) * SG_NM_TO_METER;
598                 if(_groundSpeed_ms > 10.0) {
599                         _eta = _dist2Act / _groundSpeed_ms;
600                         if(_eta <= 36) {        // TODO - this is slightly different if turn anticipation is enabled.
601                                 if(_headingBugTo) {
602                                         _waypointAlert = true;  // TODO - not if the from flag is set.
603                                 }
604                         }
605                         if(_eta < 60) {
606                                 // Check if we should sequence to next leg.
607                                 // Perhaps this should be done on distance instead, but 60s time (about 1 - 2 nm) seems reasonable for now.
608                                 //double reverseHeading = GetGreatCircleCourse(_activeWaypoint->lat, _activeWaypoint->lon, _fromWaypoint->lat, _fromWaypoint->lon);
609                                 // Hack - let's cheat and do it on heading bug for now.  TODO - that stops us 'cutting the corner'
610                                 // when we happen to approach the inside turn of a waypoint - we should probably sequence at the midpoint
611                                 // of the heading difference between legs in this instance.
612                                 int idx = GetActiveWaypointIndex();
613                                 bool finalLeg = (idx == (int)(_activeFP->waypoints.size()) - 1 ? true : false);
614                                 bool finalDto = (_dto && idx == -1);    // Dto operation to a waypoint not in the flightplan - we don't sequence in this instance
615                                 if(!_headingBugTo) {
616                                         if(finalLeg) {
617                                                 // Do nothing - not sure if Dto should switch off when arriving at the final waypoint of a flightplan
618                                         } else if(finalDto) {
619                                                 // Do nothing
620                                         } else if(_activeWaypoint.appType == GPS_MAP) {
621                                                 // Don't sequence beyond the missed approach point
622                                                 //cout << "ACTIVE WAYPOINT is MAP - not sequencing!!!!!\n";
623                                         } else {
624                                                 //cout << "Sequencing...\n";
625                                                 _fromWaypoint = _activeWaypoint;
626                                                 _activeWaypoint = *_activeFP->waypoints[idx + 1];
627                                                 _dto = false;
628                                                 // TODO - course alteration message format is dependent on whether we are slaved HSI/CDI indicator or not.
629                                                 // For now assume we are not.
630                                                 string s;
631                                                 if(fgGetBool("/instrumentation/nav[0]/slaved-to-gps")) {
632                                                         // TODO - avoid the hardwiring on nav[0]
633                                                         s = "Adj Nav Crs to ";
634                                                 } else {
635                                                         string s = "GPS Course is ";
636                                                 }
637                                                 double d = GetMagHeadingFromTo(_fromWaypoint.lat, _fromWaypoint.lon, _activeWaypoint.lat, _activeWaypoint.lon);
638                                                 while(d < 0.0) d += 360.0;
639                                                 while(d >= 360.0) d -= 360.0;
640                                                 char buf[4];
641                                                 snprintf(buf, 4, "%03i", (int)(d + 0.5));
642                                                 s += buf;
643                                                 _messageStack.push_back(s);
644                                         }
645                                         _waypointAlert = false;
646                                 }
647                         }
648                 } else {
649                         _eta = 0.0;
650                 }
651                 
652                 /*
653                 // First attempt at a sensible cross-track correction calculation
654                 // Uh? - I think this is implemented further down the file!
655                 if(_fromWaypoint != NULL) {
656                                 
657                 } else {
658                         _crosstrackDist = 0.0;
659                 }
660                 */
661         }
662 }
663
664 // I don't yet fully understand all the gotchas about where to source time from.
665 // This function sets the initial timer before the clock exports properties
666 // and the one below uses the clock to be consistent with the rest of the code.
667 // It might change soonish...
668 void DCLGPS::SetPowerOnTimer() {
669         struct tm *t = globals->get_time_params()->getGmt();
670         _powerOnTime.set_hr(t->tm_hour);
671         _powerOnTime.set_min(t->tm_min);
672         _powerOnTimerSet = true;
673 }
674
675 void DCLGPS::ResetPowerOnTimer() {
676         _powerOnTime.set_hr(atoi(fgGetString("/instrumentation/clock/indicated-hour")));
677         _powerOnTime.set_min(atoi(fgGetString("/instrumentation/clock/indicated-min")));
678         _powerOnTimerSet = true;
679 }
680
681 double DCLGPS::GetCDIDeflection() const {
682         double xtd = CalcCrossTrackDeviation(); //nm
683         return((xtd / _currentCdiScale) * 5.0 * 2.5 * -1.0);
684 }
685
686 void DCLGPS::DtoInitiate(const string& s) {
687         //cout << "DtoInitiate, s = " << s << '\n';
688         const GPSWaypoint* wp = FindFirstByExactId(s);
689         if(wp) {
690                 //cout << "Waypoint found, starting dto operation!\n";
691                 _dto = true;
692                 _activeWaypoint = *wp;
693                 _fromWaypoint.lat = _gpsLat;
694                 _fromWaypoint.lon = _gpsLon;
695                 _fromWaypoint.type = GPS_WP_VIRT;
696                 _fromWaypoint.id = "DTOWP";
697     delete wp;
698         } else {
699                 //cout << "Waypoint not found, ignoring dto request\n";
700                 // Should bring up the user waypoint page, but we're not implementing that yet.
701                 _dto = false;   // TODO - implement this some day.
702         }
703 }
704
705 void DCLGPS::DtoCancel() {
706         if(_dto) {
707                 // i.e. don't bother reorientating if we're just cancelling a DTO button press
708                 // without having previously initiated DTO.
709                 OrientateToActiveFlightPlan();
710         }
711         _dto = false;
712 }
713
714 void DCLGPS::Knob1Left1() {}
715 void DCLGPS::Knob1Right1() {}
716 void DCLGPS::Knob2Left1() {}
717 void DCLGPS::Knob2Right1() {}
718 void DCLGPS::CrsrPressed() { _activePage->CrsrPressed(); }
719 void DCLGPS::EntPressed() { _activePage->EntPressed(); }
720 void DCLGPS::ClrPressed() { _activePage->ClrPressed(); }
721 void DCLGPS::DtoPressed() {}
722 void DCLGPS::NrstPressed() {}
723 void DCLGPS::AltPressed() {}
724
725 void DCLGPS::OBSPressed() { 
726         _obsMode = !_obsMode;
727         if(_obsMode) {
728                 if(!_activeWaypoint.id.empty()) {
729                         _obsHeading = static_cast<int>(_dtkMag);
730                 }
731                 // TODO - the _fromWaypoint location will change as the OBS heading changes.
732                 // Might need to store the OBS initiation position somewhere in case it is needed again.
733                 SetOBSFromWaypoint();
734         }
735 }
736
737 // Set the _fromWaypoint position based on the active waypoint and OBS radial.
738 void DCLGPS::SetOBSFromWaypoint() {
739         if(!_obsMode) return;
740         if(_activeWaypoint.id.empty()) return;
741         
742         // TODO - base the 180 deg correction on the to/from flag.
743         _fromWaypoint = GetPositionOnMagRadial(_activeWaypoint, 10, _obsHeading + 180.0);
744         _fromWaypoint.id = "OBSWP";
745 }
746
747 void DCLGPS::MsgPressed() {}
748
749 void DCLGPS::CDIFSDIncrease() {
750         if(_currentCdiScaleIndex == 0) {
751                 _currentCdiScaleIndex = _cdiScales.size() - 1;
752         } else {
753                 _currentCdiScaleIndex--;
754         }
755 }
756
757 void DCLGPS::CDIFSDDecrease() {
758         _currentCdiScaleIndex++;
759         if(_currentCdiScaleIndex == _cdiScales.size()) {
760                 _currentCdiScaleIndex = 0;
761         }
762 }
763
764 void DCLGPS::DrawChar(char c, int field, int px, int py, bool bold) {
765 }
766
767 void DCLGPS::DrawText(const string& s, int field, int px, int py, bool bold) {
768 }
769
770 void DCLGPS::SetBaroUnits(int n, bool wrap) {
771         if(n < 1) {
772                 _baroUnits = (GPSPressureUnits)(wrap ? 3 : 1);
773         } else if(n > 3) {
774                 _baroUnits = (GPSPressureUnits)(wrap ? 1 : 3);
775         } else {
776                 _baroUnits = (GPSPressureUnits)n;
777         }
778 }
779
780 void DCLGPS::CreateDefaultFlightPlans() {}
781
782 // Get the time to the active waypoint in seconds.
783 // Returns -1 if groundspeed < 30 kts
784 double DCLGPS::GetTimeToActiveWaypoint() {
785         if(_groundSpeed_kts < 30.0) {
786                 return(-1.0);
787         } else {
788                 return(_eta);
789         }
790 }
791
792 // Get the time to the final waypoint in seconds.
793 // Returns -1 if groundspeed < 30 kts
794 double DCLGPS::GetETE() {
795         if(_groundSpeed_kts < 30.0) {
796                 return(-1.0);
797         } else {
798                 // TODO - handle OBS / DTO operation appropriately
799                 if(_activeFP->waypoints.empty()) {
800                         return(-1.0);
801                 } else {
802                         return(GetTimeToWaypoint(_activeFP->waypoints[_activeFP->waypoints.size() - 1]->id));
803                 }
804         }
805 }
806
807 // Get the time to a given waypoint (spec'd by ID) in seconds.
808 // returns -1 if groundspeed is less than 30kts.
809 // If the waypoint is an unreached part of the active flight plan the time will be via each leg.
810 // otherwise it will be a direct-to time.
811 double DCLGPS::GetTimeToWaypoint(const string& id) {
812         if(_groundSpeed_kts < 30.0) {
813                 return(-1.0);
814         }
815         
816         double eta = 0.0;
817         int n1 = GetActiveWaypointIndex();
818         int n2 = GetWaypointIndex(id);
819         if(n2 > n1) {
820                 eta = _eta;
821                 for(unsigned int i=n1+1; i<_activeFP->waypoints.size(); ++i) {
822                         GPSWaypoint* wp1 = _activeFP->waypoints[i-1];
823                         GPSWaypoint* wp2 = _activeFP->waypoints[i];
824                         double distm = GetGreatCircleDistance(wp1->lat, wp1->lon, wp2->lat, wp2->lon) * SG_NM_TO_METER;
825                         eta += (distm / _groundSpeed_ms);
826                 }
827                 return(eta);
828         } else if(id == _activeWaypoint.id) {
829                 return(_eta);
830         } else {
831                 const GPSWaypoint* wp = FindFirstByExactId(id);
832                 if(wp == NULL) return(-1.0);
833                 double distm = GetGreatCircleDistance(_gpsLat, _gpsLon, wp->lat, wp->lon);
834     delete wp;
835                 return(distm / _groundSpeed_ms);
836         }
837         return(-1.0);   // Hopefully we never get here!
838 }
839
840 // Returns magnetic great-circle heading
841 // TODO - document units.
842 float DCLGPS::GetHeadingToActiveWaypoint() {
843         if(_activeWaypoint.id.empty()) {
844                 return(-888);
845         } else {
846                 double h = GetMagHeadingFromTo(_gpsLat, _gpsLon, _activeWaypoint.lat, _activeWaypoint.lon);
847                 while(h <= 0.0) h += 360.0;
848                 while(h > 360.0) h -= 360.0;
849                 return((float)h);
850         }
851 }
852
853 // Returns magnetic great-circle heading
854 // TODO - what units?
855 float DCLGPS::GetHeadingFromActiveWaypoint() {
856         if(_activeWaypoint.id.empty()) {
857                 return(-888);
858         } else {
859                 double h = GetMagHeadingFromTo(_activeWaypoint.lat, _activeWaypoint.lon, _gpsLat, _gpsLon);
860                 while(h <= 0.0) h += 360.0;
861                 while(h > 360.0) h -= 360.0;
862                 return(h);
863         }
864 }
865
866 void DCLGPS::ClearFlightPlan(int n) {
867         for(unsigned int i=0; i<_flightPlans[n]->waypoints.size(); ++i) {
868                 delete _flightPlans[n]->waypoints[i];
869         }
870         _flightPlans[n]->waypoints.clear();
871 }
872
873 void DCLGPS::ClearFlightPlan(GPSFlightPlan* fp) {
874         for(unsigned int i=0; i<fp->waypoints.size(); ++i) {
875                 delete fp->waypoints[i];
876         }
877         fp->waypoints.clear();
878 }
879
880 int DCLGPS::GetActiveWaypointIndex() {
881         for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
882                 if(_flightPlans[0]->waypoints[i]->id == _activeWaypoint.id) return((int)i);
883         }
884         return(-1);
885 }
886
887 int DCLGPS::GetWaypointIndex(const string& id) {
888         for(unsigned int i=0; i<_flightPlans[0]->waypoints.size(); ++i) {
889                 if(_flightPlans[0]->waypoints[i]->id == id) return((int)i);
890         }
891         return(-1);
892 }
893
894 void DCLGPS::OrientateToFlightPlan(GPSFlightPlan* fp) {
895         //cout << "Orientating...\n";
896         //cout << "_lat = " << _lat << ", _lon = " << _lon << ", _gpsLat = " << _gpsLat << ", gpsLon = " << _gpsLon << '\n'; 
897         if(fp->IsEmpty()) {
898                 _activeWaypoint.id.clear();
899                 _navFlagged = true;
900         } else {
901                 _navFlagged = false;
902                 if(fp->waypoints.size() == 1) {
903                         // TODO - may need to flag nav here if not dto or obs, or possibly handle it somewhere else.
904                         _activeWaypoint = *fp->waypoints[0];
905                         _fromWaypoint.id.clear();
906                 } else {
907                         // FIXME FIXME FIXME
908                         _fromWaypoint = *fp->waypoints[0];
909                         _activeWaypoint = *fp->waypoints[1];
910                         double dmin = 1000000;  // nm!!
911                         // For now we will simply start on the leg closest to our current position.
912                         // It's possible that more fancy algorithms may take either heading or track
913                         // into account when setting inital leg - I'm not sure.
914                         // This method should handle most cases perfectly OK though.
915                         for(unsigned int i = 1; i < fp->waypoints.size(); ++i) {
916                                 //cout << "Pass " << i << ", dmin = " << dmin << ", leg is " << fp->waypoints[i-1]->id << " to " << fp->waypoints[i]->id << '\n';
917                                 // First get the cross track correction.
918                                 double d0 = fabs(CalcCrossTrackDeviation(*fp->waypoints[i-1], *fp->waypoints[i]));
919                                 // That is the shortest distance away we could be though - check for
920                                 // longer distances if we are 'off the end' of the leg.
921                                 double ht1 = GetGreatCircleCourse(fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon, 
922                                                                   fp->waypoints[i]->lat, fp->waypoints[i]->lon) 
923                                                                                                   * SG_RADIANS_TO_DEGREES;
924                                 // not simply the reverse of the above due to great circle navigation.
925                                 double ht2 = GetGreatCircleCourse(fp->waypoints[i]->lat, fp->waypoints[i]->lon, 
926                                                                   fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon) 
927                                                                                                   * SG_RADIANS_TO_DEGREES;
928                                 double hw1 = GetGreatCircleCourse(_gpsLat, _gpsLon,
929                                                                   fp->waypoints[i]->lat, fp->waypoints[i]->lon) 
930                                                                                                   * SG_RADIANS_TO_DEGREES;
931                                 double hw2 = GetGreatCircleCourse(_gpsLat, _gpsLon, 
932                                                                   fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon) 
933                                                                                                   * SG_RADIANS_TO_DEGREES;
934                                 double h1 = ht1 - hw1;
935                                 double h2 = ht2 - hw2;
936                                 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
937                                 //cout << "Normalizing...\n";
938                                 SG_NORMALIZE_RANGE(h1, -180.0, 180.0);
939                                 SG_NORMALIZE_RANGE(h2, -180.0, 180.0);
940                                 //cout << "d0, h1, h2 = " << d0 << ", " << h1 << ", " << h2 << '\n';
941                                 if(fabs(h1) > 90.0) {
942                                         // We are past the end of the to waypoint
943                                         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i]->lat, fp->waypoints[i]->lon);
944                                         if(d > d0) d0 = d;
945                                         //cout << "h1 triggered, d0 now = " << d0 << '\n';
946                                 } else if(fabs(h2) > 90.0) {
947                                         // We are past the end (not yet at!) the from waypoint
948                                         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, fp->waypoints[i-1]->lat, fp->waypoints[i-1]->lon);
949                                         if(d > d0) d0 = d;
950                                         //cout << "h2 triggered, d0 now = " << d0 << '\n';
951                                 }
952                                 if(d0 < dmin) {
953                                         //cout << "THIS LEG NOW ACTIVE!\n";
954                                         dmin = d0;
955                                         _fromWaypoint = *fp->waypoints[i-1];
956                                         _activeWaypoint = *fp->waypoints[i];
957                                 }
958                         }
959                 }
960         }
961 }
962
963 void DCLGPS::OrientateToActiveFlightPlan() {
964         OrientateToFlightPlan(_activeFP);
965 }       
966
967 /***************************************/
968
969 // Utility function - create a flightplan from a list of waypoint ids and types
970 void DCLGPS::CreateFlightPlan(GPSFlightPlan* fp, vector<string> ids, vector<GPSWpType> wps) {
971         if(fp == NULL) fp = new GPSFlightPlan;
972         unsigned int i;
973         if(!fp->waypoints.empty()) {
974                 for(i=0; i<fp->waypoints.size(); ++i) {
975                         delete fp->waypoints[i];
976                 }
977                 fp->waypoints.clear();
978         }
979         if(ids.size() != wps.size()) {
980                 cout << "ID and Waypoint types list size mismatch in GPS::CreateFlightPlan - no flightplan created!\n";
981                 return;
982         }
983         for(i=0; i<ids.size(); ++i) {
984                 bool multi;
985                 const FGAirport* ap;
986                 FGNavRecord* np;
987                 GPSWaypoint* wp = new GPSWaypoint;
988                 wp->type = wps[i];
989                 switch(wp->type) {
990                 case GPS_WP_APT:
991                         ap = FindFirstAptById(ids[i], multi, true);
992                         if(ap == NULL) {
993                                 // error
994                                 delete wp;
995                         } else {
996                                 wp->lat = ap->getLatitude() * SG_DEGREES_TO_RADIANS;
997                                 wp->lon = ap->getLongitude() * SG_DEGREES_TO_RADIANS;
998                                 wp->id = ids[i];
999                                 fp->waypoints.push_back(wp);
1000                         }
1001                         break;
1002                 case GPS_WP_VOR:
1003                         np = FindFirstVorById(ids[i], multi, true);
1004                         if(np == NULL) {
1005                                 // error
1006                                 delete wp;
1007                         } else {
1008                                 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1009                                 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1010                                 wp->id = ids[i];
1011                                 fp->waypoints.push_back(wp);
1012                         }
1013                         break;
1014                 case GPS_WP_NDB:
1015                         np = FindFirstNDBById(ids[i], multi, true);
1016                         if(np == NULL) {
1017                                 // error
1018                                 delete wp;
1019                         } else {
1020                                 wp->lat = np->get_lat() * SG_DEGREES_TO_RADIANS;
1021                                 wp->lon = np->get_lon() * SG_DEGREES_TO_RADIANS;
1022                                 wp->id = ids[i];
1023                                 fp->waypoints.push_back(wp);
1024                         }
1025                         break;
1026                 case GPS_WP_INT:
1027                         // TODO TODO
1028                         break;
1029                 case GPS_WP_USR:
1030                         // TODO
1031                         break;
1032                 }
1033         }
1034 }
1035
1036 /***************************************/
1037
1038 class DCLGPSFilter : public FGPositioned::Filter
1039 {
1040 public:
1041   virtual bool pass(const FGPositioned* aPos) const {
1042     switch (aPos->type()) {
1043     case FGPositioned::AIRPORT:
1044     // how about heliports and seaports?
1045     case FGPositioned::NDB:
1046     case FGPositioned::VOR:
1047     case FGPositioned::WAYPOINT:
1048     case FGPositioned::FIX:
1049       break;
1050     default: return false; // reject all other types
1051     }
1052     return true;
1053   }
1054 };
1055
1056 GPSWaypoint* DCLGPS::FindFirstById(const string& id) const
1057 {
1058   DCLGPSFilter filter;
1059   FGPositionedRef result = FGPositioned::findNextWithPartialId(NULL, id, &filter);
1060   return GPSWaypoint::createFromPositioned(result);
1061 }
1062
1063 GPSWaypoint* DCLGPS::FindFirstByExactId(const string& id) const
1064 {
1065   SGGeod pos(SGGeod::fromRad(_lon, _lat));
1066   FGPositionedRef result = FGPositioned::findClosestWithIdent(id, pos);
1067   return GPSWaypoint::createFromPositioned(result);
1068 }
1069
1070 // TODO - add the ASCII / alphabetical stuff from the Atlas version
1071 FGPositioned* DCLGPS::FindTypedFirstById(const string& id, FGPositioned::Type ty, bool &multi, bool exact)
1072 {
1073   multi = false;
1074   FGPositioned::TypeFilter filter(ty);
1075   
1076   if (exact) {
1077     FGPositioned::List matches = 
1078       FGPositioned::findAllWithIdentSortedByRange(id, SGGeod::fromRad(_lon, _lat), &filter);
1079     multi = (matches.size() > 1);
1080     return matches.empty() ? NULL : matches.front().ptr();
1081   }
1082   
1083   return FGPositioned::findNextWithPartialId(NULL, id, &filter);
1084 }
1085
1086 FGNavRecord* DCLGPS::FindFirstVorById(const string& id, bool &multi, bool exact)
1087 {
1088   return dynamic_cast<FGNavRecord*>(FindTypedFirstById(id, FGPositioned::VOR, multi, exact));
1089 }
1090
1091 FGNavRecord* DCLGPS::FindFirstNDBById(const string& id, bool &multi, bool exact)
1092 {
1093   return dynamic_cast<FGNavRecord*>(FindTypedFirstById(id, FGPositioned::NDB, multi, exact));
1094 }
1095
1096 const FGFix* DCLGPS::FindFirstIntById(const string& id, bool &multi, bool exact)
1097 {
1098   return dynamic_cast<FGFix*>(FindTypedFirstById(id, FGPositioned::FIX, multi, exact));
1099 }
1100
1101 const FGAirport* DCLGPS::FindFirstAptById(const string& id, bool &multi, bool exact)
1102 {
1103   return dynamic_cast<FGAirport*>(FindTypedFirstById(id, FGPositioned::AIRPORT, multi, exact));
1104 }
1105
1106 FGNavRecord* DCLGPS::FindClosestVor(double lat_rad, double lon_rad) {  
1107   FGPositioned::TypeFilter filter(FGPositioned::VOR);
1108   double cutoff = 1000; // nautical miles
1109   FGPositionedRef v = FGPositioned::findClosest(SGGeod::fromRad(lon_rad, lat_rad), cutoff, &filter);
1110   if (!v) {
1111     return NULL;
1112   }
1113   
1114   return dynamic_cast<FGNavRecord*>(v.ptr());
1115 }
1116
1117 //----------------------------------------------------------------------------------------------------------
1118
1119 // Takes lat and lon in RADIANS!!!!!!!
1120 double DCLGPS::GetMagHeadingFromTo(double latA, double lonA, double latB, double lonB) {
1121         double h = GetGreatCircleCourse(latA, lonA, latB, lonB);
1122         h *= SG_RADIANS_TO_DEGREES;
1123         // TODO - use the real altitude below instead of 0.0!
1124         //cout << "MagVar = " << sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES << '\n';
1125         h -= sgGetMagVar(_gpsLon, _gpsLat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1126         while(h >= 360.0) h -= 360.0;
1127         while(h < 0.0) h += 360.0;
1128         return(h);
1129 }
1130
1131 // ---------------- Great Circle formulae from "The Aviation Formulary" -------------
1132 // Note that all of these assume that the world is spherical.
1133
1134 double Rad2Nm(double theta) {
1135         return(((180.0*60.0)/SG_PI)*theta);
1136 }
1137
1138 double Nm2Rad(double d) {
1139         return((SG_PI/(180.0*60.0))*d);
1140 }
1141
1142 /* QUOTE:
1143
1144 The great circle distance d between two points with coordinates {lat1,lon1} and {lat2,lon2} is given by:
1145
1146 d=acos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(lon1-lon2))
1147
1148 A mathematically equivalent formula, which is less subject to rounding error for short distances is:
1149
1150 d=2*asin(sqrt((sin((lat1-lat2)/2))^2 + 
1151                  cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
1152                                  
1153 */
1154
1155 // Returns distance in nm, takes lat & lon in RADIANS
1156 double DCLGPS::GetGreatCircleDistance(double lat1, double lon1, double lat2, double lon2) const {
1157         double d = 2.0 * asin(sqrt(((sin((lat1-lat2)/2.0))*(sin((lat1-lat2)/2.0))) +
1158                    cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2.0))*(sin((lon1-lon2)/2.0))));
1159         return(Rad2Nm(d));
1160 }
1161
1162 // fmod dosen't do what we want :-( 
1163 static double mod(double d1, double d2) {
1164         return(d1 - d2*floor(d1/d2));
1165 }
1166
1167 // Returns great circle course from point 1 to point 2
1168 // Input and output in RADIANS.
1169 double DCLGPS::GetGreatCircleCourse (double lat1, double lon1, double lat2, double lon2) const {
1170         //double h = 0.0;
1171         /*
1172         // Special case the poles
1173         if(cos(lat1) < SG_EPSILON) {
1174                 if(lat1 > 0) {
1175                         // Starting from North Pole
1176                         h = SG_PI;
1177                 } else {
1178                         // Starting from South Pole
1179                         h = 2.0 * SG_PI;
1180                 }
1181         } else {
1182                 // Urgh - the formula below is for negative lon +ve !!!???
1183                 double d = GetGreatCircleDistance(lat1, lon1, lat2, lon2);
1184                 cout << "d = " << d;
1185                 d = Nm2Rad(d);
1186                 //cout << ", d_theta = " << d;
1187                 //cout << ", and d = " << Rad2Nm(d) << ' ';
1188                 if(sin(lon2 - lon1) < 0) {
1189                         cout << " A ";
1190                         h = acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1191                 } else {
1192                         cout << " B ";
1193                         h = 2.0 * SG_PI - acos((sin(lat2)-sin(lat1)*cos(d))/(sin(d)*cos(lat1)));
1194                 }
1195         }
1196         cout << h * SG_RADIANS_TO_DEGREES << '\n';
1197         */
1198         
1199         return( mod(atan2(sin(lon2-lon1)*cos(lat2),
1200             cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)),
1201             2.0*SG_PI) );
1202 }
1203
1204 // Return a position on a radial from wp1 given distance d (nm) and magnetic heading h (degrees)
1205 // Note that d should be less that 1/4 Earth diameter!
1206 GPSWaypoint DCLGPS::GetPositionOnMagRadial(const GPSWaypoint& wp1, double d, double h) {
1207         h += sgGetMagVar(wp1.lon, wp1.lat, 0.0, _time->getJD()) * SG_RADIANS_TO_DEGREES;
1208         return(GetPositionOnRadial(wp1, d, h));
1209 }
1210
1211 // Return a position on a radial from wp1 given distance d (nm) and TRUE heading h (degrees)
1212 // Note that d should be less that 1/4 Earth diameter!
1213 GPSWaypoint DCLGPS::GetPositionOnRadial(const GPSWaypoint& wp1, double d, double h) {
1214         while(h < 0.0) h += 360.0;
1215         while(h > 360.0) h -= 360.0;
1216         
1217         h *= SG_DEGREES_TO_RADIANS;
1218         d *= (SG_PI / (180.0 * 60.0));
1219         
1220         double lat=asin(sin(wp1.lat)*cos(d)+cos(wp1.lat)*sin(d)*cos(h));
1221         double lon;
1222         if(cos(lat)==0) {
1223                 lon=wp1.lon;      // endpoint a pole
1224         } else {
1225                 lon=mod(wp1.lon+asin(sin(h)*sin(d)/cos(lat))+SG_PI,2*SG_PI)-SG_PI;
1226         }
1227         
1228         GPSWaypoint wp;
1229         wp.lat = lat;
1230         wp.lon = lon;
1231         wp.type = GPS_WP_VIRT;
1232         return(wp);
1233 }
1234
1235 // Returns cross-track deviation in Nm.
1236 double DCLGPS::CalcCrossTrackDeviation() const {
1237         return(CalcCrossTrackDeviation(_fromWaypoint, _activeWaypoint));
1238 }
1239
1240 // Returns cross-track deviation of the current position between two arbitary waypoints in nm.
1241 double DCLGPS::CalcCrossTrackDeviation(const GPSWaypoint& wp1, const GPSWaypoint& wp2) const {
1242         //if(wp1 == NULL || wp2 == NULL) return(0.0);
1243         if(wp1.id.empty() || wp2.id.empty()) return(0.0);
1244         double xtd = asin(sin(Nm2Rad(GetGreatCircleDistance(wp1.lat, wp1.lon, _gpsLat, _gpsLon))) 
1245                           * sin(GetGreatCircleCourse(wp1.lat, wp1.lon, _gpsLat, _gpsLon) - GetGreatCircleCourse(wp1.lat, wp1.lon, wp2.lat, wp2.lon)));
1246         return(Rad2Nm(xtd));
1247 }