5 #include "MapWidget.hxx"
8 #include <algorithm> // for std::sort
9 #include <plib/puAux.h>
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>
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>
30 const char* RULER_LEGEND_KEY = "ruler-legend";
32 /* equatorial and polar earth radius */
33 const float rec = 6378137; // earth radius, equator (?)
34 const float rpol = 6356752.314f; // earth radius, polar (?)
36 /************************************************************************
37 some trigonometric helper functions
38 (translated more or less directly from Alexei Novikovs perl original)
39 *************************************************************************/
41 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
42 static float earth_radius_lat( float lat )
44 double a = cos(lat)/rec;
45 double b = sin(lat)/rpol;
46 return 1.0f / sqrt( a * a + b * b );
49 ///////////////////////////////////////////////////////////////////////////
51 static puBox makePuBox(int x, int y, int w, int h)
61 static bool puBoxIntersect(const puBox& a, const puBox& b)
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]);
68 return (x0 <= x1) && (y0 <= y1);
72 typedef std::vector<MapData*> MapDataVec;
77 static const int HALIGN_LEFT = 1;
78 static const int HALIGN_CENTER = 2;
79 static const int HALIGN_RIGHT = 3;
81 static const int VALIGN_TOP = 1 << 4;
82 static const int VALIGN_CENTER = 2 << 4;
83 static const int VALIGN_BOTTOM = 3 << 4;
85 MapData(int priority) :
91 _offsetDir(HALIGN_LEFT | VALIGN_CENTER),
97 void setLabel(const std::string& label)
99 if (label == _label) {
100 return; // common case, and saves invalidation
107 void setText(const std::string &text)
109 if (_rawText == text) {
110 return; // common case, and saves invalidation
117 void setDataVisible(bool vis) {
118 if (vis == _dataVisible) {
122 if (_rawText.empty()) {
130 static void setFont(puFont f)
133 _fontHeight = f.getStringHeight();
134 _fontDescender = f.getStringDescender();
137 static void setPalette(puColor* pal)
142 void setPriority(int pri)
148 { return _priority; }
150 void setAnchor(const SGVec2d& anchor)
155 void setOffset(int direction, int px)
157 if ((_offsetPx == px) && (_offsetDir == direction)) {
162 _offsetDir = direction;
166 bool isClipped(const puBox& vis) const
169 if ((_width < 1) || (_height < 1)) {
173 return !puBoxIntersect(vis, box());
176 bool overlaps(const MapDataVec& l) const
181 MapDataVec::const_iterator it;
182 for (it = l.begin(); it != l.end(); ++it) {
183 if (puBoxIntersect(b, (*it)->box())) {
186 } // of list iteration
195 _anchor.x() + _offset.x(),
196 _anchor.y() + _offset.y(),
204 int xx = _anchor.x() + _offset.x();
205 int yy = _anchor.y() + _offset.y();
208 puBox box(makePuBox(0,0,_width, _height));
210 box.draw(xx, yy, PUSTYLE_DROPSHADOW, _palette, FALSE, border);
213 int lineHeight = _fontHeight;
214 int xPos = xx + MARGIN;
215 int yPos = yy + _height - (lineHeight + MARGIN);
216 glColor3f(0.8, 0.8, 0.8);
218 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
219 _font.drawString(_lines[ln].c_str(), xPos, yPos);
220 yPos -= lineHeight + LINE_LEADING;
223 glColor3f(0.8, 0.8, 0.8);
224 _font.drawString(_label.c_str(), xx, yy + _fontDescender);
238 bool isExpired() const
239 { return (_age > 100); }
241 static bool order(MapData* a, MapData* b)
243 return a->_priority > b->_priority;
246 void validate() const
266 void measureData() const
268 _lines = simgear::strutils::split(_rawText, "\n");
269 // measure text to find width and height
273 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
274 _height += _fontHeight;
276 _height += LINE_LEADING;
279 int lw = _font.getStringWidth(_lines[ln].c_str());
280 _width = std::max(_width, lw);
281 } // of line measurement
283 if ((_width < 1) || (_height < 1)) {
288 _height += MARGIN * 2;
289 _width += MARGIN * 2;
292 void measureLabel() const
294 if (_label.empty()) {
295 _width = _height = -1;
299 _height = _fontHeight;
300 _width = _font.getStringWidth(_label.c_str());
303 void computeOffset() const
305 _dirtyOffset = false;
306 if ((_width <= 0) || (_height <= 0)) {
313 switch (_offsetDir & 0x0f) {
320 hOffset = -(_width>>1);
324 hOffset = -(_offsetPx + _width);
328 switch (_offsetDir & 0xf0) {
331 vOffset = -(_offsetPx + _height);
335 vOffset = -(_height>>1);
343 _offset = SGVec2d(hOffset, vOffset);
346 static const int LINE_LEADING = 3;
347 static const int MARGIN = 3;
349 mutable bool _dirtyText;
350 mutable bool _dirtyOffset;
352 std::string _rawText;
354 mutable std::vector<std::string> _lines;
356 mutable int _width, _height;
360 mutable SGVec2d _offset;
364 static puColor* _palette;
365 static int _fontHeight;
366 static int _fontDescender;
369 puFont MapData::_font;
370 puColor* MapData::_palette;
371 int MapData::_fontHeight = 0;
372 int MapData::_fontDescender = 0;
374 ///////////////////////////////////////////////////////////////////////////
376 const int MAX_ZOOM = 16;
377 const int SHOW_DETAIL_ZOOM = 8;
378 const int CURSOR_PAN_STEP = 32;
380 MapWidget::MapWidget(int x, int y, int maxX, int maxY) :
381 puObject(x,y,maxX, maxY)
383 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
384 _gps = fgGetNode("/instrumentation/gps");
390 MapData::setFont(legendFont);
391 MapData::setPalette(colour);
393 _magVar = new SGMagVar();
396 MapWidget::~MapWidget()
401 void MapWidget::setProperty(SGPropertyNode_ptr prop)
404 _root->setBoolValue("centre-on-aircraft", true);
405 _root->setBoolValue("draw-data", false);
406 _root->setBoolValue("magnetic-headings", true);
409 void MapWidget::setSize(int w, int h)
411 puObject::setSize(w, h);
418 void MapWidget::doHit( int button, int updown, int x, int y )
420 puObject::doHit(button, updown, x, y);
421 if (updown == PU_DRAG) {
426 if (button == 3) { // mouse-wheel up
428 } else if (button == 4) { // mouse-wheel down
432 if (button != active_mouse_button) {
436 _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
438 if (updown == PU_UP) {
439 puDeactivateWidget();
440 } else if (updown == PU_DOWN) {
441 puSetActiveWidget(this, x, y);
443 if (fgGetKeyModifiers() & KEYMOD_CTRL) {
444 _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
449 void MapWidget::handlePan(int x, int y)
451 SGVec2d delta = SGVec2d(x, y) - _hitLocation;
453 _hitLocation = SGVec2d(x,y);
456 int MapWidget::checkKey (int key, int updown )
458 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
466 pan(SGVec2d(0, -CURSOR_PAN_STEP));
470 pan(SGVec2d(0, CURSOR_PAN_STEP));
474 pan(SGVec2d(CURSOR_PAN_STEP, 0));
478 pan(SGVec2d(-CURSOR_PAN_STEP, 0));
497 void MapWidget::pan(const SGVec2d& delta)
499 _projectionCenter = unproject(-delta);
502 void MapWidget::zoomIn()
509 SG_LOG(SG_GENERAL, SG_INFO, "zoom is now:" << _zoom);
512 void MapWidget::zoomOut()
514 if (_zoom >= MAX_ZOOM) {
519 SG_LOG(SG_GENERAL, SG_INFO, "zoom is now:" << _zoom);
522 void MapWidget::draw(int dx, int dy)
524 _aircraft = SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
525 fgGetDouble("/position/latitude-deg"));
526 _magneticHeadings = _root->getBoolValue("magnetic-headings");
528 if (_root->getBoolValue("centre-on-aircraft")) {
529 _projectionCenter = _aircraft;
532 double julianDate = globals->get_time_params()->getJD();
533 _magVar->update(_projectionCenter, julianDate);
535 bool aircraftUp = _root->getBoolValue("aircraft-heading-up");
537 _upHeading = fgGetDouble("/orientation/heading-deg");
542 SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
543 // compute draw range, including a fudge factor for ILSs and other 'long'
545 _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
547 // drawing operations
548 GLint sx = (int) abox.min[0],
549 sy = (int) abox.min[1];
550 glScissor(dx + sx, dy + sy, _width, _height);
551 glEnable(GL_SCISSOR_TEST);
553 glMatrixMode(GL_MODELVIEW);
555 // cetere drawing about the widget center (which is also the
556 // projection centre)
557 glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
562 int textHeight = legendFont.getStringHeight() + 5;
565 SGVec2d loc = project(_aircraft);
566 glColor3f(1.0, 1.0, 1.0);
567 drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
570 if (_magneticHeadings) {
571 displayHdg = (int) fgGetDouble("/orientation/heading-magnetic-deg");
573 displayHdg = (int) _upHeading;
576 double y = (_height / 2) - textHeight;
578 ::snprintf(buf, 16, "%d", displayHdg);
579 int sw = legendFont.getStringWidth(buf);
580 legendFont.drawString(buf, loc.x() - sw/2, y);
587 drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
588 drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
589 paintAircraftLocation(_aircraft);
596 glDisable(GL_SCISSOR_TEST);
599 void MapWidget::paintRuler()
601 if (_clickGeod == SGGeod()) {
605 SGVec2d acftPos = project(_aircraft);
606 SGVec2d clickPos = project(_clickGeod);
608 glColor4f(0.0, 1.0, 1.0, 0.6);
609 drawLine(acftPos, clickPos);
611 circleAtAlt(clickPos, 8, 10, 5);
613 double dist, az, az2;
614 SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
615 if (_magneticHeadings) {
616 az -= _magVar->get_magvar();
617 SG_NORMALIZE_RANGE(az, 0.0, 360.0);
621 ::snprintf(buffer, 1024, "%03d/%.1fnm",
622 SGMiscd::roundToInt(az), dist * SG_METER_TO_NM);
624 MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
626 d->setAnchor(clickPos);
627 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
628 d->setPriority(20000);
633 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
635 SGVec2d loc = project(aircraftPos);
637 double hdg = fgGetDouble("/orientation/heading-deg");
640 glColor4f(1.0, 1.0, 0.0, 1.0);
642 glTranslated(loc.x(), loc.y(), 0.0);
643 glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
645 const SGVec2d wingspan(12, 0);
646 const SGVec2d nose(0, 8);
647 const SGVec2d tail(0, -14);
648 const SGVec2d tailspan(4,0);
650 drawLine(-wingspan, wingspan);
651 drawLine(nose, tail);
652 drawLine(tail - tailspan, tail + tailspan);
658 void MapWidget::paintRoute()
660 if (_route->numWaypts() < 2) {
664 RoutePath path(_route->waypts());
666 // first pass, draw the actual lines
669 for (int w=0; w<_route->numWaypts(); ++w) {
670 SGGeodVec gv(path.pathForIndex(w));
675 if (w < _route->currentIndex()) {
676 glColor4f(0.5, 0.5, 0.5, 0.7);
678 glColor4f(1.0, 0.0, 1.0, 1.0);
681 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
682 if (wpt->flag(flightgear::WPT_MISS)) {
683 glEnable(GL_LINE_STIPPLE);
684 glLineStipple(1, 0x00FF);
687 glBegin(GL_LINE_STRIP);
688 for (unsigned int i=0; i<gv.size(); ++i) {
689 SGVec2d p = project(gv[i]);
690 glVertex2d(p.x(), p.y());
694 glDisable(GL_LINE_STIPPLE);
698 // second pass, draw waypoint symbols and data
699 for (int w=0; w < _route->numWaypts(); ++w) {
700 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
701 SGGeod g = path.positionForIndex(w);
703 continue; // Vectors or similar
706 SGVec2d p = project(g);
707 glColor4f(1.0, 0.0, 1.0, 1.0);
708 circleAtAlt(p, 8, 12, 5);
710 std::ostringstream legend;
711 legend << wpt->ident();
712 if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
713 legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
716 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
717 legend << '\n' << wpt->speedMach() << "M";
718 } else if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
719 legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
722 MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
723 d->setText(legend.str());
724 d->setLabel(wpt->ident());
726 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
727 d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
729 } // of second waypoint iteration
733 * Round a SGGeod to an arbitrary precision.
734 * For example, passing precision of 0.5 will round to the nearest 0.5 of
735 * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
736 * multiple, and so on.
738 static SGGeod roundGeod(double precision, const SGGeod& g)
740 double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
741 double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
743 return SGGeod::fromDeg(lon * precision, lat * precision);
746 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
748 double minX = SGMiscd::min(a.x(), b.x()),
749 minY = SGMiscd::min(a.y(), b.y()),
750 maxX = SGMiscd::max(a.x(), b.x()),
751 maxY = SGMiscd::max(a.y(), b.y());
753 int hh = _height >> 1, hw = _width >> 1;
755 if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
759 glVertex2dv(a.data());
760 glVertex2dv(b.data());
764 SGVec2d MapWidget::gridPoint(int ix, int iy)
766 int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
767 GridPointCache::iterator it = _gridCache.find(key);
768 if (it != _gridCache.end()) {
772 SGGeod gp = SGGeod::fromDeg(
773 _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
774 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
776 SGVec2d proj = project(gp);
777 _gridCache[key] = proj;
781 void MapWidget::drawLatLonGrid()
784 _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
790 glColor4f(0.8, 0.8, 0.8, 0.4);
798 for (int x = -ix; x < ix; ++x) {
799 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
800 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
801 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
802 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
806 for (int y = -iy; y < iy; ++y) {
807 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
808 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
809 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
810 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
821 void MapWidget::drawGPSData()
823 std::string gpsMode = _gps->getStringValue("mode");
825 SGGeod wp0Geod = SGGeod::fromDeg(
826 _gps->getDoubleValue("wp/wp[0]/longitude-deg"),
827 _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
829 SGGeod wp1Geod = SGGeod::fromDeg(
830 _gps->getDoubleValue("wp/wp[1]/longitude-deg"),
831 _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
834 double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
835 double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
838 if (gpsSpeed > 3.0) { // only draw track line if valid
840 SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
842 glColor4f(1.0, 1.0, 0.0, 1.0);
843 glEnable(GL_LINE_STIPPLE);
844 glLineStipple(1, 0x00FF);
845 drawLine(project(_aircraft), project(trackRadial));
846 glDisable(GL_LINE_STIPPLE);
849 if (gpsMode == "dto") {
850 SGVec2d wp0Pos = project(wp0Geod);
851 SGVec2d wp1Pos = project(wp1Geod);
853 glColor4f(1.0, 0.0, 1.0, 1.0);
854 drawLine(wp0Pos, wp1Pos);
858 if (_gps->getBoolValue("scratch/valid")) {
864 class MapAirportFilter : public FGAirport::AirportFilter
867 MapAirportFilter(SGPropertyNode_ptr nd)
869 _heliports = nd->getBoolValue("show-heliports", false);
870 _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
871 _minLengthFt = nd->getDoubleValue("min-runway-length-ft", 2000.0);
874 virtual FGPositioned::Type maxType() const {
875 return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
878 virtual bool passAirport(FGAirport* aApt) const {
879 if (_hardRunwaysOnly) {
880 return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
888 bool _hardRunwaysOnly;
892 void MapWidget::drawAirports()
894 MapAirportFilter af(_root);
895 FGPositioned::List apts = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &af);
896 for (unsigned int i=0; i<apts.size(); ++i) {
897 drawAirport((FGAirport*) apts[i].get());
901 class NavaidFilter : public FGPositioned::Filter
904 NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
905 _fixes(fixesEnabled),
906 _navaids(navaidsEnabled)
909 virtual bool pass(FGPositioned* aPos) const {
910 if (_fixes && (aPos->type() == FGPositioned::FIX)) {
911 // ignore fixes which end in digits - expirmental
912 if (isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
920 virtual FGPositioned::Type minType() const {
921 return _fixes ? FGPositioned::FIX : FGPositioned::VOR;
924 virtual FGPositioned::Type maxType() const {
925 return _navaids ? FGPositioned::NDB : FGPositioned::FIX;
929 bool _fixes, _navaids;
932 void MapWidget::drawNavaids()
934 bool fixes = _root->getBoolValue("draw-fixes");
935 NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
937 if (f.minType() <= f.maxType()) {
938 FGPositioned::List navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
941 for (unsigned int i=0; i<navs.size(); ++i) {
942 FGPositioned::Type ty = navs[i]->type();
943 if (ty == FGPositioned::NDB) {
944 drawNDB(false, (FGNavRecord*) navs[i].get());
945 } else if (ty == FGPositioned::VOR) {
946 drawVOR(false, (FGNavRecord*) navs[i].get());
947 } else if (ty == FGPositioned::FIX) {
948 drawFix((FGFix*) navs[i].get());
950 } // of navaid iteration
951 } // of navaids || fixes are drawn test
954 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
956 SGVec2d pos = project(ndb->geod());
959 glColor3f(0.0, 1.0, 1.0);
961 glColor3f(0.0, 0.0, 0.0);
964 glEnable(GL_LINE_STIPPLE);
965 glLineStipple(1, 0x00FF);
966 circleAt(pos, 20, 6);
967 circleAt(pos, 20, 10);
968 glDisable(GL_LINE_STIPPLE);
970 if (validDataForKey(ndb)) {
971 setAnchorForKey(ndb, pos);
976 ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
977 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
979 MapData* d = createDataForKey(ndb);
981 d->setLabel(ndb->ident());
983 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
988 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
990 SGVec2d pos = project(vor->geod());
992 glColor3f(0.0, 1.0, 1.0);
994 glColor3f(0.0, 0.0, 1.0);
999 if (validDataForKey(vor)) {
1000 setAnchorForKey(vor, pos);
1005 ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1006 vor->name().c_str(), vor->ident().c_str(),
1007 vor->get_freq() / 100.0);
1009 MapData* d = createDataForKey(vor);
1011 d->setLabel(vor->ident());
1012 d->setPriority(tuned ? 10000 : 100);
1013 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1017 void MapWidget::drawFix(FGFix* fix)
1019 SGVec2d pos = project(fix->geod());
1020 glColor3f(0.0, 0.0, 0.0);
1021 circleAt(pos, 3, 6);
1023 if (_zoom > SHOW_DETAIL_ZOOM) {
1024 return; // hide fix labels beyond a certain zoom level
1027 if (validDataForKey(fix)) {
1028 setAnchorForKey(fix, pos);
1032 MapData* d = createDataForKey(fix);
1033 d->setLabel(fix->ident());
1035 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1039 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1041 if (!radio || radio->getBoolValue("slaved-to-gps", false)
1042 || !radio->getBoolValue("in-range", false)) {
1046 if (radio->getBoolValue("nav-loc", false)) {
1047 drawTunedLocalizer(radio);
1050 // identify the tuned station - unfortunately we don't get lat/lon directly,
1051 // need to do the frequency search again
1052 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1053 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _aircraft);
1054 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1055 // mismatch between navradio selection logic and ours!
1062 SGVec2d pos = project(nav->geod());
1065 double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1066 SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1067 SGVec2d prange = project(range);
1069 SGVec2d norm = normalize(prange - pos);
1070 SGVec2d perp(norm.y(), -norm.x());
1072 circleAt(pos, 64, length(prange - pos));
1073 drawLine(pos, prange);
1075 // draw to/from arrows
1076 SGVec2d midPoint = (pos + prange) * 0.5;
1077 if (radio->getBoolValue("from-flag")) {
1083 SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1084 SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1085 drawLine(midPoint, arrowB);
1086 drawLine(arrowB, arrowC);
1087 drawLine(arrowC, midPoint);
1089 drawLine(pos, (2 * pos) - prange); // reciprocal radial
1092 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1094 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1095 FGNavRecord* loc = globals->get_loclist()->findByFreq(mhz, _aircraft);
1096 if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1097 // mismatch between navradio selection logic and ours!
1101 if (loc->runway()) {
1102 drawILS(true, loc->runway());
1107 void MapWidget::drawObstacle(FGPositioned* obs)
1109 SGVec2d pos = project(obs->geod());
1110 glColor3f(0.0, 0.0, 0.0);
1112 drawLine(pos, pos + SGVec2d());
1116 void MapWidget::drawAirport(FGAirport* apt)
1118 // draw tower location
1119 SGVec2d towerPos = project(apt->getTowerLocation());
1121 if (_zoom <= SHOW_DETAIL_ZOOM) {
1122 glColor3f(1.0, 1.0, 1.0);
1125 drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1126 drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1127 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1128 drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1129 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1132 if (validDataForKey(apt)) {
1133 setAnchorForKey(apt, towerPos);
1136 ::snprintf(buffer, 1024, "%s\n%s",
1137 apt->ident().c_str(), apt->name().c_str());
1139 MapData* d = createDataForKey(apt);
1141 d->setLabel(apt->ident());
1142 d->setPriority(100 + scoreAirportRunways(apt));
1143 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1144 d->setAnchor(towerPos);
1147 if (_zoom > SHOW_DETAIL_ZOOM) {
1151 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1152 FGRunway* rwy = apt->getRunwayByIndex(r);
1153 if (!rwy->isReciprocal()) {
1158 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1159 FGRunway* rwy = apt->getRunwayByIndex(r);
1160 if (!rwy->isReciprocal()) {
1165 drawILS(false, rwy);
1167 } // of runway iteration
1171 int MapWidget::scoreAirportRunways(FGAirport* apt)
1173 bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1174 double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1177 unsigned int numRunways(apt->numRunways());
1178 for (unsigned int r=0; r<numRunways; ++r) {
1179 FGRunway* rwy = apt->getRunwayByIndex(r);
1180 if (rwy->isReciprocal()) {
1184 if (needHardSurface && !rwy->isHardSurface()) {
1188 if (rwy->lengthFt() < minLength) {
1192 int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1193 score += scoreLength;
1194 } // of runways iteration
1199 void MapWidget::drawRunwayPre(FGRunway* rwy)
1201 SGVec2d p1 = project(rwy->begin());
1202 SGVec2d p2 = project(rwy->end());
1205 glColor3f(1.0, 0.0, 1.0);
1209 void MapWidget::drawRunway(FGRunway* rwy)
1212 // optionally show active, stopway, etc
1213 // in legend, show published heading and length
1214 // and threshold elevation
1216 SGVec2d p1 = project(rwy->begin());
1217 SGVec2d p2 = project(rwy->end());
1219 glColor3f(1.0, 1.0, 1.0);
1220 SGVec2d inset = normalize(p2 - p1) * 2;
1222 drawLine(p1 + inset, p2 - inset);
1224 if (validDataForKey(rwy)) {
1225 setAnchorForKey(rwy, (p1 + p2) * 0.5);
1230 ::snprintf(buffer, 1024, "%s/%s\n%3.0f/%3.0f\n%.0f'",
1231 rwy->ident().c_str(),
1232 rwy->reciprocalRunway()->ident().c_str(),
1234 rwy->reciprocalRunway()->headingDeg(),
1237 MapData* d = createDataForKey(rwy);
1239 d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1241 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1242 d->setAnchor((p1 + p2) * 0.5);
1245 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1247 // arrow, tip centered on the landing threshold
1248 // using LOC transmitter position would be more accurate, but
1249 // is visually cluttered
1250 // arrow width is based upon the computed localizer width
1252 FGNavRecord* loc = rwy->ILS();
1253 double halfBeamWidth = loc->localizerWidth() * 0.5;
1254 SGVec2d t = project(rwy->threshold());
1256 double rangeM = loc->get_range() * SG_NM_TO_METER;
1257 double radial = loc->get_multiuse();
1258 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1261 // compute the three end points at the widge end of the arrow
1262 SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1263 SGVec2d endCentre = project(locEnd);
1265 SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1266 SGVec2d endR = project(locEnd);
1268 SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1269 SGVec2d endL = project(locEnd);
1271 // outline two triangles
1274 glColor3f(0.0, 1.0, 1.0);
1276 glColor3f(0.0, 0.0, 1.0);
1279 glBegin(GL_LINE_LOOP);
1280 glVertex2dv(t.data());
1281 glVertex2dv(endCentre.data());
1282 glVertex2dv(endL.data());
1284 glBegin(GL_LINE_LOOP);
1285 glVertex2dv(t.data());
1286 glVertex2dv(endCentre.data());
1287 glVertex2dv(endR.data());
1290 if (validDataForKey(loc)) {
1291 setAnchorForKey(loc, endR);
1296 ::snprintf(buffer, 1024, "%s\n%s\n%3.2fMHz",
1297 loc->name().c_str(), loc->ident().c_str(),loc->get_freq()/100.0);
1299 MapData* d = createDataForKey(loc);
1301 d->setLabel(loc->ident());
1303 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1307 void MapWidget::drawTraffic()
1309 if (!_root->getBoolValue("draw-traffic")) {
1313 if (_zoom > SHOW_DETAIL_ZOOM) {
1317 const SGPropertyNode* ai = fgGetNode("/ai/models", true);
1319 for (int i = 0; i < ai->nChildren(); ++i) {
1320 const SGPropertyNode *model = ai->getChild(i);
1321 // skip bad or dead entries
1322 if (!model || model->getIntValue("id", -1) == -1) {
1326 const std::string& name(model->getName());
1327 SGGeod pos = SGGeod::fromDegFt(
1328 model->getDoubleValue("position/longitude-deg"),
1329 model->getDoubleValue("position/latitude-deg"),
1330 model->getDoubleValue("position/altitude-ft"));
1332 double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
1333 if (dist > _drawRangeNm) {
1337 double heading = model->getDoubleValue("orientation/true-heading-deg");
1338 if ((name == "aircraft") || (name == "multiplayer") ||
1339 (name == "wingman") || (name == "tanker")) {
1340 drawAIAircraft(model, pos, heading);
1341 } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1342 drawAIShip(model, pos, heading);
1344 } // of ai/models iteration
1347 void MapWidget::drawAIAircraft(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1350 SGVec2d p = project(pos);
1352 glColor3f(0.0, 0.0, 0.0);
1354 circleAt(p, 4, 6.0); // black diamond
1356 // draw heading vector
1357 int speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1361 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1362 double distanceM = speedKts * SG_NM_TO_METER * dt;
1366 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1368 drawLine(p, project(advance));
1371 if (validDataForKey((void*) model)) {
1372 setAnchorForKey((void*) model, p);
1376 // draw callsign / altitude / speed
1380 ::snprintf(buffer, 1024, "%s\n%d'\n%dkts",
1381 model->getStringValue("callsign", "<>"),
1382 static_cast<int>(pos.getElevationFt() / 50.0) * 50,
1385 MapData* d = createDataForKey((void*) model);
1387 d->setLabel(model->getStringValue("callsign", "<>"));
1388 d->setPriority(speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1389 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1394 void MapWidget::drawAIShip(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1396 SGVec2d p = project(pos);
1398 glColor3f(0.0, 0.0, 0.5);
1400 circleAt(p, 4, 6.0); // blue diamond (to differentiate from aircraft.
1402 // draw heading vector
1403 int speedKts = static_cast<int>(model->getDoubleValue("velocities/speed-kts"));
1407 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1408 double distanceM = speedKts * SG_NM_TO_METER * dt;
1412 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1414 drawLine(p, project(advance));
1417 if (validDataForKey((void*) model)) {
1418 setAnchorForKey((void*) model, p);
1422 // draw callsign / speed
1424 ::snprintf(buffer, 1024, "%s\n%dkts",
1425 model->getStringValue("name", "<>"),
1428 MapData* d = createDataForKey((void*) model);
1430 d->setLabel(model->getStringValue("name", "<>"));
1431 d->setPriority(speedKts > 2 ? 30 : 10); // low priority for slow moving ships
1432 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1436 SGVec2d MapWidget::project(const SGGeod& geod) const
1438 // Sanson-Flamsteed projection, relative to the projection center
1439 double r = earth_radius_lat(geod.getLatitudeRad());
1440 double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1441 latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1443 SGVec2d p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1445 // rotate as necessary
1446 double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS),
1447 sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1448 double rx = cost * p.x() - sint * p.y();
1449 double ry = sint * p.x() + cost * p.y();
1450 return SGVec2d(rx, ry);
1453 SGGeod MapWidget::unproject(const SGVec2d& p) const
1455 // unrotate, if necessary
1456 double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS),
1457 sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1458 SGVec2d ur(cost * p.x() - sint * p.y(),
1459 sint * p.x() + cost * p.y());
1461 double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1462 SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1464 double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1465 double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1467 return SGGeod::fromRad(lon, lat);
1470 double MapWidget::currentScale() const
1472 return 1.0 / pow(2.0, _zoom);
1475 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1477 glBegin(GL_LINE_LOOP);
1478 double advance = (SGD_PI * 2) / nSides;
1479 glVertex2d(center.x(), center.y() + r);
1481 for (int i=1; i<nSides; ++i) {
1482 glVertex2d(center.x() + (sin(t) * r), center.y() + (cos(t) * r));
1488 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1490 glBegin(GL_LINE_LOOP);
1491 double advance = (SGD_PI * 2) / nSides;
1492 glVertex2d(center.x(), center.y() + r);
1494 for (int i=1; i<nSides; ++i) {
1495 double rr = (i%2 == 0) ? r : r2;
1496 glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1502 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1505 glVertex2dv(p1.data());
1506 glVertex2dv(p2.data());
1510 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1512 std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1513 const int LINE_LEADING = 4;
1514 const int MARGIN = 4;
1517 int maxWidth = -1, totalHeight = 0;
1518 int lineHeight = legendFont.getStringHeight();
1520 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1521 totalHeight += lineHeight;
1523 totalHeight += LINE_LEADING;
1526 int lw = legendFont.getStringWidth(lines[ln].c_str());
1527 maxWidth = std::max(maxWidth, lw);
1528 } // of line measurement
1531 return; // all lines are empty, don't draw
1534 totalHeight += MARGIN * 2;
1539 box.min[1] = -totalHeight;
1540 box.max[0] = maxWidth + (MARGIN * 2);
1543 box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1546 int xPos = pos.x() + MARGIN;
1547 int yPos = pos.y() - (lineHeight + MARGIN);
1548 glColor3f(0.8, 0.8, 0.8);
1550 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1551 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1552 yPos -= lineHeight + LINE_LEADING;
1556 void MapWidget::drawData()
1558 std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1560 int hw = _width >> 1,
1562 puBox visBox(makePuBox(-hw, -hh, _width, _height));
1566 std::vector<MapData*> drawQueue;
1568 bool drawData = _root->getBoolValue("draw-data");
1569 const int MAX_DRAW_DATA = 25;
1570 const int MAX_DRAW = 50;
1572 for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1573 MapData* md = _dataQueue[d];
1574 md->setDataVisible(drawData);
1576 if (md->isClipped(visBox)) {
1580 if (md->overlaps(drawQueue)) {
1581 if (drawData) { // overlapped with data, let's try just the label
1582 md->setDataVisible(false);
1583 if (md->overlaps(drawQueue)) {
1589 } // of overlaps case
1591 drawQueue.push_back(md);
1593 if (drawData && (drawn >= MAX_DRAW_DATA)) {
1598 // draw lowest-priority first, so higher-priorty items appear on top
1599 std::vector<MapData*>::reverse_iterator r;
1600 for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1605 KeyDataMap::iterator it = _mapData.begin();
1606 for (; it != _mapData.end(); ) {
1608 if (it->second->isExpired()) {
1610 KeyDataMap::iterator cur = it++;
1611 _mapData.erase(cur);
1615 } // of expiry iteration
1618 bool MapWidget::validDataForKey(void* key)
1620 KeyDataMap::iterator it = _mapData.find(key);
1621 if (it == _mapData.end()) {
1622 return false; // no valid data for the key!
1625 it->second->resetAge(); // mark data as valid this frame
1626 _dataQueue.push_back(it->second);
1630 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1632 KeyDataMap::iterator it = _mapData.find(key);
1633 if (it == _mapData.end()) {
1634 throw sg_exception("no valid data for key!");
1637 it->second->setAnchor(anchor);
1640 MapData* MapWidget::getOrCreateDataForKey(void* key)
1642 KeyDataMap::iterator it = _mapData.find(key);
1643 if (it == _mapData.end()) {
1644 return createDataForKey(key);
1647 it->second->resetAge(); // mark data as valid this frame
1648 _dataQueue.push_back(it->second);
1652 MapData* MapWidget::createDataForKey(void* key)
1654 KeyDataMap::iterator it = _mapData.find(key);
1655 if (it != _mapData.end()) {
1656 throw sg_exception("duplicate data requested for key!");
1659 MapData* d = new MapData(0);
1661 _dataQueue.push_back(d);