5 #include "MapWidget.hxx"
8 #include <algorithm> // for std::sort
9 #include <plib/puAux.h>
11 #include <simgear/sg_inlines.h>
12 #include <simgear/route/waypoint.hxx>
13 #include <simgear/sg_inlines.h>
14 #include <simgear/misc/strutils.hxx>
15 #include <simgear/magvar/magvar.hxx>
16 #include <simgear/timing/sg_time.hxx> // for magVar julianDate
17 #include <simgear/structure/exception.hxx>
19 #include <Main/globals.hxx>
20 #include <Main/fg_props.hxx>
21 #include <Autopilot/route_mgr.hxx>
22 #include <Navaids/positioned.hxx>
23 #include <Navaids/navrecord.hxx>
24 #include <Navaids/navlist.hxx>
25 #include <Navaids/fix.hxx>
26 #include <Airports/simple.hxx>
27 #include <Airports/runways.hxx>
28 #include <Main/fg_os.hxx> // fgGetKeyModifiers()
29 #include <Navaids/routePath.hxx>
31 const char* RULER_LEGEND_KEY = "ruler-legend";
33 /* equatorial and polar earth radius */
34 const float rec = 6378137; // earth radius, equator (?)
35 const float rpol = 6356752.314f; // earth radius, polar (?)
37 /************************************************************************
38 some trigonometric helper functions
39 (translated more or less directly from Alexei Novikovs perl original)
40 *************************************************************************/
42 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
43 static float earth_radius_lat( float lat )
45 double a = cos(lat)/rec;
46 double b = sin(lat)/rpol;
47 return 1.0f / sqrt( a * a + b * b );
50 ///////////////////////////////////////////////////////////////////////////
52 static puBox makePuBox(int x, int y, int w, int h)
62 static bool puBoxIntersect(const puBox& a, const puBox& b)
64 int x0 = SG_MAX2(a.min[0], b.min[0]);
65 int y0 = SG_MAX2(a.min[1], b.min[1]);
66 int x1 = SG_MIN2(a.max[0], b.max[0]);
67 int y1 = SG_MIN2(a.max[1], b.max[1]);
69 return (x0 <= x1) && (y0 <= y1);
73 typedef std::vector<MapData*> MapDataVec;
78 static const int HALIGN_LEFT = 1;
79 static const int HALIGN_CENTER = 2;
80 static const int HALIGN_RIGHT = 3;
82 static const int VALIGN_TOP = 1 << 4;
83 static const int VALIGN_CENTER = 2 << 4;
84 static const int VALIGN_BOTTOM = 3 << 4;
86 MapData(int priority) :
92 _offsetDir(HALIGN_LEFT | VALIGN_CENTER),
98 void setLabel(const std::string& label)
100 if (label == _label) {
101 return; // common case, and saves invalidation
108 void setText(const std::string &text)
110 if (_rawText == text) {
111 return; // common case, and saves invalidation
118 void setDataVisible(bool vis) {
119 if (vis == _dataVisible) {
123 if (_rawText.empty()) {
131 static void setFont(puFont f)
134 _fontHeight = f.getStringHeight();
135 _fontDescender = f.getStringDescender();
138 static void setPalette(puColor* pal)
143 void setPriority(int pri)
149 { return _priority; }
151 void setAnchor(const SGVec2d& anchor)
156 void setOffset(int direction, int px)
158 if ((_offsetPx == px) && (_offsetDir == direction)) {
163 _offsetDir = direction;
167 bool isClipped(const puBox& vis) const
170 if ((_width < 1) || (_height < 1)) {
174 return !puBoxIntersect(vis, box());
177 bool overlaps(const MapDataVec& l) const
182 MapDataVec::const_iterator it;
183 for (it = l.begin(); it != l.end(); ++it) {
184 if (puBoxIntersect(b, (*it)->box())) {
187 } // of list iteration
196 _anchor.x() + _offset.x(),
197 _anchor.y() + _offset.y(),
205 int xx = _anchor.x() + _offset.x();
206 int yy = _anchor.y() + _offset.y();
209 puBox box(makePuBox(0,0,_width, _height));
211 box.draw(xx, yy, PUSTYLE_DROPSHADOW, _palette, FALSE, border);
214 int lineHeight = _fontHeight;
215 int xPos = xx + MARGIN;
216 int yPos = yy + _height - (lineHeight + MARGIN);
217 glColor3f(0.8, 0.8, 0.8);
219 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
220 _font.drawString(_lines[ln].c_str(), xPos, yPos);
221 yPos -= lineHeight + LINE_LEADING;
224 glColor3f(0.8, 0.8, 0.8);
225 _font.drawString(_label.c_str(), xx, yy + _fontDescender);
239 bool isExpired() const
240 { return (_age > 100); }
242 static bool order(MapData* a, MapData* b)
244 return a->_priority > b->_priority;
247 void validate() const
267 void measureData() const
269 _lines = simgear::strutils::split(_rawText, "\n");
270 // measure text to find width and height
274 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
275 _height += _fontHeight;
277 _height += LINE_LEADING;
280 int lw = _font.getStringWidth(_lines[ln].c_str());
281 _width = std::max(_width, lw);
282 } // of line measurement
284 if ((_width < 1) || (_height < 1)) {
289 _height += MARGIN * 2;
290 _width += MARGIN * 2;
293 void measureLabel() const
295 if (_label.empty()) {
296 _width = _height = -1;
300 _height = _fontHeight;
301 _width = _font.getStringWidth(_label.c_str());
304 void computeOffset() const
306 _dirtyOffset = false;
307 if ((_width <= 0) || (_height <= 0)) {
314 switch (_offsetDir & 0x0f) {
321 hOffset = -(_width>>1);
325 hOffset = -(_offsetPx + _width);
329 switch (_offsetDir & 0xf0) {
332 vOffset = -(_offsetPx + _height);
336 vOffset = -(_height>>1);
344 _offset = SGVec2d(hOffset, vOffset);
347 static const int LINE_LEADING = 3;
348 static const int MARGIN = 3;
350 mutable bool _dirtyText;
351 mutable bool _dirtyOffset;
353 std::string _rawText;
355 mutable std::vector<std::string> _lines;
357 mutable int _width, _height;
361 mutable SGVec2d _offset;
365 static puColor* _palette;
366 static int _fontHeight;
367 static int _fontDescender;
370 puFont MapData::_font;
371 puColor* MapData::_palette;
372 int MapData::_fontHeight = 0;
373 int MapData::_fontDescender = 0;
375 ///////////////////////////////////////////////////////////////////////////
377 const int MAX_ZOOM = 16;
378 const int SHOW_DETAIL_ZOOM = 8;
379 const int CURSOR_PAN_STEP = 32;
381 MapWidget::MapWidget(int x, int y, int maxX, int maxY) :
382 puObject(x,y,maxX, maxY)
384 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
385 _gps = fgGetNode("/instrumentation/gps");
391 MapData::setFont(legendFont);
392 MapData::setPalette(colour);
394 _magVar = new SGMagVar();
397 MapWidget::~MapWidget()
402 void MapWidget::setProperty(SGPropertyNode_ptr prop)
405 int zoom = _root->getBoolValue("zoom", -1);
407 _root->setIntValue("zoom", 6); // default zoom
410 _root->setBoolValue("centre-on-aircraft", true);
411 _root->setBoolValue("draw-data", false);
412 _root->setBoolValue("magnetic-headings", true);
415 void MapWidget::setSize(int w, int h)
417 puObject::setSize(w, h);
424 void MapWidget::doHit( int button, int updown, int x, int y )
426 puObject::doHit(button, updown, x, y);
427 if (updown == PU_DRAG) {
432 if (button == 3) { // mouse-wheel up
434 } else if (button == 4) { // mouse-wheel down
438 if (button != active_mouse_button) {
442 _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
444 if (updown == PU_UP) {
445 puDeactivateWidget();
446 } else if (updown == PU_DOWN) {
447 puSetActiveWidget(this, x, y);
449 if (fgGetKeyModifiers() & KEYMOD_CTRL) {
450 _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
455 void MapWidget::handlePan(int x, int y)
457 SGVec2d delta = SGVec2d(x, y) - _hitLocation;
459 _hitLocation = SGVec2d(x,y);
462 int MapWidget::checkKey (int key, int updown )
464 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
472 pan(SGVec2d(0, -CURSOR_PAN_STEP));
476 pan(SGVec2d(0, CURSOR_PAN_STEP));
480 pan(SGVec2d(CURSOR_PAN_STEP, 0));
484 pan(SGVec2d(-CURSOR_PAN_STEP, 0));
503 void MapWidget::pan(const SGVec2d& delta)
506 _projectionCenter = unproject(-delta);
509 int MapWidget::zoom() const
511 int z = _root->getIntValue("zoom");
512 SG_CLAMP_RANGE(z, 0, MAX_ZOOM);
516 void MapWidget::zoomIn()
522 _root->setIntValue("zoom", zoom() - 1);
525 void MapWidget::zoomOut()
527 if (zoom() >= MAX_ZOOM) {
531 _root->setIntValue("zoom", zoom() + 1);
534 void MapWidget::draw(int dx, int dy)
536 _aircraft = SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
537 fgGetDouble("/position/latitude-deg"));
538 _magneticHeadings = _root->getBoolValue("magnetic-headings");
542 _root->setBoolValue("centre-on-aircraft", false);
545 else if (_root->getBoolValue("centre-on-aircraft")) {
546 _projectionCenter = _aircraft;
549 double julianDate = globals->get_time_params()->getJD();
550 _magVar->update(_projectionCenter, julianDate);
552 bool aircraftUp = _root->getBoolValue("aircraft-heading-up");
554 _upHeading = fgGetDouble("/orientation/heading-deg");
559 _cachedZoom = zoom();
560 SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
561 // compute draw range, including a fudge factor for ILSs and other 'long'
563 _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
565 // drawing operations
566 GLint sx = (int) abox.min[0],
567 sy = (int) abox.min[1];
568 glScissor(dx + sx, dy + sy, _width, _height);
569 glEnable(GL_SCISSOR_TEST);
571 glMatrixMode(GL_MODELVIEW);
573 // cetere drawing about the widget center (which is also the
574 // projection centre)
575 glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
580 int textHeight = legendFont.getStringHeight() + 5;
583 SGVec2d loc = project(_aircraft);
584 glColor3f(1.0, 1.0, 1.0);
585 drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
588 if (_magneticHeadings) {
589 displayHdg = (int) fgGetDouble("/orientation/heading-magnetic-deg");
591 displayHdg = (int) _upHeading;
594 double y = (_height / 2) - textHeight;
596 ::snprintf(buf, 16, "%d", displayHdg);
597 int sw = legendFont.getStringWidth(buf);
598 legendFont.drawString(buf, loc.x() - sw/2, y);
605 drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
606 drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
607 paintAircraftLocation(_aircraft);
614 glDisable(GL_SCISSOR_TEST);
617 void MapWidget::paintRuler()
619 if (_clickGeod == SGGeod()) {
623 SGVec2d acftPos = project(_aircraft);
624 SGVec2d clickPos = project(_clickGeod);
626 glColor4f(0.0, 1.0, 1.0, 0.6);
627 drawLine(acftPos, clickPos);
629 circleAtAlt(clickPos, 8, 10, 5);
631 double dist, az, az2;
632 SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
633 if (_magneticHeadings) {
634 az -= _magVar->get_magvar();
635 SG_NORMALIZE_RANGE(az, 0.0, 360.0);
639 ::snprintf(buffer, 1024, "%03d/%.1fnm",
640 SGMiscd::roundToInt(az), dist * SG_METER_TO_NM);
642 MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
644 d->setAnchor(clickPos);
645 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
646 d->setPriority(20000);
651 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
653 SGVec2d loc = project(aircraftPos);
655 double hdg = fgGetDouble("/orientation/heading-deg");
658 glColor4f(1.0, 1.0, 0.0, 1.0);
660 glTranslated(loc.x(), loc.y(), 0.0);
661 glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
663 const SGVec2d wingspan(12, 0);
664 const SGVec2d nose(0, 8);
665 const SGVec2d tail(0, -14);
666 const SGVec2d tailspan(4,0);
668 drawLine(-wingspan, wingspan);
669 drawLine(nose, tail);
670 drawLine(tail - tailspan, tail + tailspan);
676 void MapWidget::paintRoute()
678 if (_route->numWaypts() < 2) {
682 RoutePath path(_route->waypts());
684 // first pass, draw the actual lines
687 for (int w=0; w<_route->numWaypts(); ++w) {
688 SGGeodVec gv(path.pathForIndex(w));
693 if (w < _route->currentIndex()) {
694 glColor4f(0.5, 0.5, 0.5, 0.7);
696 glColor4f(1.0, 0.0, 1.0, 1.0);
699 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
700 if (wpt->flag(flightgear::WPT_MISS)) {
701 glEnable(GL_LINE_STIPPLE);
702 glLineStipple(1, 0x00FF);
705 glBegin(GL_LINE_STRIP);
706 for (unsigned int i=0; i<gv.size(); ++i) {
707 SGVec2d p = project(gv[i]);
708 glVertex2d(p.x(), p.y());
712 glDisable(GL_LINE_STIPPLE);
716 // second pass, draw waypoint symbols and data
717 for (int w=0; w < _route->numWaypts(); ++w) {
718 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
719 SGGeod g = path.positionForIndex(w);
721 continue; // Vectors or similar
724 SGVec2d p = project(g);
725 glColor4f(1.0, 0.0, 1.0, 1.0);
726 circleAtAlt(p, 8, 12, 5);
728 std::ostringstream legend;
729 legend << wpt->ident();
730 if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
731 legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
734 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
735 legend << '\n' << wpt->speedMach() << "M";
736 } else if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
737 legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
740 MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
741 d->setText(legend.str());
742 d->setLabel(wpt->ident());
744 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
745 d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
747 } // of second waypoint iteration
751 * Round a SGGeod to an arbitrary precision.
752 * For example, passing precision of 0.5 will round to the nearest 0.5 of
753 * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
754 * multiple, and so on.
756 static SGGeod roundGeod(double precision, const SGGeod& g)
758 double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
759 double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
761 return SGGeod::fromDeg(lon * precision, lat * precision);
764 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
766 double minX = SGMiscd::min(a.x(), b.x()),
767 minY = SGMiscd::min(a.y(), b.y()),
768 maxX = SGMiscd::max(a.x(), b.x()),
769 maxY = SGMiscd::max(a.y(), b.y());
771 int hh = _height >> 1, hw = _width >> 1;
773 if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
777 glVertex2dv(a.data());
778 glVertex2dv(b.data());
782 SGVec2d MapWidget::gridPoint(int ix, int iy)
784 int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
785 GridPointCache::iterator it = _gridCache.find(key);
786 if (it != _gridCache.end()) {
790 SGGeod gp = SGGeod::fromDeg(
791 _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
792 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
794 SGVec2d proj = project(gp);
795 _gridCache[key] = proj;
799 void MapWidget::drawLatLonGrid()
802 _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
808 glColor4f(0.8, 0.8, 0.8, 0.4);
816 for (int x = -ix; x < ix; ++x) {
817 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
818 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
819 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
820 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
824 for (int y = -iy; y < iy; ++y) {
825 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
826 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
827 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
828 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
839 void MapWidget::drawGPSData()
841 std::string gpsMode = _gps->getStringValue("mode");
843 SGGeod wp0Geod = SGGeod::fromDeg(
844 _gps->getDoubleValue("wp/wp[0]/longitude-deg"),
845 _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
847 SGGeod wp1Geod = SGGeod::fromDeg(
848 _gps->getDoubleValue("wp/wp[1]/longitude-deg"),
849 _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
852 double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
853 double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
856 if (gpsSpeed > 3.0) { // only draw track line if valid
858 SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
860 glColor4f(1.0, 1.0, 0.0, 1.0);
861 glEnable(GL_LINE_STIPPLE);
862 glLineStipple(1, 0x00FF);
863 drawLine(project(_aircraft), project(trackRadial));
864 glDisable(GL_LINE_STIPPLE);
867 if (gpsMode == "dto") {
868 SGVec2d wp0Pos = project(wp0Geod);
869 SGVec2d wp1Pos = project(wp1Geod);
871 glColor4f(1.0, 0.0, 1.0, 1.0);
872 drawLine(wp0Pos, wp1Pos);
876 if (_gps->getBoolValue("scratch/valid")) {
882 class MapAirportFilter : public FGAirport::AirportFilter
885 MapAirportFilter(SGPropertyNode_ptr nd)
887 _heliports = nd->getBoolValue("show-heliports", false);
888 _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
889 _minLengthFt = nd->getDoubleValue("min-runway-length-ft", 2000.0);
892 virtual FGPositioned::Type maxType() const {
893 return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
896 virtual bool passAirport(FGAirport* aApt) const {
897 if (_hardRunwaysOnly) {
898 return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
906 bool _hardRunwaysOnly;
910 void MapWidget::drawAirports()
912 MapAirportFilter af(_root);
913 FGPositioned::List apts = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &af);
914 for (unsigned int i=0; i<apts.size(); ++i) {
915 drawAirport((FGAirport*) apts[i].get());
919 class NavaidFilter : public FGPositioned::Filter
922 NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
923 _fixes(fixesEnabled),
924 _navaids(navaidsEnabled)
927 virtual bool pass(FGPositioned* aPos) const {
928 if (_fixes && (aPos->type() == FGPositioned::FIX)) {
929 // ignore fixes which end in digits - expirmental
930 if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
938 virtual FGPositioned::Type minType() const {
939 return _fixes ? FGPositioned::FIX : FGPositioned::VOR;
942 virtual FGPositioned::Type maxType() const {
943 return _navaids ? FGPositioned::NDB : FGPositioned::FIX;
947 bool _fixes, _navaids;
950 void MapWidget::drawNavaids()
952 bool fixes = _root->getBoolValue("draw-fixes");
953 NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
955 if (f.minType() <= f.maxType()) {
956 FGPositioned::List navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
959 for (unsigned int i=0; i<navs.size(); ++i) {
960 FGPositioned::Type ty = navs[i]->type();
961 if (ty == FGPositioned::NDB) {
962 drawNDB(false, (FGNavRecord*) navs[i].get());
963 } else if (ty == FGPositioned::VOR) {
964 drawVOR(false, (FGNavRecord*) navs[i].get());
965 } else if (ty == FGPositioned::FIX) {
966 drawFix((FGFix*) navs[i].get());
968 } // of navaid iteration
969 } // of navaids || fixes are drawn test
972 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
974 SGVec2d pos = project(ndb->geod());
977 glColor3f(0.0, 1.0, 1.0);
979 glColor3f(0.0, 0.0, 0.0);
982 glEnable(GL_LINE_STIPPLE);
983 glLineStipple(1, 0x00FF);
984 circleAt(pos, 20, 6);
985 circleAt(pos, 20, 10);
986 glDisable(GL_LINE_STIPPLE);
988 if (validDataForKey(ndb)) {
989 setAnchorForKey(ndb, pos);
994 ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
995 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
997 MapData* d = createDataForKey(ndb);
999 d->setLabel(ndb->ident());
1001 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1006 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
1008 SGVec2d pos = project(vor->geod());
1010 glColor3f(0.0, 1.0, 1.0);
1012 glColor3f(0.0, 0.0, 1.0);
1015 circleAt(pos, 6, 8);
1017 if (validDataForKey(vor)) {
1018 setAnchorForKey(vor, pos);
1023 ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1024 vor->name().c_str(), vor->ident().c_str(),
1025 vor->get_freq() / 100.0);
1027 MapData* d = createDataForKey(vor);
1029 d->setLabel(vor->ident());
1030 d->setPriority(tuned ? 10000 : 100);
1031 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1035 void MapWidget::drawFix(FGFix* fix)
1037 SGVec2d pos = project(fix->geod());
1038 glColor3f(0.0, 0.0, 0.0);
1039 circleAt(pos, 3, 6);
1041 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1042 return; // hide fix labels beyond a certain zoom level
1045 if (validDataForKey(fix)) {
1046 setAnchorForKey(fix, pos);
1050 MapData* d = createDataForKey(fix);
1051 d->setLabel(fix->ident());
1053 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1057 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1059 if (!radio || radio->getBoolValue("slaved-to-gps", false)
1060 || !radio->getBoolValue("in-range", false)) {
1064 if (radio->getBoolValue("nav-loc", false)) {
1065 drawTunedLocalizer(radio);
1068 // identify the tuned station - unfortunately we don't get lat/lon directly,
1069 // need to do the frequency search again
1070 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1071 FGNavRecord* nav = globals->get_navlist()->findByFreq(mhz, _aircraft);
1072 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1073 // mismatch between navradio selection logic and ours!
1080 SGVec2d pos = project(nav->geod());
1083 double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1084 SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1085 SGVec2d prange = project(range);
1087 SGVec2d norm = normalize(prange - pos);
1088 SGVec2d perp(norm.y(), -norm.x());
1090 circleAt(pos, 64, length(prange - pos));
1091 drawLine(pos, prange);
1093 // draw to/from arrows
1094 SGVec2d midPoint = (pos + prange) * 0.5;
1095 if (radio->getBoolValue("from-flag")) {
1101 SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1102 SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1103 drawLine(midPoint, arrowB);
1104 drawLine(arrowB, arrowC);
1105 drawLine(arrowC, midPoint);
1107 drawLine(pos, (2 * pos) - prange); // reciprocal radial
1110 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1112 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1113 FGNavRecord* loc = globals->get_loclist()->findByFreq(mhz, _aircraft);
1114 if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1115 // mismatch between navradio selection logic and ours!
1119 if (loc->runway()) {
1120 drawILS(true, loc->runway());
1125 void MapWidget::drawObstacle(FGPositioned* obs)
1127 SGVec2d pos = project(obs->geod());
1128 glColor3f(0.0, 0.0, 0.0);
1130 drawLine(pos, pos + SGVec2d());
1134 void MapWidget::drawAirport(FGAirport* apt)
1136 // draw tower location
1137 SGVec2d towerPos = project(apt->getTowerLocation());
1139 if (_cachedZoom <= SHOW_DETAIL_ZOOM) {
1140 glColor3f(1.0, 1.0, 1.0);
1143 drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1144 drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1145 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1146 drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1147 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1150 if (validDataForKey(apt)) {
1151 setAnchorForKey(apt, towerPos);
1154 ::snprintf(buffer, 1024, "%s\n%s",
1155 apt->ident().c_str(), apt->name().c_str());
1157 MapData* d = createDataForKey(apt);
1159 d->setLabel(apt->ident());
1160 d->setPriority(100 + scoreAirportRunways(apt));
1161 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1162 d->setAnchor(towerPos);
1165 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1169 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1170 FGRunway* rwy = apt->getRunwayByIndex(r);
1171 if (!rwy->isReciprocal()) {
1176 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1177 FGRunway* rwy = apt->getRunwayByIndex(r);
1178 if (!rwy->isReciprocal()) {
1183 drawILS(false, rwy);
1185 } // of runway iteration
1189 int MapWidget::scoreAirportRunways(FGAirport* apt)
1191 bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1192 double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1195 unsigned int numRunways(apt->numRunways());
1196 for (unsigned int r=0; r<numRunways; ++r) {
1197 FGRunway* rwy = apt->getRunwayByIndex(r);
1198 if (rwy->isReciprocal()) {
1202 if (needHardSurface && !rwy->isHardSurface()) {
1206 if (rwy->lengthFt() < minLength) {
1210 int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1211 score += scoreLength;
1212 } // of runways iteration
1217 void MapWidget::drawRunwayPre(FGRunway* rwy)
1219 SGVec2d p1 = project(rwy->begin());
1220 SGVec2d p2 = project(rwy->end());
1223 glColor3f(1.0, 0.0, 1.0);
1227 void MapWidget::drawRunway(FGRunway* rwy)
1230 // optionally show active, stopway, etc
1231 // in legend, show published heading and length
1232 // and threshold elevation
1234 SGVec2d p1 = project(rwy->begin());
1235 SGVec2d p2 = project(rwy->end());
1237 glColor3f(1.0, 1.0, 1.0);
1238 SGVec2d inset = normalize(p2 - p1) * 2;
1240 drawLine(p1 + inset, p2 - inset);
1242 if (validDataForKey(rwy)) {
1243 setAnchorForKey(rwy, (p1 + p2) * 0.5);
1248 ::snprintf(buffer, 1024, "%s/%s\n%3.0f/%3.0f\n%.0f'",
1249 rwy->ident().c_str(),
1250 rwy->reciprocalRunway()->ident().c_str(),
1252 rwy->reciprocalRunway()->headingDeg(),
1255 MapData* d = createDataForKey(rwy);
1257 d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1259 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1260 d->setAnchor((p1 + p2) * 0.5);
1263 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1265 // arrow, tip centered on the landing threshold
1266 // using LOC transmitter position would be more accurate, but
1267 // is visually cluttered
1268 // arrow width is based upon the computed localizer width
1270 FGNavRecord* loc = rwy->ILS();
1271 double halfBeamWidth = loc->localizerWidth() * 0.5;
1272 SGVec2d t = project(rwy->threshold());
1274 double rangeM = loc->get_range() * SG_NM_TO_METER;
1275 double radial = loc->get_multiuse();
1276 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1279 // compute the three end points at the widge end of the arrow
1280 SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1281 SGVec2d endCentre = project(locEnd);
1283 SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1284 SGVec2d endR = project(locEnd);
1286 SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1287 SGVec2d endL = project(locEnd);
1289 // outline two triangles
1292 glColor3f(0.0, 1.0, 1.0);
1294 glColor3f(0.0, 0.0, 1.0);
1297 glBegin(GL_LINE_LOOP);
1298 glVertex2dv(t.data());
1299 glVertex2dv(endCentre.data());
1300 glVertex2dv(endL.data());
1302 glBegin(GL_LINE_LOOP);
1303 glVertex2dv(t.data());
1304 glVertex2dv(endCentre.data());
1305 glVertex2dv(endR.data());
1308 if (validDataForKey(loc)) {
1309 setAnchorForKey(loc, endR);
1314 ::snprintf(buffer, 1024, "%s\n%s\n%3.2fMHz",
1315 loc->name().c_str(), loc->ident().c_str(),loc->get_freq()/100.0);
1317 MapData* d = createDataForKey(loc);
1319 d->setLabel(loc->ident());
1321 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1325 void MapWidget::drawTraffic()
1327 if (!_root->getBoolValue("draw-traffic")) {
1331 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1335 const SGPropertyNode* ai = fgGetNode("/ai/models", true);
1337 for (int i = 0; i < ai->nChildren(); ++i) {
1338 const SGPropertyNode *model = ai->getChild(i);
1339 // skip bad or dead entries
1340 if (!model || model->getIntValue("id", -1) == -1) {
1344 const std::string& name(model->getName());
1345 SGGeod pos = SGGeod::fromDegFt(
1346 model->getDoubleValue("position/longitude-deg"),
1347 model->getDoubleValue("position/latitude-deg"),
1348 model->getDoubleValue("position/altitude-ft"));
1350 double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
1351 if (dist > _drawRangeNm) {
1355 double heading = model->getDoubleValue("orientation/true-heading-deg");
1356 if ((name == "aircraft") || (name == "multiplayer") ||
1357 (name == "wingman") || (name == "tanker")) {
1358 drawAIAircraft(model, pos, heading);
1359 } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1360 drawAIShip(model, pos, heading);
1362 } // of ai/models iteration
1365 void MapWidget::drawAIAircraft(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1368 SGVec2d p = project(pos);
1370 glColor3f(0.0, 0.0, 0.0);
1372 circleAt(p, 4, 6.0); // black diamond
1374 // draw heading vector
1375 int speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1379 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1380 double distanceM = speedKts * SG_NM_TO_METER * dt;
1384 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1386 drawLine(p, project(advance));
1389 if (validDataForKey((void*) model)) {
1390 setAnchorForKey((void*) model, p);
1394 // draw callsign / altitude / speed
1398 ::snprintf(buffer, 1024, "%s\n%d'\n%dkts",
1399 model->getStringValue("callsign", "<>"),
1400 static_cast<int>(pos.getElevationFt() / 50.0) * 50,
1403 MapData* d = createDataForKey((void*) model);
1405 d->setLabel(model->getStringValue("callsign", "<>"));
1406 d->setPriority(speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1407 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1412 void MapWidget::drawAIShip(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1414 SGVec2d p = project(pos);
1416 glColor3f(0.0, 0.0, 0.5);
1418 circleAt(p, 4, 6.0); // blue diamond (to differentiate from aircraft.
1420 // draw heading vector
1421 int speedKts = static_cast<int>(model->getDoubleValue("velocities/speed-kts"));
1425 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1426 double distanceM = speedKts * SG_NM_TO_METER * dt;
1430 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1432 drawLine(p, project(advance));
1435 if (validDataForKey((void*) model)) {
1436 setAnchorForKey((void*) model, p);
1440 // draw callsign / speed
1442 ::snprintf(buffer, 1024, "%s\n%dkts",
1443 model->getStringValue("name", "<>"),
1446 MapData* d = createDataForKey((void*) model);
1448 d->setLabel(model->getStringValue("name", "<>"));
1449 d->setPriority(speedKts > 2 ? 30 : 10); // low priority for slow moving ships
1450 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1454 SGVec2d MapWidget::project(const SGGeod& geod) const
1456 // Sanson-Flamsteed projection, relative to the projection center
1457 double r = earth_radius_lat(geod.getLatitudeRad());
1458 double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1459 latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1461 SGVec2d p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1463 // rotate as necessary
1464 double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS),
1465 sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1466 double rx = cost * p.x() - sint * p.y();
1467 double ry = sint * p.x() + cost * p.y();
1468 return SGVec2d(rx, ry);
1471 SGGeod MapWidget::unproject(const SGVec2d& p) const
1473 // unrotate, if necessary
1474 double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS),
1475 sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1476 SGVec2d ur(cost * p.x() - sint * p.y(),
1477 sint * p.x() + cost * p.y());
1479 double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1480 SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1482 double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1483 double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1485 return SGGeod::fromRad(lon, lat);
1488 double MapWidget::currentScale() const
1490 return 1.0 / pow(2.0, _cachedZoom);
1493 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1495 glBegin(GL_LINE_LOOP);
1496 double advance = (SGD_PI * 2) / nSides;
1497 glVertex2d(center.x(), center.y() + r);
1499 for (int i=1; i<nSides; ++i) {
1500 glVertex2d(center.x() + (sin(t) * r), center.y() + (cos(t) * r));
1506 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1508 glBegin(GL_LINE_LOOP);
1509 double advance = (SGD_PI * 2) / nSides;
1510 glVertex2d(center.x(), center.y() + r);
1512 for (int i=1; i<nSides; ++i) {
1513 double rr = (i%2 == 0) ? r : r2;
1514 glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1520 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1523 glVertex2dv(p1.data());
1524 glVertex2dv(p2.data());
1528 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1530 std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1531 const int LINE_LEADING = 4;
1532 const int MARGIN = 4;
1535 int maxWidth = -1, totalHeight = 0;
1536 int lineHeight = legendFont.getStringHeight();
1538 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1539 totalHeight += lineHeight;
1541 totalHeight += LINE_LEADING;
1544 int lw = legendFont.getStringWidth(lines[ln].c_str());
1545 maxWidth = std::max(maxWidth, lw);
1546 } // of line measurement
1549 return; // all lines are empty, don't draw
1552 totalHeight += MARGIN * 2;
1557 box.min[1] = -totalHeight;
1558 box.max[0] = maxWidth + (MARGIN * 2);
1561 box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1564 int xPos = pos.x() + MARGIN;
1565 int yPos = pos.y() - (lineHeight + MARGIN);
1566 glColor3f(0.8, 0.8, 0.8);
1568 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1569 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1570 yPos -= lineHeight + LINE_LEADING;
1574 void MapWidget::drawData()
1576 std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1578 int hw = _width >> 1,
1580 puBox visBox(makePuBox(-hw, -hh, _width, _height));
1584 std::vector<MapData*> drawQueue;
1586 bool drawData = _root->getBoolValue("draw-data");
1587 const int MAX_DRAW_DATA = 25;
1588 const int MAX_DRAW = 50;
1590 for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1591 MapData* md = _dataQueue[d];
1592 md->setDataVisible(drawData);
1594 if (md->isClipped(visBox)) {
1598 if (md->overlaps(drawQueue)) {
1599 if (drawData) { // overlapped with data, let's try just the label
1600 md->setDataVisible(false);
1601 if (md->overlaps(drawQueue)) {
1607 } // of overlaps case
1609 drawQueue.push_back(md);
1611 if (drawData && (drawn >= MAX_DRAW_DATA)) {
1616 // draw lowest-priority first, so higher-priorty items appear on top
1617 std::vector<MapData*>::reverse_iterator r;
1618 for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1623 KeyDataMap::iterator it = _mapData.begin();
1624 for (; it != _mapData.end(); ) {
1626 if (it->second->isExpired()) {
1628 KeyDataMap::iterator cur = it++;
1629 _mapData.erase(cur);
1633 } // of expiry iteration
1636 bool MapWidget::validDataForKey(void* key)
1638 KeyDataMap::iterator it = _mapData.find(key);
1639 if (it == _mapData.end()) {
1640 return false; // no valid data for the key!
1643 it->second->resetAge(); // mark data as valid this frame
1644 _dataQueue.push_back(it->second);
1648 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1650 KeyDataMap::iterator it = _mapData.find(key);
1651 if (it == _mapData.end()) {
1652 throw sg_exception("no valid data for key!");
1655 it->second->setAnchor(anchor);
1658 MapData* MapWidget::getOrCreateDataForKey(void* key)
1660 KeyDataMap::iterator it = _mapData.find(key);
1661 if (it == _mapData.end()) {
1662 return createDataForKey(key);
1665 it->second->resetAge(); // mark data as valid this frame
1666 _dataQueue.push_back(it->second);
1670 MapData* MapWidget::createDataForKey(void* key)
1672 KeyDataMap::iterator it = _mapData.find(key);
1673 if (it != _mapData.end()) {
1674 throw sg_exception("duplicate data requested for key!");
1677 MapData* d = new MapData(0);
1679 _dataQueue.push_back(d);