]> git.mxchange.org Git - flightgear.git/blob - src/GUI/MapWidget.cxx
249605c6bfe7f9ac9859cf76c71e0e49a51ac5ed
[flightgear.git] / src / GUI / MapWidget.cxx
1 #ifdef HAVE_CONFIG_H
2 #  include "config.h"
3 #endif
4
5 #include "MapWidget.hxx"
6
7 #include <sstream>
8 #include <algorithm> // for std::sort
9 #include <plib/puAux.h>
10
11 #include <simgear/sg_inlines.h>
12 #include <simgear/misc/strutils.hxx>
13 #include <simgear/magvar/magvar.hxx>
14 #include <simgear/timing/sg_time.hxx> // for magVar julianDate
15 #include <simgear/structure/exception.hxx>
16
17 #include <Main/globals.hxx>
18 #include <Main/fg_props.hxx>
19 #include <Autopilot/route_mgr.hxx>
20 #include <Navaids/positioned.hxx>
21 #include <Navaids/navrecord.hxx>
22 #include <Navaids/navlist.hxx>
23 #include <Navaids/fix.hxx>
24 #include <Airports/airport.hxx>
25 #include <Airports/runways.hxx>
26 #include <Main/fg_os.hxx>      // fgGetKeyModifiers()
27 #include <Navaids/routePath.hxx>
28 #include <Aircraft/FlightHistory.hxx>
29
30 const char* RULER_LEGEND_KEY = "ruler-legend";
31
32 /* equatorial and polar earth radius */
33 const float rec  = 6378137;          // earth radius, equator (?)
34 const float rpol = 6356752.314f;      // earth radius, polar   (?)
35
36 /************************************************************************
37   some trigonometric helper functions
38   (translated more or less directly from Alexei Novikovs perl original)
39 *************************************************************************/
40
41 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
42 static float earth_radius_lat( float lat )
43 {
44   double a = cos(lat)/rec;
45   double b = sin(lat)/rpol;
46   return 1.0f / sqrt( a * a + b * b );
47 }
48
49 ///////////////////////////////////////////////////////////////////////////
50
51 static puBox makePuBox(int x, int y, int w, int h)
52 {
53   puBox r;
54   r.min[0] = x;
55   r.min[1] = y;
56   r.max[0] =  x + w;
57   r.max[1] = y + h;
58   return r;
59 }
60
61 static bool puBoxIntersect(const puBox& a, const puBox& b)
62 {
63   int x0 = SG_MAX2(a.min[0], b.min[0]);
64   int y0 = SG_MAX2(a.min[1], b.min[1]);
65   int x1 = SG_MIN2(a.max[0], b.max[0]);
66   int y1 = SG_MIN2(a.max[1], b.max[1]);
67
68   return (x0 <= x1) && (y0 <= y1);
69 }
70
71 class MapData;
72 typedef std::vector<MapData*> MapDataVec;
73
74 class MapData
75 {
76 public:
77   static const int HALIGN_LEFT = 1;
78   static const int HALIGN_CENTER = 2;
79   static const int HALIGN_RIGHT = 3;
80
81   static const int VALIGN_TOP = 1 << 4;
82   static const int VALIGN_CENTER = 2 << 4;
83   static const int VALIGN_BOTTOM = 3 << 4;
84
85   MapData(int priority) :
86     _dirtyText(true),
87     _age(0),
88     _priority(priority),
89     _width(0),
90     _height(0),
91     _offsetDir(HALIGN_LEFT | VALIGN_CENTER),
92     _offsetPx(10),
93     _dataVisible(false)
94   {
95   }
96
97   void setLabel(const std::string& label)
98   {
99     if (label == _label) {
100       return; // common case, and saves invalidation
101     }
102
103     _label = label;
104     _dirtyText = true;
105   }
106
107   void setText(const std::string &text)
108   {
109     if (_rawText == text) {
110       return; // common case, and saves invalidation
111     }
112
113     _rawText = text;
114     _dirtyText = true;
115   }
116
117   void setDataVisible(bool vis) {
118     if (vis == _dataVisible) {
119       return;
120     }
121
122     if (_rawText.empty()) {
123       vis = false;
124     }
125
126     _dataVisible = vis;
127     _dirtyText = true;
128   }
129
130   static void setFont(puFont f)
131   {
132     _font = f;
133     _fontHeight = f.getStringHeight();
134     _fontDescender = f.getStringDescender();
135   }
136
137   static void setPalette(puColor* pal)
138   {
139     _palette = pal;
140   }
141
142   void setPriority(int pri)
143   {
144     _priority = pri;
145   }
146
147   int priority() const
148   { return _priority; }
149
150   void setAnchor(const SGVec2d& anchor)
151   {
152     _anchor = anchor;
153   }
154
155   void setOffset(int direction, int px)
156   {
157     if ((_offsetPx == px) && (_offsetDir == direction)) {
158       return;
159     }
160
161     _dirtyOffset = true;
162     _offsetDir = direction;
163     _offsetPx = px;
164   }
165
166   bool isClipped(const puBox& vis) const
167   {
168     validate();
169     if ((_width < 1) || (_height < 1)) {
170       return true;
171     }
172
173     return !puBoxIntersect(vis, box());
174   }
175
176   bool overlaps(const MapDataVec& l) const
177   {
178     validate();
179     puBox b(box());
180
181     MapDataVec::const_iterator it;
182     for (it = l.begin(); it != l.end(); ++it) {
183       if (puBoxIntersect(b, (*it)->box())) {
184         return true;
185       }
186     } // of list iteration
187
188     return false;
189   }
190
191   puBox box() const
192   {
193     validate();
194     return makePuBox(
195       _anchor.x() + _offset.x(),
196       _anchor.y() + _offset.y(),
197       _width, _height);
198   }
199
200   void draw()
201   {
202     validate();
203
204     int xx = _anchor.x() + _offset.x();
205     int yy = _anchor.y() + _offset.y();
206
207     if (_dataVisible) {
208       puBox box(makePuBox(0,0,_width, _height));
209       int border = 1;
210       box.draw(xx, yy, PUSTYLE_DROPSHADOW, _palette, FALSE, border);
211
212       // draw lines
213       int lineHeight = _fontHeight;
214       int xPos = xx + MARGIN;
215       int yPos = yy + _height - (lineHeight + MARGIN);
216       glColor3f(0.8, 0.8, 0.8);
217
218       for (unsigned int ln=0; ln<_lines.size(); ++ln) {
219         _font.drawString(_lines[ln].c_str(), xPos, yPos);
220         yPos -= lineHeight + LINE_LEADING;
221       }
222     } else {
223       glColor3f(0.8, 0.8, 0.8);
224       _font.drawString(_label.c_str(), xx, yy + _fontDescender);
225     }
226   }
227
228   void age()
229   {
230     ++_age;
231   }
232
233   void resetAge()
234   {
235     _age = 0;
236   }
237
238   bool isExpired() const
239   { return (_age > 100); }
240
241   static bool order(MapData* a, MapData* b)
242   {
243     return a->_priority > b->_priority;
244   }
245 private:
246   void validate() const
247   {
248     if (!_dirtyText) {
249       if (_dirtyOffset) {
250         computeOffset();
251       }
252
253       return;
254     }
255
256     if (_dataVisible) {
257       measureData();
258     } else {
259       measureLabel();
260     }
261
262     computeOffset();
263     _dirtyText = false;
264   }
265
266   void measureData() const
267   {
268     _lines = simgear::strutils::split(_rawText, "\n");
269   // measure text to find width and height
270     _width = -1;
271     _height = 0;
272
273     for (unsigned int ln=0; ln<_lines.size(); ++ln) {
274       _height += _fontHeight;
275       if (ln > 0) {
276         _height += LINE_LEADING;
277       }
278
279       int lw = _font.getStringWidth(_lines[ln].c_str());
280       _width = std::max(_width, lw);
281     } // of line measurement
282
283     if ((_width < 1) || (_height < 1)) {
284       // will be clipped
285       return;
286     }
287
288     _height += MARGIN * 2;
289     _width += MARGIN * 2;
290   }
291
292   void measureLabel() const
293   {
294     if (_label.empty()) {
295       _width = _height = -1;
296       return;
297     }
298
299     _height = _fontHeight;
300     _width = _font.getStringWidth(_label.c_str());
301   }
302
303   void computeOffset() const
304   {
305     _dirtyOffset = false;
306     if ((_width <= 0) || (_height <= 0)) {
307       return;
308     }
309
310     int hOffset = 0;
311     int vOffset = 0;
312
313     switch (_offsetDir & 0x0f) {
314     default:
315     case HALIGN_LEFT:
316       hOffset = _offsetPx;
317       break;
318
319     case HALIGN_CENTER:
320       hOffset = -(_width>>1);
321       break;
322
323     case HALIGN_RIGHT:
324       hOffset = -(_offsetPx + _width);
325       break;
326     }
327
328     switch (_offsetDir & 0xf0) {
329     default:
330     case VALIGN_TOP:
331       vOffset = -(_offsetPx + _height);
332       break;
333
334     case VALIGN_CENTER:
335       vOffset = -(_height>>1);
336       break;
337
338     case VALIGN_BOTTOM:
339       vOffset = _offsetPx;
340       break;
341     }
342
343     _offset = SGVec2d(hOffset, vOffset);
344   }
345
346   static const int LINE_LEADING = 3;
347         static const int MARGIN = 3;
348
349   mutable bool _dirtyText;
350   mutable bool _dirtyOffset;
351   int _age;
352   std::string _rawText;
353   std::string _label;
354   mutable std::vector<std::string> _lines;
355   int _priority;
356   mutable int _width, _height;
357   SGVec2d _anchor;
358   int _offsetDir;
359   int _offsetPx;
360   mutable SGVec2d _offset;
361   bool _dataVisible;
362
363   static puFont _font;
364   static puColor* _palette;
365   static int _fontHeight;
366   static int _fontDescender;
367 };
368
369 puFont MapData::_font;
370 puColor* MapData::_palette;
371 int MapData::_fontHeight = 0;
372 int MapData::_fontDescender = 0;
373
374 ///////////////////////////////////////////////////////////////////////////
375
376 const int MAX_ZOOM = 12;
377 const int SHOW_DETAIL_ZOOM = 8;
378 const int CURSOR_PAN_STEP = 32;
379
380 MapWidget::MapWidget(int x, int y, int maxX, int maxY) :
381   puObject(x,y,maxX, maxY)
382 {
383   _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
384   _gps = fgGetNode("/instrumentation/gps");
385
386   _width = maxX - x;
387   _height = maxY - y;
388   _hasPanned = false;
389   _orthoAzimuthProject = false;
390   
391   MapData::setFont(legendFont);
392   MapData::setPalette(colour);
393
394   _magVar = new SGMagVar();
395 }
396
397 MapWidget::~MapWidget()
398 {
399   delete _magVar;
400   clearData();
401 }
402
403 void MapWidget::setProperty(SGPropertyNode_ptr prop)
404 {
405   _root = prop;
406   int zoom = _root->getIntValue("zoom", -1);
407   if (zoom < 0) {
408     _root->setIntValue("zoom", 6); // default zoom
409   }
410   
411 // expose MAX_ZOOM to the UI
412   _root->setIntValue("max-zoom", MAX_ZOOM);
413   _root->setBoolValue("centre-on-aircraft", true);
414   _root->setBoolValue("draw-data", false);
415   _root->setBoolValue("draw-flight-history", false);
416   _root->setBoolValue("magnetic-headings", true);
417 }
418
419 void MapWidget::setSize(int w, int h)
420 {
421   puObject::setSize(w, h);
422
423   _width = w;
424   _height = h;
425
426 }
427
428 void MapWidget::doHit( int button, int updown, int x, int y )
429 {
430   puObject::doHit(button, updown, x, y);
431   if (updown == PU_DRAG) {
432     handlePan(x, y);
433     return;
434   }
435
436   if (button == 3) { // mouse-wheel up
437     zoomIn();
438   } else if (button == 4) { // mouse-wheel down
439     zoomOut();
440   }
441
442   if (button != active_mouse_button) {
443     return;
444   }
445
446   _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
447
448   if (updown == PU_UP) {
449     puDeactivateWidget();
450   } else if (updown == PU_DOWN) {
451     puSetActiveWidget(this, x, y);
452
453     if (fgGetKeyModifiers() & KEYMOD_CTRL) {
454       _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
455     }
456   }
457 }
458
459 void MapWidget::handlePan(int x, int y)
460 {
461   SGVec2d delta = SGVec2d(x, y) - _hitLocation;
462   pan(delta);
463   _hitLocation = SGVec2d(x,y);
464 }
465
466 int MapWidget::checkKey (int key, int updown )
467 {
468   if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
469     return FALSE ;
470   }
471
472   switch (key)
473   {
474
475   case PU_KEY_UP:
476     pan(SGVec2d(0, -CURSOR_PAN_STEP));
477     break;
478
479   case PU_KEY_DOWN:
480     pan(SGVec2d(0, CURSOR_PAN_STEP));
481     break ;
482
483   case PU_KEY_LEFT:
484     pan(SGVec2d(CURSOR_PAN_STEP, 0));
485     break;
486
487   case PU_KEY_RIGHT:
488     pan(SGVec2d(-CURSOR_PAN_STEP, 0));
489     break;
490
491   case '-':
492     zoomOut();
493
494     break;
495
496   case '=':
497     zoomIn();
498     break;
499
500   default :
501     return FALSE;
502   }
503
504   return TRUE ;
505 }
506
507 void MapWidget::pan(const SGVec2d& delta)
508 {
509   _hasPanned = true; 
510   _projectionCenter = unproject(-delta);
511 }
512
513 int MapWidget::zoom() const
514 {
515   int z = _root->getIntValue("zoom");
516   SG_CLAMP_RANGE(z, 0, MAX_ZOOM);
517   return z;
518 }
519
520 void MapWidget::zoomIn()
521 {
522   if (zoom() >= MAX_ZOOM) {
523     return;
524   }
525
526   _root->setIntValue("zoom", zoom() + 1);
527 }
528
529 void MapWidget::zoomOut()
530 {
531   if (zoom() <= 0) {
532     return;
533   }
534
535   _root->setIntValue("zoom", zoom() - 1);
536 }
537
538 void MapWidget::draw(int dx, int dy)
539 {
540   _aircraft = globals->get_aircraft_position();
541     
542   bool mag = _root->getBoolValue("magnetic-headings");
543   if (mag != _magneticHeadings) {
544     clearData(); // flush cached data text, since it often includes heading
545     _magneticHeadings =  mag;
546   }
547   
548   if (_hasPanned) {
549       _root->setBoolValue("centre-on-aircraft", false);
550       _hasPanned = false;
551   }
552   else if (_root->getBoolValue("centre-on-aircraft")) {
553     _projectionCenter = _aircraft;
554   }
555
556   double julianDate = globals->get_time_params()->getJD();
557   _magVar->update(_projectionCenter, julianDate);
558
559   bool aircraftUp = _root->getBoolValue("aircraft-heading-up");
560   if (aircraftUp) {
561     _upHeading = fgGetDouble("/orientation/heading-deg");
562   } else {
563     _upHeading = 0.0;
564   }
565
566   _cachedZoom = MAX_ZOOM - zoom();
567   SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
568   // compute draw range, including a fudge factor for ILSs and other 'long'
569   // symbols
570   _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
571
572 // drawing operations
573   GLint sx = (int) abox.min[0],
574     sy = (int) abox.min[1];
575   glScissor(dx + sx, dy + sy, _width, _height);
576   glEnable(GL_SCISSOR_TEST);
577
578   glMatrixMode(GL_MODELVIEW);
579   glPushMatrix();
580   // cetere drawing about the widget center (which is also the
581   // projection centre)
582   glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
583
584   drawLatLonGrid();
585
586   if (aircraftUp) {
587     int textHeight = legendFont.getStringHeight() + 5;
588
589     // draw heading line
590     SGVec2d loc = project(_aircraft);
591     glColor3f(1.0, 1.0, 1.0);
592     drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
593
594     int displayHdg;
595     if (_magneticHeadings) {
596       displayHdg = (int) fgGetDouble("/orientation/heading-magnetic-deg");
597     } else {
598       displayHdg = (int) _upHeading;
599     }
600
601     double y = (_height / 2) - textHeight;
602     char buf[16];
603     ::snprintf(buf, 16, "%d", displayHdg);
604     int sw = legendFont.getStringWidth(buf);
605     legendFont.drawString(buf, loc.x() - sw/2, y);
606   }
607
608   drawAirports();
609   drawNavaids();
610   drawTraffic();
611   drawGPSData();
612   drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
613   drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
614   paintAircraftLocation(_aircraft);
615   drawFlightHistory();
616   paintRoute();
617   paintRuler();
618
619   drawData();
620
621   glPopMatrix();
622   glDisable(GL_SCISSOR_TEST);
623 }
624
625 void MapWidget::paintRuler()
626 {
627   if (_clickGeod == SGGeod()) {
628     return;
629   }
630
631   SGVec2d acftPos = project(_aircraft);
632   SGVec2d clickPos = project(_clickGeod);
633
634   glColor4f(0.0, 1.0, 1.0, 0.6);
635   drawLine(acftPos, clickPos);
636
637   circleAtAlt(clickPos, 8, 10, 5);
638
639   double dist, az, az2;
640   SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
641   char buffer[1024];
642         ::snprintf(buffer, 1024, "%03d/%.1fnm",
643                 displayHeading(az), dist * SG_METER_TO_NM);
644
645   MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
646   d->setLabel(buffer);
647   d->setAnchor(clickPos);
648   d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
649   d->setPriority(20000);
650
651
652 }
653
654 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
655 {
656   SGVec2d loc = project(aircraftPos);
657
658   double hdg = fgGetDouble("/orientation/heading-deg");
659
660   glLineWidth(2.0);
661   glColor4f(1.0, 1.0, 0.0, 1.0);
662   glPushMatrix();
663   glTranslated(loc.x(), loc.y(), 0.0);
664   glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
665
666   const SGVec2d wingspan(12, 0);
667   const SGVec2d nose(0, 8);
668   const SGVec2d tail(0, -14);
669   const SGVec2d tailspan(4,0);
670
671   drawLine(-wingspan, wingspan);
672   drawLine(nose, tail);
673   drawLine(tail - tailspan, tail + tailspan);
674
675   glPopMatrix();
676   glLineWidth(1.0);
677 }
678
679 void MapWidget::paintRoute()
680 {
681   if (_route->numWaypts() < 2) {
682     return;
683   }
684
685   RoutePath path(_route->flightPlan());
686
687 // first pass, draw the actual lines
688   glLineWidth(2.0);
689
690   for (int w=0; w<_route->numWaypts(); ++w) {
691     SGGeodVec gv(path.pathForIndex(w));
692     if (gv.empty()) {
693       continue;
694     }
695
696     if (w < _route->currentIndex()) {
697       glColor4f(0.5, 0.5, 0.5, 0.7);
698     } else {
699       glColor4f(1.0, 0.0, 1.0, 1.0);
700     }
701
702     flightgear::WayptRef wpt(_route->wayptAtIndex(w));
703     if (wpt->flag(flightgear::WPT_MISS)) {
704       glEnable(GL_LINE_STIPPLE);
705       glLineStipple(1, 0x00FF);
706     }
707
708     glBegin(GL_LINE_STRIP);
709     for (unsigned int i=0; i<gv.size(); ++i) {
710       SGVec2d p = project(gv[i]);
711       glVertex2d(p.x(), p.y());
712     }
713
714     glEnd();
715     glDisable(GL_LINE_STIPPLE);
716   }
717
718   glLineWidth(1.0);
719 // second pass, draw waypoint symbols and data
720   for (int w=0; w < _route->numWaypts(); ++w) {
721     flightgear::WayptRef wpt(_route->wayptAtIndex(w));
722     SGGeod g = path.positionForIndex(w);
723     if (g == SGGeod()) {
724       continue; // Vectors or similar
725     }
726
727     SGVec2d p = project(g);
728     glColor4f(1.0, 0.0, 1.0, 1.0);
729     circleAtAlt(p, 8, 12, 5);
730
731     std::ostringstream legend;
732     legend << wpt->ident();
733     if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
734       legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
735     }
736
737     if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
738       legend << '\n' << wpt->speedMach() << "M";
739     } else if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
740       legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
741     }
742
743     MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
744     d->setText(legend.str());
745     d->setLabel(wpt->ident());
746     d->setAnchor(p);
747     d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
748     d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
749
750   } // of second waypoint iteration
751 }
752
753 void MapWidget::drawFlightHistory()
754 {
755   FGFlightHistory* history = (FGFlightHistory*) globals->get_subsystem("history");
756   if (!history || !_root->getBoolValue("draw-flight-history")) {
757     return;
758   }
759   
760   // first pass, draw the actual lines
761   glLineWidth(2.0);
762   
763   SGGeodVec gv(history->pathForHistory());
764   glColor4f(0.0, 0.0, 1.0, 0.7);
765
766   glBegin(GL_LINE_STRIP);
767   for (unsigned int i=0; i<gv.size(); ++i) {
768     SGVec2d p = project(gv[i]);
769     glVertex2d(p.x(), p.y());
770   }
771   
772   glEnd();
773 }
774
775 /**
776  * Round a SGGeod to an arbitrary precision.
777  * For example, passing precision of 0.5 will round to the nearest 0.5 of
778  * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
779  * multiple, and so on.
780  */
781 static SGGeod roundGeod(double precision, const SGGeod& g)
782 {
783   double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
784   double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
785
786   return SGGeod::fromDeg(lon * precision, lat * precision);
787 }
788
789 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
790 {
791   double minX = SGMiscd::min(a.x(), b.x()),
792     minY = SGMiscd::min(a.y(), b.y()),
793     maxX = SGMiscd::max(a.x(), b.x()),
794     maxY = SGMiscd::max(a.y(), b.y());
795
796   int hh = _height >> 1, hw = _width >> 1;
797
798   if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
799     return false;
800   }
801
802   glVertex2dv(a.data());
803   glVertex2dv(b.data());
804   return true;
805 }
806
807 SGVec2d MapWidget::gridPoint(int ix, int iy)
808 {
809         int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
810         GridPointCache::iterator it = _gridCache.find(key);
811         if (it != _gridCache.end()) {
812                 return it->second;
813         }
814
815         SGGeod gp = SGGeod::fromDeg(
816     _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
817                 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
818
819         SGVec2d proj = project(gp);
820         _gridCache[key] = proj;
821         return proj;
822 }
823
824 void MapWidget::drawLatLonGrid()
825 {
826   _gridSpacing = 1.0;
827   _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
828   _gridCache.clear();
829
830   int ix = 0;
831   int iy = 0;
832
833   glColor4f(0.8, 0.8, 0.8, 0.4);
834   glBegin(GL_LINES);
835   bool didDraw;
836   do {
837     didDraw = false;
838     ++ix;
839     ++iy;
840
841     for (int x = -ix; x < ix; ++x) {
842       didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
843       didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
844       didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
845       didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
846
847     }
848
849     for (int y = -iy; y < iy; ++y) {
850       didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
851       didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
852       didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
853       didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
854     }
855
856     if (ix > 30) {
857       break;
858     }
859   } while (didDraw);
860
861   glEnd();
862 }
863
864 void MapWidget::drawGPSData()
865 {
866   std::string gpsMode = _gps->getStringValue("mode");
867
868   SGGeod wp0Geod = SGGeod::fromDeg(
869         _gps->getDoubleValue("wp/wp[0]/longitude-deg"),
870         _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
871
872   SGGeod wp1Geod = SGGeod::fromDeg(
873         _gps->getDoubleValue("wp/wp[1]/longitude-deg"),
874         _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
875
876 // draw track line
877   double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
878   double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
879   double az2;
880
881   if (gpsSpeed > 3.0) { // only draw track line if valid
882     SGGeod trackRadial;
883     SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
884
885     glColor4f(1.0, 1.0, 0.0, 1.0);
886     glEnable(GL_LINE_STIPPLE);
887     glLineStipple(1, 0x00FF);
888     drawLine(project(_aircraft), project(trackRadial));
889     glDisable(GL_LINE_STIPPLE);
890   }
891
892   if (gpsMode == "dto") {
893     SGVec2d wp0Pos = project(wp0Geod);
894     SGVec2d wp1Pos = project(wp1Geod);
895
896     glColor4f(1.0, 0.0, 1.0, 1.0);
897     drawLine(wp0Pos, wp1Pos);
898
899   }
900
901   if (_gps->getBoolValue("scratch/valid")) {
902     // draw scratch data
903
904   }
905 }
906
907 class MapAirportFilter : public FGAirport::AirportFilter
908 {
909 public:
910   MapAirportFilter(SGPropertyNode_ptr nd)
911   {
912     _heliports = nd->getBoolValue("show-heliports", false);
913     _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
914     _minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
915   }
916
917   virtual FGPositioned::Type maxType() const {
918     return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
919   }
920
921   virtual bool passAirport(FGAirport* aApt) const {
922     if (_hardRunwaysOnly) {
923       return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
924     }
925
926     return true;
927   }
928
929 private:
930   bool _heliports;
931   bool _hardRunwaysOnly;
932   double _minLengthFt;
933 };
934
935 void MapWidget::drawAirports()
936 {
937   MapAirportFilter af(_root);
938   bool partial = false;
939   FGPositioned::List apts = FGPositioned::findWithinRangePartial(_projectionCenter, _drawRangeNm, &af, partial);
940   for (unsigned int i=0; i<apts.size(); ++i) {
941     drawAirport((FGAirport*) apts[i].get());
942   }
943 }
944
945 class NavaidFilter : public FGPositioned::Filter
946 {
947 public:
948   NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
949     _fixes(fixesEnabled),
950     _navaids(navaidsEnabled)
951   {}
952
953   virtual bool pass(FGPositioned* aPos) const {
954     if (_fixes && (aPos->type() == FGPositioned::FIX)) {
955       // ignore fixes which end in digits - expirmental
956       if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
957         return false;
958       }
959     }
960
961     return true;
962   }
963
964   virtual FGPositioned::Type minType() const {
965     return _fixes ? FGPositioned::FIX : FGPositioned::NDB;
966   }
967
968   virtual FGPositioned::Type maxType() const {
969     return _navaids ? FGPositioned::VOR : FGPositioned::FIX;
970   }
971
972 private:
973   bool _fixes, _navaids;
974 };
975
976 void MapWidget::drawNavaids()
977 {
978   bool fixes = _root->getBoolValue("draw-fixes");
979   NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
980
981   if (f.minType() <= f.maxType()) {
982     FGPositioned::List navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
983
984     glLineWidth(1.0);
985     for (unsigned int i=0; i<navs.size(); ++i) {
986       FGPositioned::Type ty = navs[i]->type();
987       if (ty == FGPositioned::NDB) {
988         drawNDB(false, (FGNavRecord*) navs[i].get());
989       } else if (ty == FGPositioned::VOR) {
990         drawVOR(false, (FGNavRecord*) navs[i].get());
991       } else if (ty == FGPositioned::FIX) {
992         drawFix((FGFix*) navs[i].get());
993       }
994     } // of navaid iteration
995   } // of navaids || fixes are drawn test
996 }
997
998 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
999 {
1000   SGVec2d pos = project(ndb->geod());
1001
1002   if (tuned) {
1003     glColor3f(0.0, 1.0, 1.0);
1004   } else {
1005     glColor3f(0.0, 0.0, 0.0);
1006   }
1007
1008   glEnable(GL_LINE_STIPPLE);
1009   glLineStipple(1, 0x00FF);
1010   circleAt(pos, 20, 6);
1011   circleAt(pos, 20, 10);
1012   glDisable(GL_LINE_STIPPLE);
1013
1014   if (validDataForKey(ndb)) {
1015     setAnchorForKey(ndb, pos);
1016     return;
1017   }
1018
1019   char buffer[1024];
1020         ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
1021                 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
1022
1023   MapData* d = createDataForKey(ndb);
1024   d->setPriority(40);
1025   d->setLabel(ndb->ident());
1026   d->setText(buffer);
1027   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1028   d->setAnchor(pos);
1029
1030 }
1031
1032 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
1033 {
1034   SGVec2d pos = project(vor->geod());
1035   if (tuned) {
1036     glColor3f(0.0, 1.0, 1.0);
1037   } else {
1038     glColor3f(0.0, 0.0, 1.0);
1039   }
1040
1041   circleAt(pos, 6, 8);
1042
1043   if (validDataForKey(vor)) {
1044     setAnchorForKey(vor, pos);
1045     return;
1046   }
1047
1048   char buffer[1024];
1049         ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1050                 vor->name().c_str(), vor->ident().c_str(),
1051     vor->get_freq() / 100.0);
1052
1053   MapData* d = createDataForKey(vor);
1054   d->setText(buffer);
1055   d->setLabel(vor->ident());
1056   d->setPriority(tuned ? 10000 : 100);
1057   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1058   d->setAnchor(pos);
1059 }
1060
1061 void MapWidget::drawFix(FGFix* fix)
1062 {
1063   SGVec2d pos = project(fix->geod());
1064   glColor3f(0.0, 0.0, 0.0);
1065   circleAt(pos, 3, 6);
1066
1067   if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1068     return; // hide fix labels beyond a certain zoom level
1069   }
1070
1071   if (validDataForKey(fix)) {
1072     setAnchorForKey(fix, pos);
1073     return;
1074   }
1075
1076   MapData* d = createDataForKey(fix);
1077   d->setLabel(fix->ident());
1078   d->setPriority(20);
1079   d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1080   d->setAnchor(pos);
1081 }
1082
1083 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1084 {
1085   if (!radio || radio->getBoolValue("slaved-to-gps", false)
1086         || !radio->getBoolValue("in-range", false)) {
1087     return;
1088   }
1089
1090   if (radio->getBoolValue("nav-loc", false)) {
1091     drawTunedLocalizer(radio);
1092   }
1093
1094   // identify the tuned station - unfortunately we don't get lat/lon directly,
1095   // need to do the frequency search again
1096   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1097
1098   FGNavRecord* nav = FGNavList::findByFreq(mhz, _aircraft,
1099                                            FGNavList::navFilter());
1100   if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1101     // mismatch between navradio selection logic and ours!
1102     return;
1103   }
1104
1105   glLineWidth(1.0);
1106   drawVOR(true, nav);
1107
1108   SGVec2d pos = project(nav->geod());
1109   SGGeod range;
1110   double az2;
1111   double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1112   SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1113   SGVec2d prange = project(range);
1114
1115   SGVec2d norm = normalize(prange - pos);
1116   SGVec2d perp(norm.y(), -norm.x());
1117
1118   circleAt(pos, 64, length(prange - pos));
1119   drawLine(pos, prange);
1120
1121 // draw to/from arrows
1122   SGVec2d midPoint = (pos + prange) * 0.5;
1123   if (radio->getBoolValue("from-flag")) {
1124     norm = -norm;
1125     perp = -perp;
1126   }
1127
1128   int sz = 10;
1129   SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1130   SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1131   drawLine(midPoint, arrowB);
1132   drawLine(arrowB, arrowC);
1133   drawLine(arrowC, midPoint);
1134
1135   drawLine(pos, (2 * pos) - prange); // reciprocal radial
1136 }
1137
1138 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1139 {
1140   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1141   FGNavRecord* loc = FGNavList::findByFreq(mhz, _aircraft, FGNavList::locFilter());
1142   if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1143     // mismatch between navradio selection logic and ours!
1144     return;
1145   }
1146
1147   if (loc->runway()) {
1148     drawILS(true, loc->runway());
1149   }
1150 }
1151
1152 /*
1153 void MapWidget::drawObstacle(FGPositioned* obs)
1154 {
1155   SGVec2d pos = project(obs->geod());
1156   glColor3f(0.0, 0.0, 0.0);
1157   glLineWidth(2.0);
1158   drawLine(pos, pos + SGVec2d());
1159 }
1160 */
1161
1162 void MapWidget::drawAirport(FGAirport* apt)
1163 {
1164         // draw tower location
1165         SGVec2d towerPos = project(apt->getTowerLocation());
1166
1167   if (_cachedZoom <= SHOW_DETAIL_ZOOM) {
1168     glColor3f(1.0, 1.0, 1.0);
1169     glLineWidth(1.0);
1170
1171     drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1172     drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1173     drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1174     drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1175     drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1176   }
1177
1178   if (validDataForKey(apt)) {
1179     setAnchorForKey(apt, towerPos);
1180   } else {
1181     char buffer[1024];
1182     ::snprintf(buffer, 1024, "%s\n%s",
1183       apt->ident().c_str(), apt->name().c_str());
1184
1185     MapData* d = createDataForKey(apt);
1186     d->setText(buffer);
1187     d->setLabel(apt->ident());
1188     d->setPriority(100 + scoreAirportRunways(apt));
1189     d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1190     d->setAnchor(towerPos);
1191   }
1192
1193   if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1194     return;
1195   }
1196
1197   FGRunwayList runways(apt->getRunwaysWithoutReciprocals());
1198     
1199   for (unsigned int r=0; r<runways.size(); ++r) {
1200     drawRunwayPre(runways[r]);
1201   }
1202
1203   for (unsigned int r=0; r<runways.size(); ++r) {
1204     FGRunway* rwy = runways[r];
1205     drawRunway(rwy);
1206
1207     if (rwy->ILS()) {
1208         drawILS(false, rwy);
1209     }
1210     
1211     if (rwy->reciprocalRunway()) {
1212       FGRunway* recip = rwy->reciprocalRunway();
1213       if (recip->ILS()) {
1214         drawILS(false, recip);
1215       }
1216     }
1217   }
1218
1219   for (unsigned int r=0; r<apt->numHelipads(); ++r) {
1220       FGHelipad* hp = apt->getHelipadByIndex(r);
1221       drawHelipad(hp);
1222   }  // of runway iteration
1223
1224 }
1225
1226 int MapWidget::scoreAirportRunways(FGAirport* apt)
1227 {
1228   bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1229   double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1230
1231   FGRunwayList runways(apt->getRunwaysWithoutReciprocals());
1232
1233   int score = 0;
1234   for (unsigned int r=0; r<runways.size(); ++r) {
1235     FGRunway* rwy = runways[r];
1236     if (needHardSurface && !rwy->isHardSurface()) {
1237       continue;
1238     }
1239
1240     if (rwy->lengthFt() < minLength) {
1241       continue;
1242     }
1243
1244     int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1245     score += scoreLength;
1246   } // of runways iteration
1247
1248   return score;
1249 }
1250
1251 void MapWidget::drawRunwayPre(FGRunway* rwy)
1252 {
1253   SGVec2d p1 = project(rwy->begin());
1254         SGVec2d p2 = project(rwy->end());
1255
1256   glLineWidth(4.0);
1257   glColor3f(1.0, 0.0, 1.0);
1258         drawLine(p1, p2);
1259 }
1260
1261 void MapWidget::drawRunway(FGRunway* rwy)
1262 {
1263         // line for runway
1264         // optionally show active, stopway, etc
1265         // in legend, show published heading and length
1266         // and threshold elevation
1267
1268   SGVec2d p1 = project(rwy->begin());
1269         SGVec2d p2 = project(rwy->end());
1270   glLineWidth(2.0);
1271   glColor3f(1.0, 1.0, 1.0);
1272   SGVec2d inset = normalize(p2 - p1) * 2;
1273
1274         drawLine(p1 + inset, p2 - inset);
1275
1276   if (validDataForKey(rwy)) {
1277     setAnchorForKey(rwy, (p1 + p2) * 0.5);
1278     return;
1279   }
1280   
1281         char buffer[1024];
1282         ::snprintf(buffer, 1024, "%s/%s\n%03d/%03d\n%.0f'",
1283                 rwy->ident().c_str(),
1284                 rwy->reciprocalRunway()->ident().c_str(),
1285                 displayHeading(rwy->headingDeg()),
1286                 displayHeading(rwy->reciprocalRunway()->headingDeg()),
1287                 rwy->lengthFt());
1288
1289   MapData* d = createDataForKey(rwy);
1290   d->setText(buffer);
1291   d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1292   d->setPriority(50);
1293   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1294   d->setAnchor((p1 + p2) * 0.5);
1295 }
1296
1297 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1298 {
1299         // arrow, tip centered on the landing threshold
1300   // using LOC transmitter position would be more accurate, but
1301   // is visually cluttered
1302         // arrow width is based upon the computed localizer width
1303
1304         FGNavRecord* loc = rwy->ILS();
1305         double halfBeamWidth = loc->localizerWidth() * 0.5;
1306         SGVec2d t = project(rwy->threshold());
1307         SGGeod locEnd;
1308         double rangeM = loc->get_range() * SG_NM_TO_METER;
1309         double radial = loc->get_multiuse();
1310   SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1311         double az2;
1312
1313 // compute the three end points at the widge end of the arrow
1314         SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1315         SGVec2d endCentre = project(locEnd);
1316
1317         SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1318         SGVec2d endR = project(locEnd);
1319
1320         SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1321         SGVec2d endL = project(locEnd);
1322
1323 // outline two triangles
1324   glLineWidth(1.0);
1325   if (tuned) {
1326     glColor3f(0.0, 1.0, 1.0);
1327   } else {
1328     glColor3f(0.0, 0.0, 1.0);
1329         }
1330
1331   glBegin(GL_LINE_LOOP);
1332                 glVertex2dv(t.data());
1333                 glVertex2dv(endCentre.data());
1334                 glVertex2dv(endL.data());
1335         glEnd();
1336         glBegin(GL_LINE_LOOP);
1337                 glVertex2dv(t.data());
1338                 glVertex2dv(endCentre.data());
1339                 glVertex2dv(endR.data());
1340         glEnd();
1341
1342         if (validDataForKey(loc)) {
1343     setAnchorForKey(loc, endR);
1344     return;
1345   }
1346
1347         char buffer[1024];
1348         ::snprintf(buffer, 1024, "%s\n%s\n%03d - %3.2fMHz",
1349                 loc->ident().c_str(), loc->name().c_str(),
1350     displayHeading(radial),
1351     loc->get_freq()/100.0);
1352
1353   MapData* d = createDataForKey(loc);
1354   d->setPriority(40);
1355   d->setLabel(loc->ident());
1356   d->setText(buffer);
1357   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1358   d->setAnchor(endR);
1359 }
1360
1361 void MapWidget::drawTraffic()
1362 {
1363   if (!_root->getBoolValue("draw-traffic")) {
1364     return;
1365   }
1366
1367   if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1368     return;
1369   }
1370
1371   const SGPropertyNode* ai = fgGetNode("/ai/models", true);
1372
1373   for (int i = 0; i < ai->nChildren(); ++i) {
1374     const SGPropertyNode *model = ai->getChild(i);
1375     // skip bad or dead entries
1376     if (!model || model->getIntValue("id", -1) == -1) {
1377       continue;
1378     }
1379
1380     const std::string& name(model->getName());
1381     SGGeod pos = SGGeod::fromDegFt(
1382       model->getDoubleValue("position/longitude-deg"),
1383       model->getDoubleValue("position/latitude-deg"),
1384       model->getDoubleValue("position/altitude-ft"));
1385
1386     double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
1387     if (dist > _drawRangeNm) {
1388       continue;
1389     }
1390
1391     double heading = model->getDoubleValue("orientation/true-heading-deg");
1392     if ((name == "aircraft") || (name == "multiplayer") ||
1393         (name == "wingman") || (name == "tanker")) {
1394       drawAIAircraft(model, pos, heading);
1395     } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1396       drawAIShip(model, pos, heading);
1397     }
1398   } // of ai/models iteration
1399 }
1400
1401 void MapWidget::drawHelipad(FGHelipad* hp)
1402 {
1403   SGVec2d pos = project(hp->geod());
1404   glLineWidth(1.0);
1405   glColor3f(1.0, 1.0, 1.0);
1406   circleAt(pos, 16, 5.0);
1407
1408   if (validDataForKey(hp)) {
1409     setAnchorForKey(hp, pos);
1410     return;
1411   }
1412
1413   char buffer[1024];
1414   ::snprintf(buffer, 1024, "%s\n%03d\n%.0f'",
1415              hp->ident().c_str(),
1416              displayHeading(hp->headingDeg()),
1417              hp->lengthFt());
1418
1419   MapData* d = createDataForKey(hp);
1420   d->setText(buffer);
1421   d->setLabel(hp->ident());
1422   d->setPriority(40);
1423   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 8);
1424   d->setAnchor(pos);
1425 }
1426
1427 void MapWidget::drawAIAircraft(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1428 {
1429
1430   SGVec2d p = project(pos);
1431
1432   glColor3f(0.0, 0.0, 0.0);
1433   glLineWidth(2.0);
1434   circleAt(p, 4, 6.0); // black diamond
1435
1436 // draw heading vector
1437   int speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1438   if (speedKts > 1) {
1439     glLineWidth(1.0);
1440
1441     const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1442     double distanceM = speedKts * SG_NM_TO_METER * dt;
1443
1444     SGGeod advance;
1445     double az2;
1446     SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1447
1448     drawLine(p, project(advance));
1449   }
1450
1451
1452   // draw callsign / altitude / speed
1453   char buffer[1024];
1454         ::snprintf(buffer, 1024, "%s\n%d'\n%dkts",
1455                 model->getStringValue("callsign", "<>"),
1456                 static_cast<int>(pos.getElevationFt() / 50.0) * 50,
1457     speedKts);
1458
1459   MapData* d = getOrCreateDataForKey((void*) model);
1460   d->setText(buffer);
1461   d->setLabel(model->getStringValue("callsign", "<>"));
1462   d->setPriority(speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1463   d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1464   d->setAnchor(p);
1465
1466 }
1467
1468 void MapWidget::drawAIShip(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1469 {
1470   SGVec2d p = project(pos);
1471
1472   glColor3f(0.0, 0.0, 0.5);
1473   glLineWidth(2.0);
1474   circleAt(p, 4, 6.0); // blue diamond (to differentiate from aircraft.
1475
1476 // draw heading vector
1477   int speedKts = static_cast<int>(model->getDoubleValue("velocities/speed-kts"));
1478   if (speedKts > 1) {
1479     glLineWidth(1.0);
1480
1481     const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1482     double distanceM = speedKts * SG_NM_TO_METER * dt;
1483
1484     SGGeod advance;
1485     double az2;
1486     SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1487
1488     drawLine(p, project(advance));
1489   }
1490
1491   // draw callsign / speed
1492   char buffer[1024];
1493         ::snprintf(buffer, 1024, "%s\n%dkts",
1494                 model->getStringValue("name", "<>"),
1495     speedKts);
1496
1497   MapData* d = getOrCreateDataForKey((void*) model);
1498   d->setText(buffer);
1499   d->setLabel(model->getStringValue("name", "<>"));
1500   d->setPriority(speedKts > 2 ? 30 : 10); // low priority for slow moving ships
1501   d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1502   d->setAnchor(p);
1503 }
1504
1505 SGVec2d MapWidget::project(const SGGeod& geod) const
1506 {
1507   SGVec2d p;
1508   double r = earth_radius_lat(geod.getLatitudeRad());
1509   
1510   if (_orthoAzimuthProject) {
1511     // http://mathworld.wolfram.com/OrthographicProjection.html
1512     double cosTheta = cos(geod.getLatitudeRad());
1513     double sinDLambda = sin(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1514     double cosDLambda = cos(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1515     double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1516     double sinTheta = sin(geod.getLatitudeRad());
1517     double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1518     
1519     p = SGVec2d(cosTheta * sinDLambda,
1520                 (cosTheta1 * sinTheta) - (sinTheta1 * cosTheta * cosDLambda)) * r * currentScale();
1521     
1522   } else {
1523     // Sanson-Flamsteed projection, relative to the projection center
1524     double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1525       latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1526
1527     p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1528       
1529   }
1530   
1531 // rotate as necessary
1532   double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS),
1533     sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1534   double rx = cost * p.x() - sint * p.y();
1535   double ry = sint * p.x() + cost * p.y();
1536   return SGVec2d(rx, ry);
1537 }
1538
1539 SGGeod MapWidget::unproject(const SGVec2d& p) const
1540 {
1541   // unrotate, if necessary
1542   double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS),
1543     sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1544   SGVec2d ur(cost * p.x() - sint * p.y(),
1545              sint * p.x() + cost * p.y());
1546
1547   double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1548   SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1549
1550   if (_orthoAzimuthProject) {
1551       double phi = length(p);
1552       double c = asin(phi);
1553       double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1554       double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1555       
1556       double lat = asin(cos(c) * sinTheta1 + ((unscaled.y() * sin(c) * cosTheta1) / phi));
1557       double lon = _projectionCenter.getLongitudeRad() + 
1558         atan((unscaled.x()* sin(c)) / (phi  * cosTheta1 * cos(c) - unscaled.y() * sinTheta1 * sin(c)));
1559       return SGGeod::fromRad(lon, lat);
1560   } else {
1561       double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1562       double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1563       return SGGeod::fromRad(lon, lat);
1564   }
1565 }
1566
1567 double MapWidget::currentScale() const
1568 {
1569   return 1.0 / pow(2.0, _cachedZoom);
1570 }
1571
1572 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1573 {
1574   glBegin(GL_LINE_LOOP);
1575   double advance = (SGD_PI * 2) / nSides;
1576   glVertex2d(center.x(), center.y() + r);
1577   double t=advance;
1578   for (int i=1; i<nSides; ++i) {
1579     glVertex2d(center.x() + (sin(t) * r), center.y() + (cos(t) * r));
1580     t += advance;
1581   }
1582   glEnd();
1583 }
1584
1585 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1586 {
1587   glBegin(GL_LINE_LOOP);
1588   double advance = (SGD_PI * 2) / nSides;
1589   glVertex2d(center.x(), center.y() + r);
1590   double t=advance;
1591   for (int i=1; i<nSides; ++i) {
1592     double rr = (i%2 == 0) ? r : r2;
1593     glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1594     t += advance;
1595   }
1596   glEnd();
1597 }
1598
1599 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1600 {
1601   glBegin(GL_LINES);
1602     glVertex2dv(p1.data());
1603     glVertex2dv(p2.data());
1604   glEnd();
1605 }
1606
1607 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1608 {
1609         std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1610         const int LINE_LEADING = 4;
1611         const int MARGIN = 4;
1612
1613 // measure
1614         int maxWidth = -1, totalHeight = 0;
1615         int lineHeight = legendFont.getStringHeight();
1616
1617         for (unsigned int ln=0; ln<lines.size(); ++ln) {
1618                 totalHeight += lineHeight;
1619                 if (ln > 0) {
1620                         totalHeight += LINE_LEADING;
1621                 }
1622
1623                 int lw = legendFont.getStringWidth(lines[ln].c_str());
1624                 maxWidth = std::max(maxWidth, lw);
1625         } // of line measurement
1626
1627         if (maxWidth < 0) {
1628                 return; // all lines are empty, don't draw
1629         }
1630
1631         totalHeight += MARGIN * 2;
1632
1633 // draw box
1634         puBox box;
1635         box.min[0] = 0;
1636         box.min[1] = -totalHeight;
1637         box.max[0] = maxWidth + (MARGIN * 2);
1638         box.max[1] = 0;
1639         int border = 1;
1640         box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1641
1642 // draw lines
1643         int xPos = pos.x() + MARGIN;
1644         int yPos = pos.y() - (lineHeight + MARGIN);
1645         glColor3f(0.8, 0.8, 0.8);
1646
1647         for (unsigned int ln=0; ln<lines.size(); ++ln) {
1648                 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1649                 yPos -= lineHeight + LINE_LEADING;
1650         }
1651 }
1652
1653 void MapWidget::drawData()
1654 {
1655   std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1656
1657   int hw = _width >> 1,
1658     hh = _height >> 1;
1659   puBox visBox(makePuBox(-hw, -hh, _width, _height));
1660
1661   unsigned int d = 0;
1662   int drawn = 0;
1663   std::vector<MapData*> drawQueue;
1664
1665   bool drawData = _root->getBoolValue("draw-data");
1666   const int MAX_DRAW_DATA = 25;
1667   const int MAX_DRAW = 50;
1668
1669   for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1670     MapData* md = _dataQueue[d];
1671     md->setDataVisible(drawData);
1672
1673     if (md->isClipped(visBox)) {
1674       continue;
1675     }
1676
1677     if (md->overlaps(drawQueue)) {
1678       if (drawData) { // overlapped with data, let's try just the label
1679         md->setDataVisible(false);
1680         if (md->overlaps(drawQueue)) {
1681           continue;
1682         }
1683       } else {
1684         continue;
1685       }
1686     } // of overlaps case
1687
1688     drawQueue.push_back(md);
1689     ++drawn;
1690     if (drawData && (drawn >= MAX_DRAW_DATA)) {
1691       drawData = false;
1692     }
1693   }
1694
1695   // draw lowest-priority first, so higher-priorty items appear on top
1696   std::vector<MapData*>::reverse_iterator r;
1697   for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1698     (*r)->draw();
1699   }
1700
1701   _dataQueue.clear();
1702   KeyDataMap::iterator it = _mapData.begin();
1703   for (; it != _mapData.end(); ) {
1704     it->second->age();
1705     if (it->second->isExpired()) {
1706       delete it->second;
1707       KeyDataMap::iterator cur = it++;
1708       _mapData.erase(cur);
1709     } else {
1710       ++it;
1711     }
1712   } // of expiry iteration
1713 }
1714
1715 bool MapWidget::validDataForKey(void* key)
1716 {
1717   KeyDataMap::iterator it = _mapData.find(key);
1718   if (it == _mapData.end()) {
1719     return false; // no valid data for the key!
1720   }
1721
1722   it->second->resetAge(); // mark data as valid this frame
1723   _dataQueue.push_back(it->second);
1724   return true;
1725 }
1726
1727 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1728 {
1729   KeyDataMap::iterator it = _mapData.find(key);
1730   if (it == _mapData.end()) {
1731     throw sg_exception("no valid data for key!");
1732   }
1733
1734   it->second->setAnchor(anchor);
1735 }
1736
1737 MapData* MapWidget::getOrCreateDataForKey(void* key)
1738 {
1739   KeyDataMap::iterator it = _mapData.find(key);
1740   if (it == _mapData.end()) {
1741     return createDataForKey(key);
1742   }
1743
1744   it->second->resetAge(); // mark data as valid this frame
1745   _dataQueue.push_back(it->second);
1746   return it->second;
1747 }
1748
1749 MapData* MapWidget::createDataForKey(void* key)
1750 {
1751   KeyDataMap::iterator it = _mapData.find(key);
1752   if (it != _mapData.end()) {
1753     throw sg_exception("duplicate data requested for key!");
1754   }
1755
1756   MapData* d =  new MapData(0);
1757   _mapData[key] = d;
1758   _dataQueue.push_back(d);
1759   d->resetAge();
1760   return d;
1761 }
1762
1763 void MapWidget::clearData()
1764 {
1765   KeyDataMap::iterator it = _mapData.begin();
1766   for (; it != _mapData.end(); ++it) {
1767     delete it->second;
1768   }
1769   
1770   _mapData.clear();
1771 }
1772
1773 int MapWidget::displayHeading(double h) const
1774 {
1775   if (_magneticHeadings) {
1776     h -= _magVar->get_magvar() * SG_RADIANS_TO_DEGREES;
1777   }
1778   
1779   SG_NORMALIZE_RANGE(h, 0.0, 360.0);
1780   return SGMiscd::roundToInt(h);
1781 }