]> git.mxchange.org Git - flightgear.git/blob - src/GUI/MapWidget.cxx
Merge branch 'next' of git@gitorious.org:fg/flightgear into next
[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/route/waypoint.hxx>
12 #include <simgear/sg_inlines.h>
13 #include <simgear/misc/strutils.hxx>
14 #include <simgear/magvar/magvar.hxx>
15 #include <simgear/timing/sg_time.hxx> // for magVar julianDate
16 #include <simgear/structure/exception.hxx>
17
18 #include <Main/globals.hxx>
19 #include <Main/fg_props.hxx>
20 #include <Autopilot/route_mgr.hxx>
21 #include <Navaids/positioned.hxx>
22 #include <Navaids/navrecord.hxx>
23 #include <Navaids/navlist.hxx>
24 #include <Navaids/fix.hxx>
25 #include <Airports/simple.hxx>
26 #include <Airports/runways.hxx>
27 #include <Main/fg_os.hxx>      // fgGetKeyModifiers()
28 #include <Navaids/routePath.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 = 16;
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   _zoom = 6;
387   _width = maxX - x;
388   _height = maxY - y;
389   
390   MapData::setFont(legendFont);
391   MapData::setPalette(colour);
392   
393   _magVar = new SGMagVar();
394 }
395
396 MapWidget::~MapWidget()
397 {
398   delete _magVar;
399 }
400
401 void MapWidget::setProperty(SGPropertyNode_ptr prop)
402 {
403   _root = prop;
404   _root->setBoolValue("centre-on-aircraft", true);
405   _root->setBoolValue("draw-data", false);
406   _root->setBoolValue("magnetic-headings", true);
407 }
408
409 void MapWidget::setSize(int w, int h)
410 {
411   puObject::setSize(w, h);
412
413   _width = w;
414   _height = h;
415
416 }
417
418 void MapWidget::doHit( int button, int updown, int x, int y )
419 {
420   puObject::doHit(button, updown, x, y);  
421   if (updown == PU_DRAG) {    
422     handlePan(x, y);
423     return;
424   }
425   
426   if (button == 3) { // mouse-wheel up
427     zoomIn();
428   } else if (button == 4) { // mouse-wheel down
429     zoomOut();
430   }
431   
432   if (button != active_mouse_button) {
433     return;
434   }
435   
436   _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
437   
438   if (updown == PU_UP) {
439     puDeactivateWidget();
440   } else if (updown == PU_DOWN) {
441     puSetActiveWidget(this, x, y);
442     
443     if (fgGetKeyModifiers() & KEYMOD_CTRL) {
444       _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
445     }
446   }
447 }
448
449 void MapWidget::handlePan(int x, int y)
450 {
451   SGVec2d delta = SGVec2d(x, y) - _hitLocation;
452   pan(delta);
453   _hitLocation = SGVec2d(x,y);
454 }
455
456 int MapWidget::checkKey (int key, int updown )
457 {
458   if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
459     return FALSE ;
460   }
461   
462   switch (key)
463   {
464
465   case PU_KEY_UP:
466     pan(SGVec2d(0, -CURSOR_PAN_STEP));
467     break;
468
469   case PU_KEY_DOWN:
470     pan(SGVec2d(0, CURSOR_PAN_STEP));
471     break ;
472   
473   case PU_KEY_LEFT:
474     pan(SGVec2d(CURSOR_PAN_STEP, 0));
475     break;
476     
477   case PU_KEY_RIGHT:
478     pan(SGVec2d(-CURSOR_PAN_STEP, 0));
479     break;
480   
481   case '-':
482     zoomOut();
483     
484     break;
485     
486   case '=':
487     zoomIn();
488     break;
489   
490   default :
491     return FALSE;
492   }
493
494   return TRUE ;
495 }
496
497 void MapWidget::pan(const SGVec2d& delta)
498 {
499   _projectionCenter = unproject(-delta);
500 }
501
502 void MapWidget::zoomIn()
503 {
504   if (_zoom <= 0) {
505     return;
506   }
507   
508   --_zoom;
509   SG_LOG(SG_GENERAL, SG_INFO, "zoom is now:" << _zoom);
510 }
511
512 void MapWidget::zoomOut()
513 {
514   if (_zoom >= MAX_ZOOM) {
515     return;
516   }
517   
518   ++_zoom;
519   SG_LOG(SG_GENERAL, SG_INFO, "zoom is now:" << _zoom);
520 }
521
522 void MapWidget::draw(int dx, int dy)
523 {
524   _aircraft = SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"), 
525     fgGetDouble("/position/latitude-deg"));
526   _magneticHeadings = _root->getBoolValue("magnetic-headings");
527   
528   if (_root->getBoolValue("centre-on-aircraft")) {
529     _projectionCenter = _aircraft;
530     _root->setBoolValue("centre-on-aircraft", false);
531   }
532   
533   double julianDate = globals->get_time_params()->getJD();
534   _magVar->update(_projectionCenter, julianDate);
535
536   bool aircraftUp = _root->getBoolValue("aircraft-heading-up");
537   if (aircraftUp) {
538     _upHeading = fgGetDouble("/orientation/heading-deg");
539   } else {
540     _upHeading = 0.0;
541   }
542
543   SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
544   // compute draw range, including a fudge factor for ILSs and other 'long'
545   // symbols
546   _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
547
548 // drawing operations
549   GLint sx = (int) abox.min[0],
550     sy = (int) abox.min[1];
551   glScissor(dx + sx, dy + sy, _width, _height);
552   glEnable(GL_SCISSOR_TEST);
553   
554   glMatrixMode(GL_MODELVIEW);
555   glPushMatrix();
556   // cetere drawing about the widget center (which is also the
557   // projection centre)
558   glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
559   
560   drawLatLonGrid();
561   
562   if (aircraftUp) {
563     int textHeight = legendFont.getStringHeight() + 5;
564     
565     // draw heading line
566     SGVec2d loc = project(_aircraft);
567     glColor3f(1.0, 1.0, 1.0);
568     drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
569     
570     int displayHdg;
571     if (_magneticHeadings) {
572       displayHdg = (int) fgGetDouble("/orientation/heading-magnetic-deg");
573     } else {
574       displayHdg = (int) _upHeading;
575     }
576     
577     double y = (_height / 2) - textHeight;
578     char buf[16];
579     ::snprintf(buf, 16, "%d", displayHdg);
580     int sw = legendFont.getStringWidth(buf);
581     legendFont.drawString(buf, loc.x() - sw/2, y);
582   }
583   
584   drawAirports();
585   drawNavaids();
586   drawTraffic();
587   drawGPSData();
588   drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
589   drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
590   paintAircraftLocation(_aircraft);
591   paintRoute();
592   paintRuler();
593   
594   drawData();
595   
596   glPopMatrix();
597   glDisable(GL_SCISSOR_TEST);
598 }
599
600 void MapWidget::paintRuler()
601 {
602   if (_clickGeod == SGGeod()) {
603     return;
604   }
605   
606   SGVec2d acftPos = project(_aircraft);
607   SGVec2d clickPos = project(_clickGeod);
608   
609   glColor4f(0.0, 1.0, 1.0, 0.6);
610   drawLine(acftPos, clickPos);
611   
612   circleAtAlt(clickPos, 8, 10, 5);
613   
614   double dist, az, az2;
615   SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
616   if (_magneticHeadings) {
617     az -= _magVar->get_magvar();
618     SG_NORMALIZE_RANGE(az, 0.0, 360.0);
619   }
620   
621   char buffer[1024];
622         ::snprintf(buffer, 1024, "%03d/%.1fnm",
623                 SGMiscd::roundToInt(az), dist * SG_METER_TO_NM);
624   
625   MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
626   d->setLabel(buffer);
627   d->setAnchor(clickPos);
628   d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
629   d->setPriority(20000);
630
631   
632 }
633
634 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
635 {
636   SGVec2d loc = project(aircraftPos);
637   
638   double hdg = fgGetDouble("/orientation/heading-deg");
639   
640   glLineWidth(2.0);
641   glColor4f(1.0, 1.0, 0.0, 1.0);
642   glPushMatrix();
643   glTranslated(loc.x(), loc.y(), 0.0);
644   glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
645   
646   const SGVec2d wingspan(12, 0);
647   const SGVec2d nose(0, 8);
648   const SGVec2d tail(0, -14);
649   const SGVec2d tailspan(4,0);
650   
651   drawLine(-wingspan, wingspan);
652   drawLine(nose, tail);
653   drawLine(tail - tailspan, tail + tailspan);
654   
655   glPopMatrix();
656   glLineWidth(1.0);
657 }
658
659 void MapWidget::paintRoute()
660 {
661   if (_route->numWaypts() < 2) {
662     return;
663   }
664   
665   RoutePath path(_route->waypts());
666   
667 // first pass, draw the actual lines
668   glLineWidth(2.0);
669   
670   for (int w=0; w<_route->numWaypts(); ++w) {
671     SGGeodVec gv(path.pathForIndex(w));
672     if (gv.empty()) {
673       continue;
674     }
675     
676     if (w < _route->currentIndex()) {
677       glColor4f(0.5, 0.5, 0.5, 0.7);
678     } else {
679       glColor4f(1.0, 0.0, 1.0, 1.0);
680     }
681     
682     flightgear::WayptRef wpt(_route->wayptAtIndex(w));
683     if (wpt->flag(flightgear::WPT_MISS)) {
684       glEnable(GL_LINE_STIPPLE);
685       glLineStipple(1, 0x00FF);
686     }
687     
688     glBegin(GL_LINE_STRIP);
689     for (unsigned int i=0; i<gv.size(); ++i) {
690       SGVec2d p = project(gv[i]);
691       glVertex2d(p.x(), p.y());
692     }
693     
694     glEnd();
695     glDisable(GL_LINE_STIPPLE);
696   }
697   
698   glLineWidth(1.0);
699 // second pass, draw waypoint symbols and data
700   for (int w=0; w < _route->numWaypts(); ++w) {
701     flightgear::WayptRef wpt(_route->wayptAtIndex(w));
702     SGGeod g = path.positionForIndex(w);
703     if (g == SGGeod()) {
704       continue; // Vectors or similar
705     }
706     
707     SGVec2d p = project(g);
708     glColor4f(1.0, 0.0, 1.0, 1.0);
709     circleAtAlt(p, 8, 12, 5);
710     
711     std::ostringstream legend;
712     legend << wpt->ident();
713     if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
714       legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
715     }
716     
717     if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
718       legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
719     }
720         
721     MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
722     d->setText(legend.str());
723     d->setLabel(wpt->ident());
724     d->setAnchor(p);
725     d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
726     d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
727         
728   } // of second waypoint iteration
729 }
730
731 /**
732  * Round a SGGeod to an arbitrary precision. 
733  * For example, passing precision of 0.5 will round to the nearest 0.5 of
734  * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
735  * multiple, and so on.
736  */
737 static SGGeod roundGeod(double precision, const SGGeod& g)
738 {
739   double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
740   double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
741   
742   return SGGeod::fromDeg(lon * precision, lat * precision);
743 }
744
745 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
746 {
747   double minX = SGMiscd::min(a.x(), b.x()),
748     minY = SGMiscd::min(a.y(), b.y()),
749     maxX = SGMiscd::max(a.x(), b.x()),
750     maxY = SGMiscd::max(a.y(), b.y());
751   
752   int hh = _height >> 1, hw = _width >> 1;
753   
754   if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
755     return false;
756   }
757   
758   glVertex2dv(a.data());
759   glVertex2dv(b.data());
760   return true;
761 }
762
763 SGVec2d MapWidget::gridPoint(int ix, int iy)
764 {
765         int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
766         GridPointCache::iterator it = _gridCache.find(key);
767         if (it != _gridCache.end()) {
768                 return it->second;
769         }
770         
771         SGGeod gp = SGGeod::fromDeg(
772     _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
773                 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
774                 
775         SGVec2d proj = project(gp);
776         _gridCache[key] = proj;
777         return proj;
778 }
779
780 void MapWidget::drawLatLonGrid()
781 {
782   _gridSpacing = 1.0;
783   _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
784   _gridCache.clear();
785   
786   int ix = 0;
787   int iy = 0;
788
789   glColor4f(0.8, 0.8, 0.8, 0.4);
790   glBegin(GL_LINES);
791   bool didDraw;
792   do {
793     didDraw = false;
794     ++ix;
795     ++iy;
796     
797     for (int x = -ix; x < ix; ++x) {
798       didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
799       didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
800       didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
801       didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
802
803     }
804     
805     for (int y = -iy; y < iy; ++y) {
806       didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
807       didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
808       didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
809       didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
810     }
811     
812     if (ix > 30) {
813       break;
814     }
815   } while (didDraw);
816   
817   glEnd();
818 }
819
820 void MapWidget::drawGPSData()
821 {
822   std::string gpsMode = _gps->getStringValue("mode");
823   
824   SGGeod wp0Geod = SGGeod::fromDeg(
825         _gps->getDoubleValue("wp/wp[0]/longitude-deg"), 
826         _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
827         
828   SGGeod wp1Geod = SGGeod::fromDeg(
829         _gps->getDoubleValue("wp/wp[1]/longitude-deg"), 
830         _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
831   
832 // draw track line
833   double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
834   double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
835   double az2;
836   
837   if (gpsSpeed > 3.0) { // only draw track line if valid
838     SGGeod trackRadial;
839     SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
840     
841     glColor4f(1.0, 1.0, 0.0, 1.0);
842     glEnable(GL_LINE_STIPPLE);
843     glLineStipple(1, 0x00FF);
844     drawLine(project(_aircraft), project(trackRadial));
845     glDisable(GL_LINE_STIPPLE);
846   }
847   
848   if (gpsMode == "dto") {
849     SGVec2d wp0Pos = project(wp0Geod);
850     SGVec2d wp1Pos = project(wp1Geod);
851     
852     glColor4f(1.0, 0.0, 1.0, 1.0);
853     drawLine(wp0Pos, wp1Pos);
854     
855   }
856     
857   if (_gps->getBoolValue("scratch/valid")) {
858     // draw scratch data
859     
860   }
861 }
862
863 class MapAirportFilter : public FGAirport::AirportFilter
864 {
865 public:
866   MapAirportFilter(SGPropertyNode_ptr nd)
867   {
868     _heliports = nd->getBoolValue("show-heliports", false);
869     _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
870     _minLengthFt = nd->getDoubleValue("min-runway-length-ft", 2000.0);
871   }
872   
873   virtual FGPositioned::Type maxType() const {
874     return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
875   }
876        
877   virtual bool passAirport(FGAirport* aApt) const {
878     if (_hardRunwaysOnly) {
879       return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
880     }
881     
882     return true;
883   }
884
885 private:
886   bool _heliports;
887   bool _hardRunwaysOnly;
888   double _minLengthFt;
889 };
890
891 void MapWidget::drawAirports()
892 {
893   MapAirportFilter af(_root);
894   FGPositioned::List apts = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &af);
895   for (unsigned int i=0; i<apts.size(); ++i) {
896     drawAirport((FGAirport*) apts[i].get());
897   }
898 }
899
900 class NavaidFilter : public FGPositioned::Filter
901 {
902 public:
903   NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
904     _fixes(fixesEnabled),
905     _navaids(navaidsEnabled)
906   {}
907   
908   virtual bool pass(FGPositioned* aPos) const { 
909     if (_fixes && (aPos->type() == FGPositioned::FIX)) {
910       // ignore fixes which end in digits - expirmental
911       if (isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
912         return false;
913       }
914     }
915     
916     return true;
917   }
918    
919   virtual FGPositioned::Type minType() const {
920     return _fixes ? FGPositioned::FIX : FGPositioned::VOR;
921   }
922    
923   virtual FGPositioned::Type maxType() const {
924     return _navaids ? FGPositioned::NDB : FGPositioned::FIX;
925   }
926   
927 private:
928   bool _fixes, _navaids;
929 };
930
931 void MapWidget::drawNavaids()
932 {
933   bool fixes = _root->getBoolValue("draw-fixes");
934   NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
935     
936   if (f.minType() <= f.maxType()) {
937     FGPositioned::List navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
938     
939     glLineWidth(1.0);
940     for (unsigned int i=0; i<navs.size(); ++i) {
941       FGPositioned::Type ty = navs[i]->type();
942       if (ty == FGPositioned::NDB) {
943         drawNDB(false, (FGNavRecord*) navs[i].get());
944       } else if (ty == FGPositioned::VOR) {
945         drawVOR(false, (FGNavRecord*) navs[i].get());
946       } else if (ty == FGPositioned::FIX) {
947         drawFix((FGFix*) navs[i].get());
948       }
949     } // of navaid iteration
950   } // of navaids || fixes are drawn test
951 }
952
953 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
954 {
955   SGVec2d pos = project(ndb->geod());
956   
957   if (tuned) {
958     glColor3f(0.0, 1.0, 1.0);
959   } else {
960     glColor3f(0.0, 0.0, 0.0);
961   }
962   
963   glEnable(GL_LINE_STIPPLE);
964   glLineStipple(1, 0x00FF);
965   circleAt(pos, 20, 6);
966   circleAt(pos, 20, 10);
967   glDisable(GL_LINE_STIPPLE);
968   
969   if (validDataForKey(ndb)) {
970     setAnchorForKey(ndb, pos);
971     return;
972   }
973   
974   char buffer[1024];
975         ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
976                 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
977         
978   MapData* d = createDataForKey(ndb);
979   d->setPriority(40);
980   d->setLabel(ndb->ident());
981   d->setText(buffer);
982   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
983   d->setAnchor(pos);
984
985 }
986
987 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
988 {
989   SGVec2d pos = project(vor->geod());
990   if (tuned) {
991     glColor3f(0.0, 1.0, 1.0);
992   } else {
993     glColor3f(0.0, 0.0, 1.0);
994   }
995   
996   circleAt(pos, 6, 8);
997   
998   if (validDataForKey(vor)) {
999     setAnchorForKey(vor, pos);
1000     return;
1001   }
1002   
1003   char buffer[1024];
1004         ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1005                 vor->name().c_str(), vor->ident().c_str(),
1006     vor->get_freq() / 100.0);
1007         
1008   MapData* d = createDataForKey(vor);
1009   d->setText(buffer);
1010   d->setLabel(vor->ident());
1011   d->setPriority(tuned ? 10000 : 100);
1012   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1013   d->setAnchor(pos);
1014 }
1015
1016 void MapWidget::drawFix(FGFix* fix)
1017 {
1018   SGVec2d pos = project(fix->geod());
1019   glColor3f(0.0, 0.0, 0.0);
1020   circleAt(pos, 3, 6);
1021   
1022   if (_zoom > SHOW_DETAIL_ZOOM) {
1023     return; // hide fix labels beyond a certain zoom level
1024   }
1025
1026   if (validDataForKey(fix)) {
1027     setAnchorForKey(fix, pos);
1028     return;
1029   }
1030   
1031   MapData* d = createDataForKey(fix);
1032   d->setLabel(fix->ident());
1033   d->setPriority(20);
1034   d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1035   d->setAnchor(pos);
1036 }
1037
1038 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1039 {
1040   if (!radio || radio->getBoolValue("slaved-to-gps", false) 
1041         || !radio->getBoolValue("in-range", false)) {
1042     return;
1043   }
1044   
1045   if (radio->getBoolValue("nav-loc", false)) {
1046     drawTunedLocalizer(radio);
1047   }
1048   
1049   // identify the tuned station - unfortunately we don't get lat/lon directly,
1050   // need to do the frequency search again
1051   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1052   FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _aircraft);
1053   if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1054     // mismatch between navradio selection logic and ours!
1055     return;
1056   }
1057   
1058   glLineWidth(1.0);
1059   drawVOR(true, nav);
1060   
1061   SGVec2d pos = project(nav->geod());
1062   SGGeod range;
1063   double az2;
1064   double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1065   SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1066   SGVec2d prange = project(range);
1067   
1068   SGVec2d norm = normalize(prange - pos);
1069   SGVec2d perp(norm.y(), -norm.x());
1070   
1071   circleAt(pos, 64, length(prange - pos));
1072   drawLine(pos, prange);
1073   
1074 // draw to/from arrows
1075   SGVec2d midPoint = (pos + prange) * 0.5;
1076   if (radio->getBoolValue("from-flag")) {
1077     norm = -norm;
1078     perp = -perp;
1079   }
1080   
1081   int sz = 10;
1082   SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1083   SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1084   drawLine(midPoint, arrowB);
1085   drawLine(arrowB, arrowC);
1086   drawLine(arrowC, midPoint);
1087   
1088   drawLine(pos, (2 * pos) - prange); // reciprocal radial
1089 }
1090
1091 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1092 {
1093   double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1094   FGNavRecord* loc = globals->get_loclist()->findByFreq(mhz, _aircraft);
1095   if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1096     // mismatch between navradio selection logic and ours!
1097     return;
1098   }
1099   
1100   if (loc->runway()) {
1101     drawILS(true, loc->runway());
1102   }
1103 }
1104
1105 /*
1106 void MapWidget::drawObstacle(FGPositioned* obs)
1107 {
1108   SGVec2d pos = project(obs->geod());
1109   glColor3f(0.0, 0.0, 0.0);
1110   glLineWidth(2.0);
1111   drawLine(pos, pos + SGVec2d());
1112 }
1113 */
1114
1115 void MapWidget::drawAirport(FGAirport* apt)
1116 {
1117         // draw tower location
1118         SGVec2d towerPos = project(apt->getTowerLocation());
1119   
1120   if (_zoom <= SHOW_DETAIL_ZOOM) {
1121     glColor3f(1.0, 1.0, 1.0);
1122     glLineWidth(1.0);
1123     
1124     drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1125     drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1126     drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1127     drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1128     drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1129   }
1130   
1131   if (validDataForKey(apt)) {
1132     setAnchorForKey(apt, towerPos);
1133   } else {
1134     char buffer[1024];
1135     ::snprintf(buffer, 1024, "%s\n%s",
1136       apt->ident().c_str(), apt->name().c_str());
1137
1138     MapData* d = createDataForKey(apt);
1139     d->setText(buffer);
1140     d->setLabel(apt->ident());
1141     d->setPriority(100 + scoreAirportRunways(apt));
1142     d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1143     d->setAnchor(towerPos);
1144   }
1145   
1146   if (_zoom > SHOW_DETAIL_ZOOM) {
1147     return;
1148   }
1149
1150   for (unsigned int r=0; r<apt->numRunways(); ++r) {
1151     FGRunway* rwy = apt->getRunwayByIndex(r);
1152                 if (!rwy->isReciprocal()) {
1153                         drawRunwayPre(rwy);
1154                 }
1155   }
1156   
1157         for (unsigned int r=0; r<apt->numRunways(); ++r) {
1158                 FGRunway* rwy = apt->getRunwayByIndex(r);
1159                 if (!rwy->isReciprocal()) {
1160                         drawRunway(rwy);
1161                 }
1162                 
1163                 if (rwy->ILS()) {
1164                         drawILS(false, rwy);
1165                 }
1166         } // of runway iteration
1167         
1168 }
1169
1170 int MapWidget::scoreAirportRunways(FGAirport* apt)
1171 {
1172   bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1173   double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1174   
1175   int score = 0;
1176   unsigned int numRunways(apt->numRunways());
1177   for (unsigned int r=0; r<numRunways; ++r) {
1178     FGRunway* rwy = apt->getRunwayByIndex(r);
1179     if (rwy->isReciprocal()) {
1180       continue;
1181     }
1182
1183     if (needHardSurface && !rwy->isHardSurface()) {
1184       continue;
1185     }
1186     
1187     if (rwy->lengthFt() < minLength) {
1188       continue;
1189     }
1190     
1191     int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1192     score += scoreLength;
1193   } // of runways iteration
1194
1195   return score;
1196 }
1197
1198 void MapWidget::drawRunwayPre(FGRunway* rwy)
1199 {
1200   SGVec2d p1 = project(rwy->begin());
1201         SGVec2d p2 = project(rwy->end());
1202         
1203   glLineWidth(4.0);
1204   glColor3f(1.0, 0.0, 1.0);
1205         drawLine(p1, p2);
1206 }
1207
1208 void MapWidget::drawRunway(FGRunway* rwy)
1209 {
1210         // line for runway 
1211         // optionally show active, stopway, etc
1212         // in legend, show published heading and length
1213         // and threshold elevation
1214         
1215   SGVec2d p1 = project(rwy->begin());
1216         SGVec2d p2 = project(rwy->end());
1217   glLineWidth(2.0);
1218   glColor3f(1.0, 1.0, 1.0);
1219   SGVec2d inset = normalize(p2 - p1) * 2;
1220   
1221         drawLine(p1 + inset, p2 - inset);
1222         
1223   if (validDataForKey(rwy)) {
1224     setAnchorForKey(rwy, (p1 + p2) * 0.5);
1225     return;
1226   }
1227   
1228         char buffer[1024];
1229         ::snprintf(buffer, 1024, "%s/%s\n%3.0f/%3.0f\n%.0f'",
1230                 rwy->ident().c_str(),
1231                 rwy->reciprocalRunway()->ident().c_str(),
1232                 rwy->headingDeg(),
1233                 rwy->reciprocalRunway()->headingDeg(),
1234                 rwy->lengthFt());
1235         
1236   MapData* d = createDataForKey(rwy);
1237   d->setText(buffer);
1238   d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1239   d->setPriority(50);
1240   d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1241   d->setAnchor((p1 + p2) * 0.5);
1242 }
1243
1244 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1245 {
1246         // arrow, tip centered on the landing threshold
1247   // using LOC transmitter position would be more accurate, but
1248   // is visually cluttered
1249         // arrow width is based upon the computed localizer width
1250         
1251         FGNavRecord* loc = rwy->ILS();
1252         double halfBeamWidth = loc->localizerWidth() * 0.5;
1253         SGVec2d t = project(rwy->threshold());
1254         SGGeod locEnd;
1255         double rangeM = loc->get_range() * SG_NM_TO_METER;
1256         double radial = loc->get_multiuse();
1257   SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1258         double az2;
1259         
1260 // compute the three end points at the widge end of the arrow
1261         SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1262         SGVec2d endCentre = project(locEnd);
1263         
1264         SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1265         SGVec2d endR = project(locEnd);
1266         
1267         SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1268         SGVec2d endL = project(locEnd);
1269         
1270 // outline two triangles
1271   glLineWidth(1.0);
1272   if (tuned) {
1273     glColor3f(0.0, 1.0, 1.0);
1274   } else {
1275     glColor3f(0.0, 0.0, 1.0);
1276         }
1277   
1278   glBegin(GL_LINE_LOOP);
1279                 glVertex2dv(t.data());
1280                 glVertex2dv(endCentre.data());
1281                 glVertex2dv(endL.data());
1282         glEnd();
1283         glBegin(GL_LINE_LOOP);
1284                 glVertex2dv(t.data());
1285                 glVertex2dv(endCentre.data());
1286                 glVertex2dv(endR.data());
1287         glEnd();
1288 }
1289
1290 void MapWidget::drawTraffic()
1291 {
1292   if (!_root->getBoolValue("draw-traffic")) {
1293     return;
1294   }
1295   
1296   if (_zoom > SHOW_DETAIL_ZOOM) {
1297     return;
1298   }
1299   
1300   const SGPropertyNode* ai = fgGetNode("/ai/models", true);
1301
1302   for (int i = 0; i < ai->nChildren(); ++i) {
1303     const SGPropertyNode *model = ai->getChild(i);
1304     // skip bad or dead entries
1305     if (!model || model->getIntValue("id", -1) < 0) {
1306       continue;
1307     }
1308
1309     const std::string& name(model->getName());
1310     SGGeod pos = SGGeod::fromDegFt(
1311       model->getDoubleValue("position/longitude-deg"),
1312       model->getDoubleValue("position/latitude-deg"),
1313       model->getDoubleValue("position/altitude-ft"));
1314       
1315     double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
1316     if (dist > _drawRangeNm) {
1317       continue;
1318     }
1319     
1320     double heading = model->getDoubleValue("orientation/true-heading-deg");
1321     if ((name == "aircraft") || (name == "multiplayer") || 
1322         (name == "wingman") || (name == "tanker")) {
1323       drawAIAircraft(model, pos, heading);
1324     } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1325       drawAIShip(model, pos, heading);
1326     }
1327   } // of ai/models iteration
1328 }
1329
1330 void MapWidget::drawAIAircraft(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1331 {
1332
1333   SGVec2d p = project(pos);
1334
1335   glColor3f(0.0, 0.0, 0.0);
1336   glLineWidth(2.0);
1337   circleAt(p, 4, 6.0); // black diamond
1338   
1339 // draw heading vector
1340   int speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1341   if (speedKts > 1) {
1342     glLineWidth(1.0);
1343
1344     const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1345     double distanceM = speedKts * SG_NM_TO_METER * dt;
1346     
1347     SGGeod advance;
1348     double az2;
1349     SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1350     
1351     drawLine(p, project(advance));
1352   }
1353     
1354   if (validDataForKey((void*) model)) {
1355     setAnchorForKey((void*) model, p);
1356     return;
1357   }
1358   
1359   // draw callsign / altitude / speed
1360
1361   
1362   char buffer[1024];
1363         ::snprintf(buffer, 1024, "%s\n%d'\n%dkts",
1364                 model->getStringValue("callsign", "<>"),
1365                 static_cast<int>(pos.getElevationFt() / 50.0) * 50,
1366     speedKts);
1367         
1368   MapData* d = createDataForKey((void*) model);
1369   d->setText(buffer);
1370   d->setLabel(model->getStringValue("callsign", "<>"));
1371   d->setPriority(speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1372   d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1373   d->setAnchor(p);
1374
1375 }
1376
1377 void MapWidget::drawAIShip(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1378 {
1379
1380 }
1381
1382 SGVec2d MapWidget::project(const SGGeod& geod) const
1383 {
1384   // Sanson-Flamsteed projection, relative to the projection center
1385   double r = earth_radius_lat(geod.getLatitudeRad());
1386   double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1387     latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1388   
1389   SGVec2d p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1390   
1391 // rotate as necessary
1392   double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS), 
1393     sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1394   double rx = cost * p.x() - sint * p.y();
1395   double ry = sint * p.x() + cost * p.y();
1396   return SGVec2d(rx, ry);
1397 }
1398
1399 SGGeod MapWidget::unproject(const SGVec2d& p) const
1400 {
1401   // unrotate, if necessary
1402   double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS), 
1403     sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1404   SGVec2d ur(cost * p.x() - sint * p.y(), 
1405              sint * p.x() + cost * p.y());
1406   
1407   double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1408   SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1409   
1410   double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1411   double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1412   
1413   return SGGeod::fromRad(lon, lat);
1414 }
1415
1416 double MapWidget::currentScale() const
1417 {
1418   return 1.0 / pow(2.0, _zoom);
1419 }
1420
1421 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1422 {
1423   glBegin(GL_LINE_LOOP);
1424   double advance = (SGD_PI * 2) / nSides;
1425   glVertex2d(center.x(), center.y() + r);
1426   double t=advance;
1427   for (int i=1; i<nSides; ++i) {
1428     glVertex2d(center.x() + (sin(t) * r), center.y() + (cos(t) * r));
1429     t += advance;
1430   }
1431   glEnd();
1432 }
1433
1434 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1435 {
1436   glBegin(GL_LINE_LOOP);
1437   double advance = (SGD_PI * 2) / nSides;
1438   glVertex2d(center.x(), center.y() + r);
1439   double t=advance;
1440   for (int i=1; i<nSides; ++i) {
1441     double rr = (i%2 == 0) ? r : r2;
1442     glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1443     t += advance;
1444   }
1445   glEnd();
1446 }
1447
1448 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1449 {
1450   glBegin(GL_LINES);
1451     glVertex2dv(p1.data());
1452     glVertex2dv(p2.data());
1453   glEnd();
1454 }
1455
1456 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1457 {
1458         std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1459         const int LINE_LEADING = 4;
1460         const int MARGIN = 4;
1461         
1462 // measure
1463         int maxWidth = -1, totalHeight = 0;
1464         int lineHeight = legendFont.getStringHeight();
1465         
1466         for (unsigned int ln=0; ln<lines.size(); ++ln) {
1467                 totalHeight += lineHeight;
1468                 if (ln > 0) {
1469                         totalHeight += LINE_LEADING;
1470                 }
1471                 
1472                 int lw = legendFont.getStringWidth(lines[ln].c_str());
1473                 maxWidth = std::max(maxWidth, lw);
1474         } // of line measurement
1475         
1476         if (maxWidth < 0) {
1477                 return; // all lines are empty, don't draw
1478         }
1479         
1480         totalHeight += MARGIN * 2;
1481
1482 // draw box
1483         puBox box;
1484         box.min[0] = 0;
1485         box.min[1] = -totalHeight;
1486         box.max[0] = maxWidth + (MARGIN * 2);
1487         box.max[1] = 0;
1488         int border = 1;
1489         box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1490         
1491 // draw lines
1492         int xPos = pos.x() + MARGIN;
1493         int yPos = pos.y() - (lineHeight + MARGIN);
1494         glColor3f(0.8, 0.8, 0.8);
1495   
1496         for (unsigned int ln=0; ln<lines.size(); ++ln) {
1497                 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1498                 yPos -= lineHeight + LINE_LEADING;
1499         }
1500 }
1501
1502 void MapWidget::drawData()
1503 {
1504   std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1505   
1506   int hw = _width >> 1, 
1507     hh = _height >> 1;
1508   puBox visBox(makePuBox(-hw, -hh, _width, _height));
1509   
1510   unsigned int d = 0;
1511   int drawn = 0;
1512   std::vector<MapData*> drawQueue;
1513   
1514   bool drawData = _root->getBoolValue("draw-data");
1515   const int MAX_DRAW_DATA = 25;
1516   const int MAX_DRAW = 50;
1517   
1518   for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1519     MapData* md = _dataQueue[d];
1520     md->setDataVisible(drawData);
1521     
1522     if (md->isClipped(visBox)) {
1523       continue;
1524     }
1525     
1526     if (md->overlaps(drawQueue)) {
1527       if (drawData) { // overlapped with data, let's try just the label
1528         md->setDataVisible(false);
1529         if (md->overlaps(drawQueue)) {
1530           continue;
1531         }
1532       } else {
1533         continue;
1534       }
1535     } // of overlaps case
1536     
1537     drawQueue.push_back(md);
1538     ++drawn;
1539     if (drawData && (drawn >= MAX_DRAW_DATA)) {
1540       drawData = false;
1541     }
1542   }
1543     
1544   // draw lowest-priority first, so higher-priorty items appear on top
1545   std::vector<MapData*>::reverse_iterator r;
1546   for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1547     (*r)->draw();
1548   }
1549   
1550   _dataQueue.clear();
1551   KeyDataMap::iterator it = _mapData.begin();
1552   for (; it != _mapData.end(); ) {
1553     it->second->age();
1554     if (it->second->isExpired()) {
1555       delete it->second;
1556       KeyDataMap::iterator cur = it++;
1557       _mapData.erase(cur);
1558     } else {
1559       ++it;
1560     }
1561   } // of expiry iteration
1562 }
1563
1564 bool MapWidget::validDataForKey(void* key)
1565 {
1566   KeyDataMap::iterator it = _mapData.find(key);
1567   if (it == _mapData.end()) {
1568     return false; // no valid data for the key!
1569   }
1570   
1571   it->second->resetAge(); // mark data as valid this frame
1572   _dataQueue.push_back(it->second);
1573   return true;
1574 }
1575
1576 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1577 {
1578   KeyDataMap::iterator it = _mapData.find(key);
1579   if (it == _mapData.end()) {
1580     throw sg_exception("no valid data for key!");
1581   }
1582   
1583   it->second->setAnchor(anchor);
1584 }
1585
1586 MapData* MapWidget::getOrCreateDataForKey(void* key)
1587 {
1588   KeyDataMap::iterator it = _mapData.find(key);
1589   if (it == _mapData.end()) {
1590     return createDataForKey(key);
1591   }
1592   
1593   it->second->resetAge(); // mark data as valid this frame
1594   _dataQueue.push_back(it->second);
1595   return it->second;
1596 }
1597
1598 MapData* MapWidget::createDataForKey(void* key)
1599 {
1600   KeyDataMap::iterator it = _mapData.find(key);
1601   if (it != _mapData.end()) {
1602     throw sg_exception("duplicate data requested for key!");
1603   }
1604   
1605   MapData* d =  new MapData(0);
1606   _mapData[key] = d;
1607   _dataQueue.push_back(d);
1608   d->resetAge();
1609   return d;
1610 }