]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/KLN89/kln89.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[flightgear.git] / src / Instrumentation / KLN89 / kln89.cxx
1 // kln89_page.cxx - a class to manage the simulation of a KLN89
2 //                  GPS unit.  Note that this is primarily the 
3 //                  simulation of the user interface and display
4 //                  - the core GPS calculations such as position
5 //                  and waypoint sequencing are done (or should 
6 //                  be done) by FG code. 
7 //
8 // Written by David Luff, started 2005.
9 //
10 // Copyright (C) 2005 - David C Luff - daveluff AT ntlworld.com
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27
28 #include "kln89.hxx"
29 #include "kln89_page.hxx"
30 #include "kln89_page_apt.hxx"
31 #include "kln89_page_vor.hxx"
32 #include "kln89_page_ndb.hxx"
33 #include "kln89_page_int.hxx"
34 #include "kln89_page_usr.hxx"
35 #include "kln89_page_act.hxx"
36 #include "kln89_page_nav.hxx"
37 #include "kln89_page_fpl.hxx"
38 #include "kln89_page_cal.hxx"
39 #include "kln89_page_set.hxx"
40 #include "kln89_page_oth.hxx"
41 #include "kln89_page_dir.hxx"
42 #include "kln89_page_nrst.hxx"
43 #include "kln89_symbols.hxx"
44 #include <iostream>
45
46 #if ENABLE_ATCDCL
47 #include <ATCDCL/ATCProjection.hxx>
48 #else
49 #include <ATC/atcutils.hxx>
50 #endif
51
52 #include <Main/fg_props.hxx>
53 #include <simgear/math/SGMath.hxx>
54 #include <simgear/structure/commands.hxx>
55 #include <Airports/simple.hxx>
56
57 using std::cout;
58
59 // Command callbacks for FlightGear
60
61 static bool do_kln89_msg_pressed(const SGPropertyNode* arg) {
62         //cout << "do_kln89_msg_pressed called!\n";
63         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
64         gps->MsgPressed();
65         return(true);
66 }
67
68 static bool do_kln89_obs_pressed(const SGPropertyNode* arg) {
69         //cout << "do_kln89_obs_pressed called!\n";
70         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
71         gps->OBSPressed();
72         return(true);
73 }
74
75 static bool do_kln89_alt_pressed(const SGPropertyNode* arg) {
76         //cout << "do_kln89_alt_pressed called!\n";
77         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
78         gps->AltPressed();
79         return(true);
80 }
81
82 static bool do_kln89_nrst_pressed(const SGPropertyNode* arg) {
83         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
84         gps->NrstPressed();
85         return(true);
86 }
87
88 static bool do_kln89_dto_pressed(const SGPropertyNode* arg) {
89         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
90         gps->DtoPressed();
91         return(true);
92 }
93
94 static bool do_kln89_clr_pressed(const SGPropertyNode* arg) {
95         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
96         gps->ClrPressed();
97         return(true);
98 }
99
100 static bool do_kln89_ent_pressed(const SGPropertyNode* arg) {
101         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
102         gps->EntPressed();
103         return(true);
104 }
105
106 static bool do_kln89_crsr_pressed(const SGPropertyNode* arg) {
107         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
108         gps->CrsrPressed();
109         return(true);
110 }
111
112 static bool do_kln89_knob1left1(const SGPropertyNode* arg) {
113         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
114         gps->Knob1Left1();
115         return(true);
116 }
117
118 static bool do_kln89_knob1right1(const SGPropertyNode* arg) {
119         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
120         gps->Knob1Right1();
121         return(true);
122 }
123
124 static bool do_kln89_knob2left1(const SGPropertyNode* arg) {
125         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
126         gps->Knob2Left1();
127         return(true);
128 }
129
130 static bool do_kln89_knob2right1(const SGPropertyNode* arg) {
131         KLN89* gps = (KLN89*)globals->get_subsystem("kln89");
132         gps->Knob2Right1();
133         return(true);
134 }
135
136 // End command callbacks
137
138 KLN89::KLN89(RenderArea2D* instrument) 
139 : DCLGPS(instrument) {
140         _mode = KLN89_MODE_DISP;
141         _blink = false;
142         _cum_dt = 0.0;
143         _nFields = 2;
144         _maxFields = 2;
145         _xBorder = 0;
146         _yBorder = 4;
147         // ..Field..[0] => no fields in action
148         _xFieldBorder[0] = 0;
149         _xFieldBorder[1] = 0;
150         _yFieldBorder[0] = 0;
151         _yFieldBorder[1] = 0;
152         _xFieldBorder[2] = 2;
153         _yFieldBorder[2] = 0;
154         _xFieldStart[0] = 0;
155         _xFieldStart[1] = 0;
156         _xFieldStart[2] = 45;
157         _yFieldStart[0] = 0;
158         _yFieldStart[1] = 0;
159         _yFieldStart[2] = 0;
160         
161         //_pixelated = true;
162         _pixelated = false;
163
164         // Cyclic pages
165         _pages.clear();
166         KLN89Page* apt_page = new KLN89AptPage(this);
167         _pages.push_back(apt_page);
168         KLN89Page* vor_page = new KLN89VorPage(this);
169         _pages.push_back(vor_page);
170         KLN89Page* ndb_page = new KLN89NDBPage(this);
171         _pages.push_back(ndb_page);
172         KLN89Page* int_page = new KLN89IntPage(this);
173         _pages.push_back(int_page);
174         KLN89Page* usr_page = new KLN89UsrPage(this);
175         _pages.push_back(usr_page);
176         KLN89Page* act_page = new KLN89ActPage(this);
177         _pages.push_back(act_page);
178         KLN89Page* nav_page = new KLN89NavPage(this);
179         _pages.push_back(nav_page);
180         KLN89Page* fpl_page = new KLN89FplPage(this);
181         _pages.push_back(fpl_page);
182         KLN89Page* cal_page = new KLN89CalPage(this);
183         _pages.push_back(cal_page);
184         KLN89Page* set_page = new KLN89SetPage(this);
185         _pages.push_back(set_page);
186         KLN89Page* oth_page = new KLN89OthPage(this);
187         _pages.push_back(oth_page);
188         _nPages = _pages.size();
189         _curPage = 0;
190         
191         // Other pages
192         _dir_page = new KLN89DirPage(this);
193         _nrst_page = new KLN89NrstPage(this);
194         
195         _activePage = apt_page;
196         _obsMode = false;
197         _dto = false;
198         _fullLegMode = true;
199         _obsHeading = 215;
200         
201         _maxFlightPlans = 26;
202         for(unsigned int i=0; i<_maxFlightPlans; ++i) {
203                 GPSFlightPlan* fp = new GPSFlightPlan;
204                 fp->waypoints.clear();
205                 _flightPlans.push_back(fp);
206         }
207         _activeFP = _flightPlans[0];
208         
209         _entJump = _clrJump = -1;
210         _jumpRestoreCrsr = false;
211         
212         _dispMsg = false;
213         
214         _dtoReview = false;
215
216         // Moving map stuff
217         _mapOrientation = 0;
218         _mapHeading = 0.0;
219         _mapHeadingUpdateTimer = 0.0;
220         _drawSUA = false;
221         _drawVOR = false;
222         _drawApt = true;
223         //_mapScaleIndex = 20;
224         _mapScaleIndex = 7;     // I think that the above is more accurate for no-flightplan default, but this is more sane for initial testing!
225         _mapScaleAuto = true;
226         
227         // Configuration.  Eventually this may be user-achivable in order that settings can be persistent between sessions.
228         _suaAlertEnabled = false;
229         _altAlertEnabled = false;
230         _minDisplayBrightness = 4;
231         
232         // Mega-hack - hardwire airport town and state names for the FG base area since we don't have any data for these at the moment
233         // TODO - do this better one day!
234         _airportTowns["KSFO"] = "San Francisco";
235         _airportTowns["KSQL"] = "San Carlos";
236         _airportTowns["KPAO"] = "Palo Alto";
237         _airportTowns["KNUQ"] = "Mountain View";
238         _airportTowns["KSJC"] = "San Jose";
239         _airportTowns["KRHV"] = "San Jose";
240         _airportTowns["E16"] = "San Martin";
241         _airportTowns["KWVI"] = "Watsonville";
242         _airportTowns["KOAK"] = "Oakland";
243         _airportTowns["KHWD"] = "Hayward";
244         _airportTowns["KLVK"] = "Livermore";
245         _airportTowns["KCCR"] = "Concord";
246         _airportTowns["KTCY"] = "Tracy";
247         _airportTowns["KSCK"] = "Stockton";
248         _airportTowns["KHAF"] = "Half Moon Bay";
249         
250         _airportStates["KSFO"] = "CA";
251         _airportStates["KSQL"] = "CA";
252         _airportStates["KPAO"] = "CA";
253         _airportStates["KNUQ"] = "CA";
254         _airportStates["KSJC"] = "CA";
255         _airportStates["KRHV"] = "CA";
256         _airportStates["E16"] = "CA";
257         _airportStates["KWVI"] = "CA";
258         _airportStates["KOAK"] = "CA";
259         _airportStates["KHWD"] = "CA";
260         _airportStates["KLVK"] = "CA";
261         _airportStates["KCCR"] = "CA";
262         _airportStates["KTCY"] = "CA";
263         _airportStates["KSCK"] = "CA";
264         _airportStates["KHAF"] = "CA";
265 }
266
267 KLN89::~KLN89() {
268         for(unsigned int i=0; i<_pages.size(); ++i) {
269                 delete _pages[i];
270         }
271         
272         delete _dir_page;
273         delete _nrst_page;
274         
275         for(unsigned int i=0; i<_maxFlightPlans; ++i) {
276                 ClearFlightPlan(i);
277                 delete _flightPlans[i];
278         }
279 }
280
281 void KLN89::bind() {
282         fgTie("/instrumentation/gps/message-alert", this, &KLN89::GetMsgAlert);
283         DCLGPS::bind();
284 }
285
286 void KLN89::unbind() {
287         fgUntie("/instrumentation/gps/message-alert");
288         DCLGPS::unbind();
289 }
290
291 void KLN89::init() {
292         globals->get_commands()->addCommand("kln89_msg_pressed", do_kln89_msg_pressed);
293         globals->get_commands()->addCommand("kln89_obs_pressed", do_kln89_obs_pressed);
294         globals->get_commands()->addCommand("kln89_alt_pressed", do_kln89_alt_pressed);
295         globals->get_commands()->addCommand("kln89_nrst_pressed", do_kln89_nrst_pressed);
296         globals->get_commands()->addCommand("kln89_dto_pressed", do_kln89_dto_pressed);
297         globals->get_commands()->addCommand("kln89_clr_pressed", do_kln89_clr_pressed);
298         globals->get_commands()->addCommand("kln89_ent_pressed", do_kln89_ent_pressed);
299         globals->get_commands()->addCommand("kln89_crsr_pressed", do_kln89_crsr_pressed);
300         globals->get_commands()->addCommand("kln89_knob1left1", do_kln89_knob1left1);
301         globals->get_commands()->addCommand("kln89_knob1right1", do_kln89_knob1right1);
302         globals->get_commands()->addCommand("kln89_knob2left1", do_kln89_knob2left1);
303         globals->get_commands()->addCommand("kln89_knob2right1", do_kln89_knob2right1);
304         
305         DCLGPS::init();
306 }
307
308 void KLN89::update(double dt) {
309         // Run any positional calc's required first
310         DCLGPS::update(dt);
311         
312         // Set the display brightness.  This should be reduced in response to falling light
313         // (i.e. nighttime), or the user covering the photocell that detects the light level.
314         // At the moment I don't know how to detect nighttime or actual light level, so only
315         // respond to the photocell being obscured.
316         // TODO - reduce the brightness in response to nighttime / lowlight.
317         float rgba[4] = {1.0, 0.0, 0.0, 1.0};
318         if(fgGetBool("/instrumentation/kln89/photocell-obscured")) {
319                 rgba[0] -= (9 - _minDisplayBrightness) * 0.05;
320         }
321         _instrument->SetPixelColor(rgba);
322         
323         _cum_dt += dt;
324         if(_blink) {
325                 if(_cum_dt > 0.2) {
326                         _cum_dt = 0.0;
327                         _blink = false;
328                 }
329         } else {
330                 if(_cum_dt > 0.8) {
331                         _cum_dt = 0.0;
332                         _blink = true;
333                 }
334         }
335         
336         _mapHeadingUpdateTimer += dt;
337         if(_mapHeadingUpdateTimer > 1.0) {
338                 UpdateMapHeading();
339                 _mapHeadingUpdateTimer = 0.0;
340         }
341         
342         _instrument->Flush();
343         _instrument->DrawBackground();
344         
345         if(_dispMsg) {
346                 if(_messageStack.empty()) {
347                         DrawText("No Message", 0, 5, 2);
348                 } else {
349                         // TODO - parse the message string for special strings that indicate degrees signs etc!
350                         DrawText(*_messageStack.begin(), 0, 0, 3);
351                 }
352                 return;
353         } else {
354                 if(!_messageStack.empty()) {
355                         DrawMessageAlert();
356                 }
357         }
358         
359         if(_curPage == 6 && _activePage->GetSubPage() == 3) {
360                 // Don't draw the bar on the nav-4 page
361         } else if(_activePage == _nrst_page) {
362                 // Don't draw the bar on the nearest page
363         } else {
364                 DrawBar(_curPage);
365         }
366         
367         _activePage->Update(dt);
368 }
369
370 void KLN89::CreateDefaultFlightPlans() {
371         // TODO - read these in from preferences.xml or similar instead!!!!
372         // Create some hardwired default flightplans for testing.
373         vector<string> ids;
374         vector<GPSWpType> wps;
375         
376         ids.clear();
377         wps.clear();
378         ids.push_back("KLSN");
379         wps.push_back(GPS_WP_APT);
380         ids.push_back("VOLTA");
381         wps.push_back(GPS_WP_INT);
382         ids.push_back("C83");
383         wps.push_back(GPS_WP_APT);
384         CreateFlightPlan(_flightPlans[5], ids, wps);
385         
386         ids.clear();
387         wps.clear();
388         ids.push_back("KCCR");
389         wps.push_back(GPS_WP_APT);
390         ids.push_back("KHAF");
391         wps.push_back(GPS_WP_APT);
392         CreateFlightPlan(_flightPlans[4], ids, wps);
393         
394         ids.clear();
395         wps.clear();
396         ids.push_back("KLVK");
397         wps.push_back(GPS_WP_APT);
398         ids.push_back("OAK");
399         wps.push_back(GPS_WP_VOR);
400         ids.push_back("PORTE");
401         wps.push_back(GPS_WP_INT);
402         ids.push_back("KHAF");
403         wps.push_back(GPS_WP_APT);
404         CreateFlightPlan(_flightPlans[3], ids, wps);
405         
406         ids.clear();
407         wps.clear();
408         ids.push_back("KDPA");
409         wps.push_back(GPS_WP_APT);
410         ids.push_back("OBK");
411         wps.push_back(GPS_WP_VOR);
412         ids.push_back("ENW");
413         wps.push_back(GPS_WP_VOR);
414         ids.push_back("KRAC");
415         wps.push_back(GPS_WP_APT);
416         CreateFlightPlan(_flightPlans[2], ids, wps);
417         //cout << "Size of FP2 WP list is " << _flightPlans[2]->waypoints.size() << '\n';
418         
419         ids.clear();
420         wps.clear();
421         ids.push_back("KSFO");
422         ids.push_back("KOAK");
423         wps.push_back(GPS_WP_APT);
424         wps.push_back(GPS_WP_APT);
425         CreateFlightPlan(_flightPlans[1], ids, wps);
426         
427         ids.clear();
428         wps.clear();
429         //ids.push_back("KOSH");
430         ids.push_back("KSFO");
431         ids.push_back("KHAF");
432         ids.push_back("OSI");
433         ids.push_back("KSQL");
434         //ids.push_back("KPAO");
435         //ids.push_back("KHWD");
436         wps.push_back(GPS_WP_APT);
437         wps.push_back(GPS_WP_APT);
438         wps.push_back(GPS_WP_VOR);
439         wps.push_back(GPS_WP_APT);
440         //wps.push_back(GPS_WP_APT);
441         //wps.push_back(GPS_WP_APT);
442         CreateFlightPlan(_flightPlans[0], ids, wps);
443         
444         /*
445         ids.clear();
446         wps.clear();
447         ids.push_back("KLVK");
448         ids.push_back("KHWD");
449         wps.push_back(GPS_WP_APT);
450         wps.push_back(GPS_WP_APT);
451         CreateFlightPlan(_flightPlans[0], ids, wps);
452         */
453 }
454
455 void KLN89::Knob1Right1() {
456         if(_mode == KLN89_MODE_DISP) {
457                 _activePage->LooseFocus();
458                 if(_cleanUpPage >= 0) {
459                         _pages[(unsigned int)_cleanUpPage]->CleanUp();
460                         _cleanUpPage = -1;
461                 }
462                 _curPage++;
463                 if(_curPage >= _pages.size()) _curPage = 0;
464                 _activePage = _pages[_curPage];
465         } else {
466                 _activePage->Knob1Right1();
467         }
468         update(0.0);
469 }
470
471 void KLN89::Knob1Left1() {
472         if(_mode == KLN89_MODE_DISP) {
473                 _activePage->LooseFocus();
474                 if(_cleanUpPage >= 0) {
475                         _pages[(unsigned int)_cleanUpPage]->CleanUp();
476                         _cleanUpPage = -1;
477                 }
478                 if(_curPage == 0) {
479                         _curPage = _pages.size() - 1;
480                 } else {
481                         _curPage--;
482                 }
483                 _activePage = _pages[_curPage];
484         } else {
485                 _activePage->Knob1Left1();
486         }
487         update(0.0);
488 }
489
490 void KLN89::Knob2Left1() {
491         _activePage->Knob2Left1();
492 }
493
494 void KLN89::Knob2Right1() {
495         _activePage->Knob2Right1();
496 }
497
498 void KLN89::CrsrPressed() {
499         _dispMsg = false;
500         // CRSR cannot be switched off on nrst page.
501         if(_activePage == _nrst_page) { return; }
502         // CRSR is always off when inner-knob is out on nav4 page.
503         if(_curPage == 6 && _activePage->GetSubPage() == 3 && fgGetBool("/instrumentation/kln89/scan-pull")) { return; }
504         if(_cleanUpPage >= 0) {
505                 _pages[(unsigned int)_cleanUpPage]->CleanUp();
506                 _cleanUpPage = -1;
507         }
508         _jumpRestoreCrsr = false;
509         _entJump = _clrJump = -1;
510         ((KLN89Page*)_activePage)->SetEntInvert(false);
511         if(_mode == KLN89_MODE_DISP) {
512                 _mode = KLN89_MODE_CRSR;
513                 _activePage->CrsrPressed();
514         } else {
515                 _mode = KLN89_MODE_DISP;
516                 _activePage->CrsrPressed();
517         }
518         update(0.0);
519 }
520
521 void KLN89::EntPressed() {
522         if(_entJump >= 0) {
523                 if(_curPage < 5) {
524                         // one of the data pages.  Signal ent pressed to it here, and ent pressed to the call back page a few lines further down.
525                         // Ie. 2 ent pressed signals in this case is deliberate.
526                         _activePage->EntPressed();
527                 }
528                 _curPage = _entJump;
529                 _activePage = _pages[(unsigned int)_entJump];
530                 if(_jumpRestoreCrsr) _mode = KLN89_MODE_CRSR;
531                 _entJump = _clrJump = -1;
532         }
533         if(_activePage == _dir_page) {
534                 _dir_page->EntPressed();
535                 _mode = KLN89_MODE_DISP;
536                 _activePage = _pages[_curPage];
537         } else {
538                 _activePage->EntPressed();
539         }
540 }
541
542 void KLN89::ClrPressed() {
543         if(_clrJump >= 0) {
544                 _curPage = _clrJump;
545                 _activePage = _pages[(unsigned int)_clrJump];
546                 if(_jumpRestoreCrsr) _mode = KLN89_MODE_CRSR;
547                 _entJump = _clrJump = -1;
548         }
549         _activePage->ClrPressed();
550 }
551
552 void KLN89::DtoPressed() {
553         if(_activePage != _dir_page) {
554                 // Figure out which waypoint the dir page should display, according to the following rules:
555                 // 1. If the FPL 0 page is displayed AND the cursor is over one of the waypoints, display that waypoint.
556                 // 2. If the NAV 4 page is displayed with the inner knob pulled out, display the waypoint highlighted in the lower RH corner of the nav page.
557                 // 3. If any of APT, VOR, NDB, INT, USR or ACT pages is displayed then display the waypoint being viewed.
558                 // 4. If none of the above, display the active waypoint, unless the active waypoint is the MAP of an approach and it has been flown past 
559                 // (no waypoint sequence past the MAP), in which case display the first waypoint of the missed approach procedure.
560                 // 5. If none of the above (i.e. no active waypoint) then display blanks.
561                 if(_curPage <= 5) {
562                         // APT, VOR, NDB, INT, USR or ACT
563                         if(!_activePage->GetId().empty()) {     // Guard against no user waypoints defined
564                                 _dir_page->SetId(_activePage->GetId());
565                         } else {
566                                 _dir_page->SetId(_activeWaypoint.id);
567                         }
568                 } else if(_curPage == 6 && _activePage->GetSubPage() == 3 && fgGetBool("/instrumentation/kln89/scan-pull") && _activeFP->waypoints.size()) {
569                         // NAV 4
570                         _dir_page->SetId(((KLN89NavPage*)_activePage)->GetNav4WpId());
571                 } else if(_curPage == 7 && _activePage->GetSubPage() == 0 && _mode == KLN89_MODE_CRSR) {
572                         // FPL 0
573                         if(!_activePage->GetId().empty()) {
574                                 //cout << "Not empty!!!\n";
575                                 _dir_page->SetId(_activePage->GetId());
576                         } else {
577                                 //cout << "empty :-(\n";
578                                 _dir_page->SetId(_activeWaypoint.id);
579                         }
580                 } else {
581                         _dir_page->SetId(_activeWaypoint.id);
582                 }
583                 // This need to come after the bit before otherwise the FPL or NAV4 page clears their current ID when it looses focus.
584                 _activePage->LooseFocus();
585                 _activePage = _dir_page;
586                 _mode = KLN89_MODE_CRSR;
587         }
588 }
589
590 void KLN89::NrstPressed() {
591         if(_activePage != _nrst_page) {
592                 _activePage->LooseFocus();      // TODO - check whether we should call loose focus here
593                 _lastActivePage = _activePage;
594                 _activePage = _nrst_page;
595                 _lastMode = _mode;
596                 _mode = KLN89_MODE_CRSR;
597         } else {
598                 _activePage = _lastActivePage;
599                 _mode = _lastMode;
600         }
601 }
602         
603 void KLN89::AltPressed() {}
604
605 void KLN89::OBSPressed() {
606         ToggleOBSMode();
607         if(_obsMode) {
608                 // if(ORS 02)
609                 _mode = KLN89_MODE_CRSR;
610                 _activePage->OBSPressed();
611         }
612 }
613
614 void KLN89::MsgPressed() {
615         // TODO - handle persistent messages such as SUA alerting.
616         // (The message annunciation flashes before first view, but afterwards remains continuously lit with the message available
617         // until the potential conflict no longer pertains).
618         if(_dispMsg && _messageStack.size()) {
619                 _messageStack.pop_front();
620         }
621         _dispMsg = !_dispMsg;
622 }
623
624 void KLN89::ToggleOBSMode() {
625         DCLGPS::ToggleOBSMode();
626 }
627
628 void KLN89::DtoInitiate(const string& id) {
629         _dtoReview = false;
630         // Set the current page to NAV1
631         _curPage = 6;
632         _activePage = _pages[_curPage];
633         _activePage->SetSubPage(0);
634         // TODO - need to output a scratchpad message with the new course, but we don't know it yet!
635         // Call the base class to actually initiate the DTO.
636         DCLGPS::DtoInitiate(id);
637 }
638
639 void KLN89::SetMinDisplayBrightness(int n) {
640         _minDisplayBrightness = n;
641         if(_minDisplayBrightness < 1) _minDisplayBrightness = 1;
642         if(_minDisplayBrightness > 9) _minDisplayBrightness = 9;
643 }
644
645 void KLN89::DecrementMinDisplayBrightness() {
646         _minDisplayBrightness--;
647         if(_minDisplayBrightness < 1) _minDisplayBrightness = 1;
648 }
649
650 void KLN89::IncrementMinDisplayBrightness() {
651         _minDisplayBrightness++;
652         if(_minDisplayBrightness > 9) _minDisplayBrightness = 9;
653 }
654
655 void KLN89::DrawBar(int page) {
656         int px = 1 + (page * 15);
657         int py = 1;
658         for(int i=0; i<7; ++i) {
659                 // Ugh - this is crude and inefficient!
660                 _instrument->DrawPixel(px+i, py);
661                 _instrument->DrawPixel(px+i, py+1);
662         }
663 }
664
665 // Convert moving map to instrument co-ordinates
666 void KLN89::MapToInstrument(int &x, int &y) {
667         x += _xBorder + _xFieldBorder[2] + _xFieldStart[2];
668 }
669
670 // Draw a pixel specified in instrument co-ords, but clipped to the map region
671 //void KLN89::DrawInstrMapPixel(int x, int y) {
672
673 /*
674 // Clip, translate and draw a map pixel
675 // If we didn't need per-pixel clipping, it would be cheaper to translate object rather than pixel positions.
676 void KLN89::DrawMapPixel(int x, int y, bool invert) {
677         if(x < 0 || x > 111 || y < 0 || y > 39)  return;
678         x += _xBorder + _xFieldBorder[2] + _xFieldStart[2];
679         _instrument->DrawPixel(x, y, invert);
680 }
681 */
682
683 // HACK - use something FG provides
684 static double gps_min(const double &a, const double &b) {
685         return(a <= b ? a : b);
686 }
687
688 static double gps_max(const double &a, const double &b) {
689         return(a >= b ? a : b);
690 }
691
692 void KLN89::UpdateMapHeading() {
693         switch(_mapOrientation) {
694         case 0:         // North up
695                 _mapHeading = 0.0;
696                 break;
697         case 1:         // DTK up
698                 _mapHeading = _dtkTrue;
699                 break;
700         case 2:         // Track up
701                 _mapHeading = _track;
702                 break;
703         }
704 }               
705
706 // The screen area allocated to the moving map is 111 x 40 pixels.
707 // In North up mode, the user position marker is at 57, 20. (Map co-ords).
708 void KLN89::DrawMap(bool draw_avs) {
709         // Set the clipping region to the moving map part of the display
710         int xstart = _xBorder + _xFieldBorder[2] + _xFieldStart[2];
711         _instrument->SetClipRegion(xstart, 0, xstart + 110, 39);
712         
713         _mapScaleUnits = (int)_distUnits;
714         _mapScale = (double)(KLN89MapScales[_mapScaleUnits][_mapScaleIndex]);
715         
716         //cout << "Map scale = " << _mapScale << '\n';
717         
718         double mapScaleMeters = _mapScale * (_mapScaleUnits == 0 ? SG_NM_TO_METER : 1000);
719         
720         // TODO - use an aligned projection when either DTK or TK up!
721 #if ENABLE_ATCDCL
722         FGATCAlignedProjection mapProj(SGGeod::fromRad(_gpsLon, _gpsLat), _mapHeading);
723 #else   
724         FGKln89AlignedProjection mapProj(SGGeod::fromRad(_gpsLon, _gpsLat), _mapHeading);
725 #endif
726         double meter_per_pix = (_mapOrientation == 0 ? mapScaleMeters / 20.0f : mapScaleMeters / 29.0f);
727         SGGeod bottomLeft = mapProj.ConvertFromLocal(SGVec3d(gps_max(-57.0 * meter_per_pix, -50000), gps_max((_mapOrientation == 0 ? -20.0 * meter_per_pix : -11.0 * meter_per_pix), -25000), 0.0));
728         SGGeod topRight = mapProj.ConvertFromLocal(SGVec3d(gps_min(54.0 * meter_per_pix, 50000), gps_min((_mapOrientation == 0 ? 20.0 * meter_per_pix : 29.0 * meter_per_pix), 25000), 0.0));
729
730
731
732         
733         // Draw Airport labels first (but not one's that are waypoints)
734         // Draw Airports first (but not one's that are waypoints)
735         // Ditto for VORs (not sure if SUA/VOR/Airport ordering is important or not).
736         // Ditto for SUA
737         // Then flighttrack
738         // Then waypoints
739         // Then waypoint labels (not sure if this should be before or after waypoints)
740         // Then user pos.
741         // Annotation then gets drawn by Nav page, NOT this function.
742
743         if(_drawApt && draw_avs) {
744                 /*
745                 bool have_apt = _overlays->FindArpByRegion(&apt, bottomLeft.lat(), bottomLeft.lon(), topRight.lat(), topRight.lon());
746                 //cout << "Vors enclosed are: ";
747                 // Draw all the labels first...
748                 for(unsigned int i=0; i<apt.size(); ++i) {
749                         //cout << nav[i]->id << ' ';
750                         Point3D p = mapProj.ConvertToLocal(Point3D(apt[i]->lon * SG_RADIANS_TO_DEGREES, apt[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
751                         //cout << p << " .... ";
752                         int mx = int(p.x() / meter_per_pix) + 56;
753                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
754                         //cout << "mx = " << mx << ", my = " << my << '\n';
755                         bool right_align = (p.x() < 0.0);
756                         DrawLabel(apt[i]->id, mx + (right_align ? -2 : 3), my + (p.y() < 0.0 ? -7 : 3), right_align);
757                         // I think that we probably should have -1 in the right_align case above to match the real life instrument.
758                 }
759                 // ...and then all the Apts.
760                 for(unsigned int i=0; i<apt.size(); ++i) {
761                         //cout << nav[i]->id << ' ';
762                         Point3D p = mapProj.ConvertToLocal(Point3D(apt[i]->lon * SG_RADIANS_TO_DEGREES, apt[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
763                         //cout << p << " .... ";
764                         int mx = int(p.x() / meter_per_pix) + 56;
765                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
766                         //cout << "mx = " << mx << ", my = " << my << '\n';
767                         DrawApt(mx, my);
768                 }
769                 //cout << '\n';
770                 */
771         }
772         /*
773         if(_drawVOR && draw_avs) {
774                 Overlays::nav_array_type nav;
775                 bool have_vor = _overlays->FindVorByRegion(&nav, bottomLeft.lat(), bottomLeft.lon(), topRight.lat(), topRight.lon());
776                 //cout << "Vors enclosed are: ";
777                 // Draw all the labels first...
778                 for(unsigned int i=0; i<nav.size(); ++i) {
779                         //cout << nav[i]->id << ' ';
780                         Point3D p = mapProj.ConvertToLocal(Point3D(nav[i]->lon * SG_RADIANS_TO_DEGREES, nav[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
781                         //cout << p << " .... ";
782                         int mx = int(p.x() / meter_per_pix) + 56;
783                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
784                         //cout << "mx = " << mx << ", my = " << my << '\n';
785                         bool right_align = (p.x() < 0.0);
786                         DrawLabel(nav[i]->id, mx + (right_align ? -2 : 3), my + (p.y() < 0.0 ? -7 : 3), right_align);
787                         // I think that we probably should have -1 in the right_align case above to match the real life instrument.
788                 }
789                 // ...and then all the VORs.
790                 for(unsigned int i=0; i<nav.size(); ++i) {
791                         //cout << nav[i]->id << ' ';
792                         Point3D p = mapProj.ConvertToLocal(Point3D(nav[i]->lon * SG_RADIANS_TO_DEGREES, nav[i]->lat * SG_RADIANS_TO_DEGREES, 0.0));
793                         //cout << p << " .... ";
794                         int mx = int(p.x() / meter_per_pix) + 56;
795                         int my = int(p.y() / meter_per_pix) + (_mapOrientation == 0 ? 19 : 10);
796                         //cout << "mx = " << mx << ", my = " << my << '\n';
797                         DrawVOR(mx, my);
798                 }
799                 //cout << '\n';
800         }
801         */
802         
803         // FlightTrack
804         if(_activeFP->waypoints.size() > 1) {
805                 vector<int> xvec, yvec, qvec;   // qvec stores the quadrant that each waypoint label should
806                                                                                 // be drawn in (relative to the waypoint). 
807                                                                                 // 1 = NE, 2 = SE, 3 = SW, 4 = NW.
808                 double save_h = 0.0; // Each pass, save a heading from the previous one for label quadrant determination.
809                 bool drawTrack = true;
810                 for(unsigned int i=1; i<_activeFP->waypoints.size(); ++i) {
811                         GPSWaypoint* wp0 = _activeFP->waypoints[i-1];
812                         GPSWaypoint* wp1 = _activeFP->waypoints[i];
813                         SGVec3d p0 = mapProj.ConvertToLocal(SGGeod::fromRad(wp0->lon, wp0->lat));
814                         SGVec3d p1 = mapProj.ConvertToLocal(SGGeod::fromRad(wp1->lon, wp1->lat));
815                         int mx0 = int(p0.x() / meter_per_pix + 0.5) + 56;
816                         int my0 = int(p0.y() / meter_per_pix + 0.5) + (_mapOrientation == 0 ? 19 : 10);
817                         int mx1 = int(p1.x() / meter_per_pix + 0.5) + 56;
818                         int my1 = int(p1.y() / meter_per_pix + 0.5) + (_mapOrientation == 0 ? 19 : 10);
819                         if(i == 1) {
820                                 xvec.push_back(mx0);
821                                 yvec.push_back(my0);
822                                 double h = GetGreatCircleCourse(wp0->lat, wp0->lon, wp1->lat, wp1->lon) * SG_RADIANS_TO_DEGREES;
823                                 // Adjust for map orientation
824                                 h -= _mapHeading;
825                                 qvec.push_back(GetLabelQuadrant(h));
826                                 //cout << "i = " << i << ", h = " << h << ", qvec[0] = " << qvec[0] << '\n';
827                         }
828                         xvec.push_back(mx1);
829                         yvec.push_back(my1);
830                         if(drawTrack) { DrawLine(mx0, my0, mx1, my1); }
831                         if(i != 1) {
832                                 double h = GetGreatCircleCourse(wp0->lat, wp0->lon, wp1->lat, wp1->lon) * SG_RADIANS_TO_DEGREES;
833                                 // Adjust for map orientation
834                                 h -= _mapHeading;
835                                 qvec.push_back(GetLabelQuadrant(save_h, h));
836                         }
837                         save_h = GetGreatCircleCourse(wp1->lat, wp1->lon, wp0->lat, wp0->lon) * SG_RADIANS_TO_DEGREES;
838                         // Adjust for map orientation
839                         save_h -= _mapHeading;
840                         if(i == _activeFP->waypoints.size() - 1) {
841                                 qvec.push_back(GetLabelQuadrant(save_h));
842                         }
843                         // Don't draw flight track beyond the missed approach point of an approach
844                         if(_approachLoaded) {
845                                 //cout << "Waypoints are " << wp0->id << " and " << wp1->id << '\n';
846                                 //cout << "Types are " << wp0->appType << " and " << wp1->appType << '\n';
847                                 if(wp1->appType == GPS_MAP) {
848                                         drawTrack = false;
849                                 }
850                         }
851                 }
852                 // ASSERT(xvec.size() == yvec.size() == qvec.size() == _activeFP->waypoints.size());
853                 for(unsigned int i=0; i<xvec.size(); ++i) {
854                         DrawWaypoint(xvec[i], yvec[i]);
855                         bool right_align = (qvec[i] > 2);
856                         bool top = (qvec[i] == 1 || qvec[i] == 4);
857                         // TODO - not sure if labels should be drawn in sequence with waypoints and flightpaths,
858                         // or all before or all afterwards.  Doesn't matter a huge deal though.
859                         DrawLabel(_activeFP->waypoints[i]->id, xvec[i] + (right_align ? -2 : 3), yvec[i] + (top ? 3 : -7), right_align);
860                 }
861         }
862         
863         // User pos
864         if(_mapOrientation == 0) {
865                 // North up
866                 DrawUser1(56, 19);
867         } else if(_mapOrientation == 1) {
868                 // DTK up
869                 DrawUser1(56, 10);
870         } else if(_mapOrientation == 2) {
871                 // TK up
872                 DrawUser2(56, 10);
873         } else {
874                 // Heading up
875                 // TODO - don't know what to do here!
876         }
877         
878         // And finally, reset the clip region to stop the rest of the code going pear-shaped!
879         _instrument->ResetClipRegion();
880 }
881
882 // Get the quadrant to draw the label of the start or end waypoint (i.e. one with only one track from it).
883 // Heading specified FROM the waypoint.
884 // 4 | 1
885 // -----
886 // 3 | 2
887 int KLN89::GetLabelQuadrant(double h) {
888         while(h < 0.0) h += 360.0;
889         while(h > 360.0) h -= 360.0;
890         if(h < 90.0) return(3);
891         if(h < 180.0) return(4);
892         if(h < 270.0) return(1);
893         return(2);
894 }
895
896 // Get the quadrant to draw the label of an en-route waypoint,
897 // with BOTH tracks specified as headings FROM the waypoint.
898 // 4 | 1
899 // -----
900 // 3 | 2
901 int KLN89::GetLabelQuadrant(double h1, double h2) {
902         while(h1 < 0.0) h1 += 360.0;
903         while(h1 > 360.0) h1 -= 360.0;
904         while(h2 < 0.0) h2 += 360.0;
905         while(h2 > 360.0) h2 -= 360.0;
906         double max_min_diff = 0.0;
907         int quad = 1;
908         for(int i=0; i<4; ++i) {
909                 double h = 45 + (90 * i);
910                 double diff1 = fabs(h - h1);
911                 if(diff1 > 180) diff1 = 360 - diff1;
912                 double diff2 = fabs(h - h2);
913                 if(diff2 > 180) diff2 = 360 - diff2;
914                 double min_diff = gps_min(diff1, diff2);
915                 if(min_diff > max_min_diff) {
916                         max_min_diff = min_diff;
917                         quad = i + 1;
918                 }
919         }
920         //cout << "GetLabelQuadrant, h1 = " << h1 << ", h2 = " << h2 << ", quad = " << quad << '\n';
921         return(quad);
922 }
923
924 // Draw the diamond style of user pos
925 // 
926 //    o
927 //   oxo
928 //  oxxxo
929 // oxxxxxo
930 //  oxxxo
931 //   oxo
932 //    o
933 // 
934 void KLN89::DrawUser1(int x, int y) {
935         MapToInstrument(x, y);
936         int min_j = 0, max_j = 0;
937         for(int i=-3; i<=3; ++i) {
938                 for(int j=min_j; j<=max_j; ++j) {
939                         _instrument->DrawPixel(x+j, y+i, (j == min_j || j == max_j ? true : false));
940                 }
941                 if(i < 0) {
942                         min_j--;
943                         max_j++;
944                 } else {
945                         min_j++;
946                         max_j--;
947                 }
948         }
949 }
950
951 // Draw the airplane style of user pos
952 // Define the origin to be the midpoint of the *fuselage*
953 void KLN89::DrawUser2(int x, int y) {
954         MapToInstrument(x, y);
955         
956         // Draw the background as three black quads first
957         _instrument->DrawQuad(x-2, y-3, x+2, y-1, true);
958         _instrument->DrawQuad(x-3, y, x+3, y+2, true);
959         _instrument->DrawQuad(x-1, y+3, x+1, y+3, true);
960         
961         if(_pixelated) {
962                 for(int j=y-2; j<=y+2; ++j) {
963                         _instrument->DrawPixel(x, j);
964                 }
965                 for(int i=x-1; i<=x+1; ++i) {
966                         _instrument->DrawPixel(i, y-2);
967                 }
968                 for(int i=x-2; i<=x+2; ++i) {
969                         _instrument->DrawPixel(i, y+1);
970                 }
971         } else {
972                 _instrument->DrawQuad(x, y-2, x, y+2);
973                 _instrument->DrawQuad(x-1, y-2, x+1, y-2);
974                 _instrument->DrawQuad(x-2, y+1, x+2, y+1);
975         }
976 }
977
978 // Draw an airport symbol on the moving map
979 //
980 //  ooo
981 // ooxoo
982 // oxxxo
983 // ooxoo
984 //  ooo
985 //
986 void KLN89::DrawApt(int x, int y) {
987         MapToInstrument(x, y);
988         
989         int j = y-2;
990         int i;
991         for(i=x-1; i<=x+1; ++i) _instrument->DrawPixel(i, j, true);
992         ++j;
993         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (i != x ? true : false));
994         ++j;
995         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (abs(i - x) > 1 ? true : false));
996         ++j;
997         for(i=x-2; i<=x+2; ++i) _instrument->DrawPixel(i, j, (i != x ? true : false));
998         ++j;
999         for(i=x-1; i<=x+1; ++i) _instrument->DrawPixel(i, j, true);
1000 }
1001
1002 // Draw a waypoint on the moving map
1003 //
1004 // ooooo
1005 // oxxxo
1006 // oxxxo
1007 // oxxxo
1008 // ooooo
1009 //
1010 void KLN89::DrawWaypoint(int x, int y) {
1011         MapToInstrument(x, y);
1012         _instrument->SetDebugging(true);
1013         
1014         // Draw black background
1015         _instrument->DrawQuad(x-2, y-2, x+2, y+2, true);
1016         
1017         // Draw the coloured square
1018         if(_pixelated) {
1019                 for(int i=x-1; i<=x+1; ++i) {
1020                         for(int j=y-1; j<=y+1; ++j) {
1021                                 _instrument->DrawPixel(i, j);
1022                         }
1023                 }
1024         } else {
1025                 _instrument->DrawQuad(x-1, y-1, x+1, y+1);
1026         }
1027         _instrument->SetDebugging(false);
1028 }
1029
1030 // Draw a VOR on the moving map
1031 //
1032 // ooooo
1033 // oxxxo
1034 // oxoxo
1035 // oxxxo
1036 // ooooo
1037 //
1038 void KLN89::DrawVOR(int x, int y) {
1039         // Cheat - draw a waypoint and then a black pixel in the middle.
1040         // Need to call Waypoint draw *before* translating co-ords.
1041         DrawWaypoint(x, y);
1042         MapToInstrument(x, y);
1043         _instrument->DrawPixel(x, y, true);
1044 }
1045
1046 // Draw a line on the moving map
1047 void KLN89::DrawLine(int x1, int y1, int x2, int y2) {
1048         MapToInstrument(x1, y1);
1049         MapToInstrument(x2, y2);
1050         _instrument->DrawLine(x1, y1, x2, y2);
1051 }
1052
1053 void KLN89::DrawMapUpArrow(int x, int y) {
1054         MapToInstrument(x, y);
1055         if(_pixelated) {
1056                 for(int j=0; j<7; ++j) {
1057                         _instrument->DrawPixel(x + 2, y + j);
1058                 }
1059         } else {
1060                 _instrument->DrawQuad(x+2, y, x+2, y+6);
1061         }
1062         _instrument->DrawPixel(x, y+4);
1063         _instrument->DrawPixel(x+1, y+5);
1064         _instrument->DrawPixel(x+3, y+5);
1065         _instrument->DrawPixel(x+4, y+4);
1066 }
1067
1068 // Draw a quad on the moving map
1069 void KLN89::DrawMapQuad(int x1, int y1, int x2, int y2, bool invert) {
1070         MapToInstrument(x1, y1);
1071         MapToInstrument(x2, y2);
1072         _instrument->DrawQuad(x1, y1, x2, y2, invert);
1073 }
1074
1075 // Draw an airport or waypoint label on the moving map
1076 // Specify position by the map pixel co-ordinate of the left or right, bottom, of the *visible* portion of the label.
1077 // The black background quad will automatically overlap this by 1 pixel.
1078 void KLN89::DrawLabel(const string& s, int x1, int y1, bool right_align) {
1079         MapToInstrument(x1, y1);
1080         if(!right_align) {
1081                 for(unsigned int i=0; i<s.size(); ++i) {
1082                         char c = s[i];
1083                         x1 += DrawSmallChar(c, x1, y1);
1084                         x1 ++;
1085                 }
1086         } else {
1087                 for(int i=(int)(s.size()-1); i>=0; --i) {
1088                         char c = s[i];
1089                         x1 -= DrawSmallChar(c, x1, y1, right_align);
1090                         x1--;
1091                 }
1092         }
1093 }
1094
1095 void KLN89::DrawCDI() {
1096         // Scale
1097         for(int i=0; i<5; ++i) {
1098                 DrawSpecialChar(2, 2, 3+i, 2);
1099                 DrawSpecialChar(1, 2, 9+i, 2);
1100         }
1101         
1102         int field = 2;
1103         int px = 8 * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field] + 2;
1104         int py = 2 * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1105         
1106         // Deflection bar
1107         // Every 7 pixels deflection left or right is one dot on the scale, and hence 1/5 FSD.
1108         // Maximum deflection is 37 pixels left, or 38 pixels right !?!
1109         double xtd = CalcCrossTrackDeviation();
1110         int deflect;
1111         if(_cdiScaleTransition) {
1112                 double dots = (xtd / _currentCdiScale) * 5.0;
1113                 deflect = (int)(dots * 7.0 * -1.0);
1114                 // TODO - for all these I think I should add 0.5 before casting to int, and *then* multiply by -1.  Possibly!
1115         } else {
1116                 if(0 == _currentCdiScaleIndex) {        // 5.0nm FSD => 1 nm per dot => 7 pixels per nm.
1117                         deflect = (int)(xtd * 7.0 * -1.0);      // The -1.0 is because we move the 'needle' indicating the course, not the plane.
1118                 } else if(1 == _currentCdiScaleIndex) {
1119                         deflect = (int)(xtd * 35.0 * -1.0);
1120                 } else {        // 0.3 == _cdiScale
1121                         deflect = (int)(xtd * 116.6666666667 * -1.0);
1122                 }
1123         }
1124         if(deflect > 38) deflect = 38;
1125         if(deflect < -37) deflect = -37;
1126         if(_pixelated) {
1127                 for(int j=0; j<9; ++j) {
1128                         _instrument->DrawPixel(px + deflect, py+j);
1129                         _instrument->DrawPixel(px + deflect + 1, py+j);
1130                 }
1131         } else {
1132                 _instrument->DrawQuad(px + deflect, py, px + deflect + 1, py + 8);
1133         }
1134         
1135         // To/From indicator
1136         px-=4;
1137         py+=2;
1138         for(int j=4; j>=0; --j) {
1139                 int k = 10 - (2*j);
1140                 for(int i=0; i<k; ++i) {                
1141                         _instrument->DrawPixel(px+j+i, (_headingBugTo ? py+j : py+4-j));
1142                         // At the extremities, draw the outlining dark pixel
1143                         if(i == 0 || i == k-1) {
1144                                 _instrument->DrawPixel(px+j+i, (_headingBugTo ? py+j+1 : py+3-j), true);
1145                         }
1146                 }
1147         }
1148 }
1149
1150 void KLN89::DrawLegTail(int py) {
1151         int px = 0 * 7 + _xBorder + _xFieldBorder[2] + _xFieldStart[2];
1152         py = py * 9 + _yBorder + _yFieldBorder[2] + _yFieldStart[2];
1153         
1154         px++;
1155         py+=3;
1156         py++;   // Hack - not sure if this represents a border issue.
1157         
1158         for(int i=0; i<9; ++i) _instrument->DrawPixel(px, py+i);
1159         for(int i2=0; i2<5; ++i2) _instrument->DrawPixel(px+i2, py+9);
1160 }
1161
1162 void KLN89::DrawLongLegTail(int py) {
1163         int px = 0 * 7 + _xBorder + _xFieldBorder[2] + _xFieldStart[2];
1164         py = py * 9 + _yBorder + _yFieldBorder[2] + _yFieldStart[2];
1165         
1166         px++;
1167         py+=3;
1168         py++;   // Hack - not sure if this represents a border issue.
1169         
1170         for(int i=0; i<18; ++i) _instrument->DrawPixel(px, py+i);
1171         for(int i2=0; i2<5; ++i2) _instrument->DrawPixel(px+i2, py+18);
1172 }
1173
1174 void KLN89::DrawHalfLegTail(int py) {
1175 }
1176
1177 void KLN89::DrawDivider() {
1178         int px = _xFieldStart[2] - 1;
1179         int py = _yBorder;
1180         for(int i=0; i<36; ++i) {
1181                 _instrument->DrawPixel(px, py+i);
1182         }
1183 }
1184
1185 void KLN89::DrawEnt(int field, int px, int py) {
1186         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1187         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field] + 1;
1188         
1189         px++;   // Not sure why we need px++, but it seems to work!
1190         py++;
1191         
1192         // E
1193         for(int i=0; i<5; ++i) _instrument->DrawPixel(px, py+i);
1194         _instrument->DrawPixel(px+1, py);
1195         _instrument->DrawPixel(px+2, py);
1196         _instrument->DrawPixel(px+1, py+2);
1197         _instrument->DrawPixel(px+1, py+4);
1198         _instrument->DrawPixel(px+2, py+4);
1199         
1200         px += 4;
1201         // N
1202         for(int i=0; i<4; ++i) _instrument->DrawPixel(px, py+i);
1203         _instrument->DrawPixel(px+1, py+2);
1204         _instrument->DrawPixel(px+2, py+1);
1205         for(int i=0; i<4; ++i) _instrument->DrawPixel(px+3, py+i);
1206         
1207         px += 5;
1208         // T
1209         _instrument->DrawPixel(px, py+3);
1210         for(int i=0; i<4; ++i) _instrument->DrawPixel(px+1, py+i);
1211         _instrument->DrawPixel(px+2, py+3);
1212 }
1213
1214 void KLN89::DrawMessageAlert() {
1215         // TODO - draw the proper message indicator
1216         if(!_blink) {
1217                 int px = _xBorder + _xFieldBorder[1] + _xFieldStart[1];
1218                 int py = 1 * 9 + _yBorder + _yFieldBorder[1] + _yFieldStart[1] + 1;
1219                 
1220                 px++;   // Not sure why we need px++, but it seems to work!
1221                 py++;
1222
1223                 DrawText("  ", 1, 0, 1, false, 99);
1224                 _instrument->DrawQuad(px+1, py-1, px+2, py+5, true);
1225                 _instrument->DrawQuad(px+3, py+3, px+3, py+5, true);
1226                 _instrument->DrawQuad(px+4, py+2, px+4, py+4, true);
1227                 _instrument->DrawQuad(px+5, py+1, px+6, py+3, true);
1228                 _instrument->DrawQuad(px+7, py+2, px+7, py+4, true);
1229                 _instrument->DrawQuad(px+8, py+3, px+8, py+5, true);
1230                 _instrument->DrawQuad(px+9, py-1, px+10, py+5, true);
1231         }
1232 }
1233
1234 void KLN89::Underline(int field, int px, int py, int len) {
1235         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1236         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1237         for(int i=0; i<(len*7); ++i) {
1238                 _instrument->DrawPixel(px, py);
1239                 ++px;
1240         }
1241 }
1242
1243 void KLN89::DrawKPH(int field, int cx, int cy) {
1244         // Add some border
1245         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1246         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1247         
1248         px++;
1249         py++;
1250         
1251         for(int j=0; j<=4; ++j) {
1252                 _instrument->DrawPixel(px, py + 2 +j);
1253                 _instrument->DrawPixel(px + 8, py + j);
1254                 if(j <= 1) {
1255                         _instrument->DrawPixel(px + 11, py + j);
1256                         _instrument->DrawPixel(px + 9 + j, py + 2);
1257                 }
1258         }
1259         
1260         for(int i=0; i<=6; ++i) {
1261                 if(i <= 2) {
1262                         _instrument->DrawPixel(px + 1 + i, py + 4 + i);
1263                         _instrument->DrawPixel(px + 1 + i, py + (4 - i));
1264                 }
1265                 _instrument->DrawPixel(px + 2 + i, py + i);
1266         }
1267 }
1268
1269 void KLN89::DrawDTO(int field, int cx, int cy) {
1270         DrawSpecialChar(6, field, cx, cy);
1271         if(!(_waypointAlert && _blink)) {
1272                 DrawSpecialChar(3, field, cx+1, cy);
1273         }
1274         
1275         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1276         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1277         
1278         px++;
1279         py++;
1280         
1281         // Fill in the gap between the 'D' and the arrow.
1282         _instrument->DrawPixel(px+5, py+3);
1283 }
1284
1285 // Takes character position
1286 void KLN89::DrawChar(char c, int field, int px, int py, bool bold, bool invert) {
1287         // Ignore field for now
1288         // Add some border
1289         px = px * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1290         py = py * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1291         
1292         // Draw an orange background for inverted characters
1293         if(invert) {
1294                 for(int i=0; i<7; ++i) {
1295                         for(int j=0; j<9; ++j) {
1296                                 _instrument->DrawPixel(px + i, py + j);
1297                         }
1298                 }
1299         }
1300                                 
1301         if(c < 33) return;  // space
1302         
1303         // Render normal decimal points in bold floats
1304         if(c == '.') bold = false;
1305         
1306         ++py;   // Shift the char up by one pixel
1307         for(int j=7; j>=0; --j) {
1308                 char c1 = (bold ? NumbersBold[c-48][j] : UpperAlpha[c-33][j]);
1309                 // Don't do the last column for now (ie. j = 1, not 0)
1310                 for(int i=5; i>=0; --i) {
1311                         if(c1 & (01 << i)) {
1312                                 _instrument->DrawPixel(px, py, invert);
1313                         }
1314                         ++px;
1315                 }
1316                 px -= 6;
1317                 ++py;
1318         }
1319 }
1320
1321 // Takes pixel position
1322 void KLN89::DrawFreeChar(char c, int x, int y, bool draw_background) {
1323         
1324         if(draw_background) {
1325                 _instrument->DrawQuad(x, y, x+6, y+8, true);
1326         }               
1327                                 
1328         if(c < 33) return;  // space
1329         
1330         ++y;    // Shift the char up by one pixel
1331         for(int j=7; j>=0; --j) {
1332                 char c1 = UpperAlpha[c-33][j];
1333                 // Don't do the last column for now (ie. j = 1, not 0)
1334                 for(int i=5; i>=0; --i) {
1335                         if(c1 & (01 << i)) {
1336                                 _instrument->DrawPixel(x, y);
1337                         }
1338                         ++x;
1339                 }
1340                 x -= 6;
1341                 ++y;
1342         }
1343 }
1344
1345 // Takes instrument pixel co-ordinates.
1346 // Position is specified by the bottom of the *visible* portion, by default the left position unless align_right is true.
1347 // The return value is the pixel width of the visible portion
1348 int KLN89::DrawSmallChar(char c, int x, int y, bool align_right) {
1349         // calculate the index into the SmallChar array
1350         int idx;
1351         if(c > 47 && c < 58) {
1352                 // number
1353                 idx = c - 48;
1354         } else if(c > 64 && c < 91) {
1355                 // Uppercase letter
1356                 idx = c - 55;
1357         } else {
1358                 return(0);
1359         }
1360         
1361         char n = SmallChar[idx][0];             // Width of visible portion
1362         if(align_right) x -= n;
1363         
1364         // background
1365         _instrument->DrawQuad(x - 1, y - 1, x + n, y + 5, true);
1366         
1367         for(int j=7; j>=3; --j) {
1368                 char c1 = SmallChar[idx][j];
1369                 for(int i=n-1; i>=0; --i) {
1370                         if(c1 & (01 << i)) {
1371                                 _instrument->DrawPixel(x, y);
1372                         }
1373                         ++x;
1374                 }
1375                 x -= n;
1376                 ++y;
1377         }
1378         
1379         return(n);
1380 }
1381
1382 // Takes character position
1383 void KLN89::DrawSpecialChar(char c, int field, int cx, int cy, bool bold) {
1384         if(c > 7) {
1385                 cout << "ERROR - requested special char outside array bounds!\n";
1386                 return;  // Increment this as SpecialChar grows
1387         }
1388         
1389         // Convert character to pixel position.
1390         // Ignore field for now
1391         // Add some border
1392         int px = cx * 7 + _xBorder + _xFieldBorder[field] + _xFieldStart[field];
1393         int py = cy * 9 + _yBorder + _yFieldBorder[field] + _yFieldStart[field];
1394         ++py;   // Total hack - the special chars were coming out 1 pixel too low!
1395         for(int i=7; i>=0; --i) {
1396                 char c1 = SpecialChar[(int)c][i];
1397                 // Don't do the last column for now (ie. j = 1, not 0)
1398                 for(int j=5; j>=0; --j) {
1399                         if(c1 & (01 << j)) {
1400                                 _instrument->DrawPixel(px, py);
1401                         }
1402                         ++px;
1403                 }
1404                 px -= 6;
1405                 ++py;
1406         }
1407 }
1408
1409 void KLN89::DrawText(const string& s, int field, int px, int py, bool bold, int invert) {
1410         for(int i = 0; i < (int)s.size(); ++i) {
1411                 DrawChar(s[(unsigned int)i], field, px+i, py, bold, (invert == i || invert == 99));
1412         }
1413 }
1414
1415 void KLN89::DrawMapText(const string& s, int x, int y, bool draw_background) {
1416         MapToInstrument(x, y);
1417         if(draw_background) {
1418                 //_instrument->DrawQuad(x, y, x + (7 * s.size()) - 1, y + 8, true);
1419                 _instrument->DrawQuad(x - 1, y, x + (7 * s.size()) - 2, y + 8, true);
1420                 // The minus 1 and minus 2 are an ugly hack to disguise the fact that I've lost track of exactly what's going on!
1421         }
1422         
1423         for(int i = 0; i < (int)s.size(); ++i) {
1424                 DrawFreeChar(s[(unsigned int)i], x+(i * 7)-1, y);
1425         }
1426 }
1427
1428 void KLN89::DrawLatitude(double d, int field, int px, int py) {
1429         DrawChar((d >= 0 ? 'N' : 'S'), field, px, py);
1430         d = fabs(d);
1431         px += 1;
1432         // TODO - sanity check input to ensure major lat field can only ever by 2 chars wide
1433         char buf[8];
1434         // Don't know whether to zero pad the below for single digits or not?
1435         //cout << d << ", " << (int)d << '\n';
1436         // 3 not 2 in size before for trailing \0
1437         int n = snprintf(buf, 3, "%i", (int)d);
1438         string s = buf;
1439         //cout << s << "... " << n << '\n';
1440         DrawText(s, field, px+(3-n), py);
1441         n = snprintf(buf, 7, "%05.2f'", ((double)(d - (int)d)) * 60.0f);
1442         s = buf;
1443         px += 3;
1444         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1445         px++;
1446         DrawText(s, field, px, py);
1447 }
1448
1449 void KLN89::DrawLongitude(double d, int field, int px, int py) {
1450         DrawChar((d >= 0 ? 'E' : 'W'), field, px, py);
1451         d = fabs(d);
1452         px += 1;
1453         // TODO - sanity check input to ensure major lat field can only ever be 2 chars wide
1454         char buf[8];
1455         // Don't know whether to zero pad the below for single digits or not?
1456         //cout << d << ", " << (int)d << '\n';
1457         // 4 not 3 in size before for trailing \0
1458         int n = snprintf(buf, 4, "%i", (int)d);
1459         string s = buf;
1460         //cout << s << "... " << n << '\n';
1461         DrawText(s, field, px+(3-n), py);
1462         n = snprintf(buf, 7, "%05.2f'", ((double)(d - (int)d)) * 60.0f);
1463         s = buf;
1464         px += 3;
1465         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1466         px++;
1467         DrawText(s, field, px, py);
1468 }
1469
1470 void KLN89::DrawFreq(double d, int field, int px, int py) {
1471         if(d >= 1000) d /= 100.0f;
1472         char buf[8];
1473         snprintf(buf, 7, "%6.2f", d);
1474         string s = buf;
1475         DrawText(s, field, px, py);
1476 }
1477
1478 void KLN89::DrawTime(double time, int field, int px, int py) {
1479         int hrs = (int)(time / 3600);
1480         int mins = (int)(ceil((time - (hrs * 3600)) / 60.0));
1481         char buf[10];
1482         int n;
1483         if(time >= 60.0) {
1484                 // Draw hr:min
1485                 n = snprintf(buf, 9, "%i:%02i", hrs, mins);
1486         } else {
1487                 // Draw :secs
1488                 n = snprintf(buf, 4, ":%02i", (int)time);
1489         }
1490         string s = buf;
1491         DrawText(s, field, px - n + 1, py);
1492 }
1493
1494 void KLN89::DrawHeading(int h, int field, int px, int py) {
1495         char buf[4];
1496         snprintf(buf, 4, "%i", h);
1497         string s = buf;
1498         DrawText(s, field, px - s.size(), py);
1499         DrawSpecialChar(0, field, px, py);      // Degrees symbol
1500 }
1501
1502 void KLN89::DrawDist(double d, int field, int px, int py) {
1503         d *= (_distUnits == GPS_DIST_UNITS_NM ? 1.0 : SG_NM_TO_METER * 0.001);
1504         char buf[10];
1505         snprintf(buf, 9, "%i", (int)(d + 0.5));
1506         string s = buf;
1507         s += (_distUnits == GPS_DIST_UNITS_NM ? "nm" : "Km");
1508         DrawText(s, field, px - s.size() + 1, py);
1509 }
1510
1511 void KLN89::DrawSpeed(double v, int field, int px, int py, int decimal) {
1512         // TODO - implement variable decimal places
1513         v *= (_velUnits == GPS_VEL_UNITS_KT ? 1.0 : 0.51444444444 * 0.001 * 3600.0);
1514         char buf[10];
1515         snprintf(buf, 9, "%i", (int)(v + 0.5));
1516         string s = buf;
1517         if(_velUnits == GPS_VEL_UNITS_KT) {
1518                 s += "kt";
1519                 DrawText(s, field, px - s.size() + 1, py);
1520         } else {
1521                 DrawText(s, field, px - s.size() - 1, py);
1522                 DrawKPH(field, px - 1, py);
1523         }
1524 }
1525
1526 void KLN89::DrawDirDistField(double lat, double lon, int field, int px, int py, bool to_flag, bool cursel) {
1527         DrawChar('>', field, px, py);
1528         char buf[8];
1529         double h;
1530         if(to_flag) {
1531                 h = GetMagHeadingFromTo(_gpsLat, _gpsLon, lat, lon);
1532         } else {
1533                 h = GetMagHeadingFromTo(lat, lon, _gpsLat, _gpsLon);
1534         }
1535         while(h < 0.0) h += 360.0;
1536         while(h > 360.0) h -= 360.0;
1537         snprintf(buf, 4, "%3i", (int)(h + 0.5));
1538         string s = buf;
1539         if(!(cursel && _blink)) { 
1540                 DrawText(s, field, px + 4 - s.size(), py);
1541                 DrawSpecialChar(0, field, px+4, py);
1542                 DrawText((to_flag ? "To" : "Fr"), field, px+5, py);
1543                 if(cursel) Underline(field, px + 1, py, 6);
1544         }
1545         //double d = GetHorizontalSeparation(_gpsLat, _gpsLon, lat, lon);
1546         //d *= (_distUnits == GPS_DIST_UNITS_NM ? SG_METER_TO_NM : 0.001);
1547         double d = GetGreatCircleDistance(_gpsLat, _gpsLon, lat, lon);
1548         d *= (_distUnits == GPS_DIST_UNITS_NM ? 1.0 : SG_NM_TO_METER * 0.001);
1549         if(d >= 100.0) {
1550                 snprintf(buf, 7, "%5i", (int)(d + 0.5));
1551         } else {
1552                 snprintf(buf, 7, "%4.1f", d);
1553         }
1554         s = buf;
1555         DrawText(s, field, px + 12 - s.size(), py);
1556         DrawText((_distUnits == GPS_DIST_UNITS_NM ? "nm" : "Km"), field, px + 12, py);
1557 }
1558
1559 char KLN89::IncChar(char c, bool gap, bool wrap) {
1560         if(c == '9') return(wrap ? (gap ? ' ' : 'A') : '9');
1561         if(c == 'Z') return('0');
1562         if(c == ' ') return('A');
1563         return(c + 1);
1564 }
1565
1566 char KLN89::DecChar(char c, bool gap, bool wrap) {
1567         if(c == 'A') return(wrap ? (gap ? ' ' : '9') : 'A');
1568         if(c == '0') return('Z');
1569         if(c == ' ') return('9');
1570         return(c - 1);
1571 }