Debian Codegraph @

src/GUI/MapWidget.cxx

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