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