5 #include "MapWidget.hxx"
8 #include <algorithm> // for std::sort
9 #include <plib/puAux.h>
11 #include <simgear/sg_inlines.h>
12 #include <simgear/misc/strutils.hxx>
13 #include <simgear/magvar/magvar.hxx>
14 #include <simgear/timing/sg_time.hxx> // for magVar julianDate
15 #include <simgear/structure/exception.hxx>
17 #include <Main/globals.hxx>
18 #include <Main/fg_props.hxx>
19 #include <Autopilot/route_mgr.hxx>
20 #include <Navaids/positioned.hxx>
21 #include <Navaids/navrecord.hxx>
22 #include <Navaids/navlist.hxx>
23 #include <Navaids/fix.hxx>
24 #include <Airports/simple.hxx>
25 #include <Airports/runways.hxx>
26 #include <Main/fg_os.hxx> // fgGetKeyModifiers()
27 #include <Navaids/routePath.hxx>
28 #include <Aircraft/FlightHistory.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 = 12;
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");
389 _orthoAzimuthProject = false;
391 MapData::setFont(legendFont);
392 MapData::setPalette(colour);
394 _magVar = new SGMagVar();
397 MapWidget::~MapWidget()
403 void MapWidget::setProperty(SGPropertyNode_ptr prop)
406 int zoom = _root->getIntValue("zoom", -1);
408 _root->setIntValue("zoom", 6); // default zoom
411 // expose MAX_ZOOM to the UI
412 _root->setIntValue("max-zoom", MAX_ZOOM);
413 _root->setBoolValue("centre-on-aircraft", true);
414 _root->setBoolValue("draw-data", false);
415 _root->setBoolValue("draw-flight-history", false);
416 _root->setBoolValue("magnetic-headings", true);
419 void MapWidget::setSize(int w, int h)
421 puObject::setSize(w, h);
428 void MapWidget::doHit( int button, int updown, int x, int y )
430 puObject::doHit(button, updown, x, y);
431 if (updown == PU_DRAG) {
436 if (button == 3) { // mouse-wheel up
438 } else if (button == 4) { // mouse-wheel down
442 if (button != active_mouse_button) {
446 _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
448 if (updown == PU_UP) {
449 puDeactivateWidget();
450 } else if (updown == PU_DOWN) {
451 puSetActiveWidget(this, x, y);
453 if (fgGetKeyModifiers() & KEYMOD_CTRL) {
454 _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
459 void MapWidget::handlePan(int x, int y)
461 SGVec2d delta = SGVec2d(x, y) - _hitLocation;
463 _hitLocation = SGVec2d(x,y);
466 int MapWidget::checkKey (int key, int updown )
468 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
476 pan(SGVec2d(0, -CURSOR_PAN_STEP));
480 pan(SGVec2d(0, CURSOR_PAN_STEP));
484 pan(SGVec2d(CURSOR_PAN_STEP, 0));
488 pan(SGVec2d(-CURSOR_PAN_STEP, 0));
507 void MapWidget::pan(const SGVec2d& delta)
510 _projectionCenter = unproject(-delta);
513 int MapWidget::zoom() const
515 int z = _root->getIntValue("zoom");
516 SG_CLAMP_RANGE(z, 0, MAX_ZOOM);
520 void MapWidget::zoomIn()
522 if (zoom() >= MAX_ZOOM) {
526 _root->setIntValue("zoom", zoom() + 1);
529 void MapWidget::zoomOut()
535 _root->setIntValue("zoom", zoom() - 1);
538 void MapWidget::draw(int dx, int dy)
540 _aircraft = SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
541 fgGetDouble("/position/latitude-deg"));
543 bool mag = _root->getBoolValue("magnetic-headings");
544 if (mag != _magneticHeadings) {
545 clearData(); // flush cached data text, since it often includes heading
546 _magneticHeadings = mag;
550 _root->setBoolValue("centre-on-aircraft", false);
553 else if (_root->getBoolValue("centre-on-aircraft")) {
554 _projectionCenter = _aircraft;
557 double julianDate = globals->get_time_params()->getJD();
558 _magVar->update(_projectionCenter, julianDate);
560 bool aircraftUp = _root->getBoolValue("aircraft-heading-up");
562 _upHeading = fgGetDouble("/orientation/heading-deg");
567 _cachedZoom = MAX_ZOOM - zoom();
568 SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
569 // compute draw range, including a fudge factor for ILSs and other 'long'
571 _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
573 // drawing operations
574 GLint sx = (int) abox.min[0],
575 sy = (int) abox.min[1];
576 glScissor(dx + sx, dy + sy, _width, _height);
577 glEnable(GL_SCISSOR_TEST);
579 glMatrixMode(GL_MODELVIEW);
581 // cetere drawing about the widget center (which is also the
582 // projection centre)
583 glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
588 int textHeight = legendFont.getStringHeight() + 5;
591 SGVec2d loc = project(_aircraft);
592 glColor3f(1.0, 1.0, 1.0);
593 drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
596 if (_magneticHeadings) {
597 displayHdg = (int) fgGetDouble("/orientation/heading-magnetic-deg");
599 displayHdg = (int) _upHeading;
602 double y = (_height / 2) - textHeight;
604 ::snprintf(buf, 16, "%d", displayHdg);
605 int sw = legendFont.getStringWidth(buf);
606 legendFont.drawString(buf, loc.x() - sw/2, y);
613 drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
614 drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
615 paintAircraftLocation(_aircraft);
623 glDisable(GL_SCISSOR_TEST);
626 void MapWidget::paintRuler()
628 if (_clickGeod == SGGeod()) {
632 SGVec2d acftPos = project(_aircraft);
633 SGVec2d clickPos = project(_clickGeod);
635 glColor4f(0.0, 1.0, 1.0, 0.6);
636 drawLine(acftPos, clickPos);
638 circleAtAlt(clickPos, 8, 10, 5);
640 double dist, az, az2;
641 SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
643 ::snprintf(buffer, 1024, "%03d/%.1fnm",
644 displayHeading(az), dist * SG_METER_TO_NM);
646 MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
648 d->setAnchor(clickPos);
649 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
650 d->setPriority(20000);
655 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
657 SGVec2d loc = project(aircraftPos);
659 double hdg = fgGetDouble("/orientation/heading-deg");
662 glColor4f(1.0, 1.0, 0.0, 1.0);
664 glTranslated(loc.x(), loc.y(), 0.0);
665 glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
667 const SGVec2d wingspan(12, 0);
668 const SGVec2d nose(0, 8);
669 const SGVec2d tail(0, -14);
670 const SGVec2d tailspan(4,0);
672 drawLine(-wingspan, wingspan);
673 drawLine(nose, tail);
674 drawLine(tail - tailspan, tail + tailspan);
680 void MapWidget::paintRoute()
682 if (_route->numWaypts() < 2) {
686 RoutePath path(_route->flightPlan());
688 // first pass, draw the actual lines
691 for (int w=0; w<_route->numWaypts(); ++w) {
692 SGGeodVec gv(path.pathForIndex(w));
697 if (w < _route->currentIndex()) {
698 glColor4f(0.5, 0.5, 0.5, 0.7);
700 glColor4f(1.0, 0.0, 1.0, 1.0);
703 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
704 if (wpt->flag(flightgear::WPT_MISS)) {
705 glEnable(GL_LINE_STIPPLE);
706 glLineStipple(1, 0x00FF);
709 glBegin(GL_LINE_STRIP);
710 for (unsigned int i=0; i<gv.size(); ++i) {
711 SGVec2d p = project(gv[i]);
712 glVertex2d(p.x(), p.y());
716 glDisable(GL_LINE_STIPPLE);
720 // second pass, draw waypoint symbols and data
721 for (int w=0; w < _route->numWaypts(); ++w) {
722 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
723 SGGeod g = path.positionForIndex(w);
725 continue; // Vectors or similar
728 SGVec2d p = project(g);
729 glColor4f(1.0, 0.0, 1.0, 1.0);
730 circleAtAlt(p, 8, 12, 5);
732 std::ostringstream legend;
733 legend << wpt->ident();
734 if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
735 legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
738 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
739 legend << '\n' << wpt->speedMach() << "M";
740 } else if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
741 legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
744 MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
745 d->setText(legend.str());
746 d->setLabel(wpt->ident());
748 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
749 d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
751 } // of second waypoint iteration
754 void MapWidget::drawFlightHistory()
756 FGFlightHistory* history = (FGFlightHistory*) globals->get_subsystem("history");
757 if (!history || !_root->getBoolValue("draw-flight-history")) {
761 // first pass, draw the actual lines
764 SGGeodVec gv(history->pathForHistory());
765 glColor4f(0.0, 0.0, 1.0, 0.7);
767 glBegin(GL_LINE_STRIP);
768 for (unsigned int i=0; i<gv.size(); ++i) {
769 SGVec2d p = project(gv[i]);
770 glVertex2d(p.x(), p.y());
777 * Round a SGGeod to an arbitrary precision.
778 * For example, passing precision of 0.5 will round to the nearest 0.5 of
779 * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
780 * multiple, and so on.
782 static SGGeod roundGeod(double precision, const SGGeod& g)
784 double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
785 double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
787 return SGGeod::fromDeg(lon * precision, lat * precision);
790 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
792 double minX = SGMiscd::min(a.x(), b.x()),
793 minY = SGMiscd::min(a.y(), b.y()),
794 maxX = SGMiscd::max(a.x(), b.x()),
795 maxY = SGMiscd::max(a.y(), b.y());
797 int hh = _height >> 1, hw = _width >> 1;
799 if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
803 glVertex2dv(a.data());
804 glVertex2dv(b.data());
808 SGVec2d MapWidget::gridPoint(int ix, int iy)
810 int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
811 GridPointCache::iterator it = _gridCache.find(key);
812 if (it != _gridCache.end()) {
816 SGGeod gp = SGGeod::fromDeg(
817 _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
818 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
820 SGVec2d proj = project(gp);
821 _gridCache[key] = proj;
825 void MapWidget::drawLatLonGrid()
828 _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
834 glColor4f(0.8, 0.8, 0.8, 0.4);
842 for (int x = -ix; x < ix; ++x) {
843 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
844 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
845 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
846 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
850 for (int y = -iy; y < iy; ++y) {
851 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
852 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
853 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
854 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
865 void MapWidget::drawGPSData()
867 std::string gpsMode = _gps->getStringValue("mode");
869 SGGeod wp0Geod = SGGeod::fromDeg(
870 _gps->getDoubleValue("wp/wp[0]/longitude-deg"),
871 _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
873 SGGeod wp1Geod = SGGeod::fromDeg(
874 _gps->getDoubleValue("wp/wp[1]/longitude-deg"),
875 _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
878 double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
879 double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
882 if (gpsSpeed > 3.0) { // only draw track line if valid
884 SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
886 glColor4f(1.0, 1.0, 0.0, 1.0);
887 glEnable(GL_LINE_STIPPLE);
888 glLineStipple(1, 0x00FF);
889 drawLine(project(_aircraft), project(trackRadial));
890 glDisable(GL_LINE_STIPPLE);
893 if (gpsMode == "dto") {
894 SGVec2d wp0Pos = project(wp0Geod);
895 SGVec2d wp1Pos = project(wp1Geod);
897 glColor4f(1.0, 0.0, 1.0, 1.0);
898 drawLine(wp0Pos, wp1Pos);
902 if (_gps->getBoolValue("scratch/valid")) {
908 class MapAirportFilter : public FGAirport::AirportFilter
911 MapAirportFilter(SGPropertyNode_ptr nd)
913 _heliports = nd->getBoolValue("show-heliports", false);
914 _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
915 _minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
918 virtual FGPositioned::Type maxType() const {
919 return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
922 virtual bool passAirport(FGAirport* aApt) const {
923 if (_hardRunwaysOnly) {
924 return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
932 bool _hardRunwaysOnly;
936 void MapWidget::drawAirports()
938 MapAirportFilter af(_root);
939 bool partial = false;
940 FGPositioned::List apts = FGPositioned::findWithinRangePartial(_projectionCenter, _drawRangeNm, &af, partial);
941 for (unsigned int i=0; i<apts.size(); ++i) {
942 drawAirport((FGAirport*) apts[i].get());
946 class NavaidFilter : public FGPositioned::Filter
949 NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
950 _fixes(fixesEnabled),
951 _navaids(navaidsEnabled)
954 virtual bool pass(FGPositioned* aPos) const {
955 if (_fixes && (aPos->type() == FGPositioned::FIX)) {
956 // ignore fixes which end in digits - expirmental
957 if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
965 virtual FGPositioned::Type minType() const {
966 return _fixes ? FGPositioned::FIX : FGPositioned::NDB;
969 virtual FGPositioned::Type maxType() const {
970 return _navaids ? FGPositioned::VOR : FGPositioned::FIX;
974 bool _fixes, _navaids;
977 void MapWidget::drawNavaids()
979 bool fixes = _root->getBoolValue("draw-fixes");
980 NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
982 if (f.minType() <= f.maxType()) {
983 FGPositioned::List navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
986 for (unsigned int i=0; i<navs.size(); ++i) {
987 FGPositioned::Type ty = navs[i]->type();
988 if (ty == FGPositioned::NDB) {
989 drawNDB(false, (FGNavRecord*) navs[i].get());
990 } else if (ty == FGPositioned::VOR) {
991 drawVOR(false, (FGNavRecord*) navs[i].get());
992 } else if (ty == FGPositioned::FIX) {
993 drawFix((FGFix*) navs[i].get());
995 } // of navaid iteration
996 } // of navaids || fixes are drawn test
999 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
1001 SGVec2d pos = project(ndb->geod());
1004 glColor3f(0.0, 1.0, 1.0);
1006 glColor3f(0.0, 0.0, 0.0);
1009 glEnable(GL_LINE_STIPPLE);
1010 glLineStipple(1, 0x00FF);
1011 circleAt(pos, 20, 6);
1012 circleAt(pos, 20, 10);
1013 glDisable(GL_LINE_STIPPLE);
1015 if (validDataForKey(ndb)) {
1016 setAnchorForKey(ndb, pos);
1021 ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
1022 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
1024 MapData* d = createDataForKey(ndb);
1026 d->setLabel(ndb->ident());
1028 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1033 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
1035 SGVec2d pos = project(vor->geod());
1037 glColor3f(0.0, 1.0, 1.0);
1039 glColor3f(0.0, 0.0, 1.0);
1042 circleAt(pos, 6, 8);
1044 if (validDataForKey(vor)) {
1045 setAnchorForKey(vor, pos);
1050 ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1051 vor->name().c_str(), vor->ident().c_str(),
1052 vor->get_freq() / 100.0);
1054 MapData* d = createDataForKey(vor);
1056 d->setLabel(vor->ident());
1057 d->setPriority(tuned ? 10000 : 100);
1058 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1062 void MapWidget::drawFix(FGFix* fix)
1064 SGVec2d pos = project(fix->geod());
1065 glColor3f(0.0, 0.0, 0.0);
1066 circleAt(pos, 3, 6);
1068 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1069 return; // hide fix labels beyond a certain zoom level
1072 if (validDataForKey(fix)) {
1073 setAnchorForKey(fix, pos);
1077 MapData* d = createDataForKey(fix);
1078 d->setLabel(fix->ident());
1080 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1084 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1086 if (!radio || radio->getBoolValue("slaved-to-gps", false)
1087 || !radio->getBoolValue("in-range", false)) {
1091 if (radio->getBoolValue("nav-loc", false)) {
1092 drawTunedLocalizer(radio);
1095 // identify the tuned station - unfortunately we don't get lat/lon directly,
1096 // need to do the frequency search again
1097 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1099 FGNavRecord* nav = FGNavList::findByFreq(mhz, _aircraft,
1100 FGNavList::navFilter());
1101 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1102 // mismatch between navradio selection logic and ours!
1109 SGVec2d pos = project(nav->geod());
1112 double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1113 SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1114 SGVec2d prange = project(range);
1116 SGVec2d norm = normalize(prange - pos);
1117 SGVec2d perp(norm.y(), -norm.x());
1119 circleAt(pos, 64, length(prange - pos));
1120 drawLine(pos, prange);
1122 // draw to/from arrows
1123 SGVec2d midPoint = (pos + prange) * 0.5;
1124 if (radio->getBoolValue("from-flag")) {
1130 SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1131 SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1132 drawLine(midPoint, arrowB);
1133 drawLine(arrowB, arrowC);
1134 drawLine(arrowC, midPoint);
1136 drawLine(pos, (2 * pos) - prange); // reciprocal radial
1139 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1141 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1142 FGNavRecord* loc = FGNavList::findByFreq(mhz, _aircraft, FGNavList::locFilter());
1143 if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1144 // mismatch between navradio selection logic and ours!
1148 if (loc->runway()) {
1149 drawILS(true, loc->runway());
1154 void MapWidget::drawObstacle(FGPositioned* obs)
1156 SGVec2d pos = project(obs->geod());
1157 glColor3f(0.0, 0.0, 0.0);
1159 drawLine(pos, pos + SGVec2d());
1163 void MapWidget::drawAirport(FGAirport* apt)
1165 // draw tower location
1166 SGVec2d towerPos = project(apt->getTowerLocation());
1168 if (_cachedZoom <= SHOW_DETAIL_ZOOM) {
1169 glColor3f(1.0, 1.0, 1.0);
1172 drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1173 drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1174 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1175 drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1176 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1179 if (validDataForKey(apt)) {
1180 setAnchorForKey(apt, towerPos);
1183 ::snprintf(buffer, 1024, "%s\n%s",
1184 apt->ident().c_str(), apt->name().c_str());
1186 MapData* d = createDataForKey(apt);
1188 d->setLabel(apt->ident());
1189 d->setPriority(100 + scoreAirportRunways(apt));
1190 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1191 d->setAnchor(towerPos);
1194 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1198 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1199 FGRunway* rwy = apt->getRunwayByIndex(r);
1200 if (!rwy->isReciprocal()) {
1205 for (unsigned int r=0; r<apt->numRunways(); ++r) {
1206 FGRunway* rwy = apt->getRunwayByIndex(r);
1207 if (!rwy->isReciprocal()) {
1212 drawILS(false, rwy);
1214 } // of runway iteration
1218 int MapWidget::scoreAirportRunways(FGAirport* apt)
1220 bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1221 double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1224 unsigned int numRunways(apt->numRunways());
1225 for (unsigned int r=0; r<numRunways; ++r) {
1226 FGRunway* rwy = apt->getRunwayByIndex(r);
1227 if (rwy->isReciprocal()) {
1231 if (needHardSurface && !rwy->isHardSurface()) {
1235 if (rwy->lengthFt() < minLength) {
1239 int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1240 score += scoreLength;
1241 } // of runways iteration
1246 void MapWidget::drawRunwayPre(FGRunway* rwy)
1248 SGVec2d p1 = project(rwy->begin());
1249 SGVec2d p2 = project(rwy->end());
1252 glColor3f(1.0, 0.0, 1.0);
1256 void MapWidget::drawRunway(FGRunway* rwy)
1259 // optionally show active, stopway, etc
1260 // in legend, show published heading and length
1261 // and threshold elevation
1263 SGVec2d p1 = project(rwy->begin());
1264 SGVec2d p2 = project(rwy->end());
1266 glColor3f(1.0, 1.0, 1.0);
1267 SGVec2d inset = normalize(p2 - p1) * 2;
1269 drawLine(p1 + inset, p2 - inset);
1271 if (validDataForKey(rwy)) {
1272 setAnchorForKey(rwy, (p1 + p2) * 0.5);
1277 ::snprintf(buffer, 1024, "%s/%s\n%03d/%03d\n%.0f'",
1278 rwy->ident().c_str(),
1279 rwy->reciprocalRunway()->ident().c_str(),
1280 displayHeading(rwy->headingDeg()),
1281 displayHeading(rwy->reciprocalRunway()->headingDeg()),
1284 MapData* d = createDataForKey(rwy);
1286 d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1288 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1289 d->setAnchor((p1 + p2) * 0.5);
1292 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1294 // arrow, tip centered on the landing threshold
1295 // using LOC transmitter position would be more accurate, but
1296 // is visually cluttered
1297 // arrow width is based upon the computed localizer width
1299 FGNavRecord* loc = rwy->ILS();
1300 double halfBeamWidth = loc->localizerWidth() * 0.5;
1301 SGVec2d t = project(rwy->threshold());
1303 double rangeM = loc->get_range() * SG_NM_TO_METER;
1304 double radial = loc->get_multiuse();
1305 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1308 // compute the three end points at the widge end of the arrow
1309 SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1310 SGVec2d endCentre = project(locEnd);
1312 SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1313 SGVec2d endR = project(locEnd);
1315 SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1316 SGVec2d endL = project(locEnd);
1318 // outline two triangles
1321 glColor3f(0.0, 1.0, 1.0);
1323 glColor3f(0.0, 0.0, 1.0);
1326 glBegin(GL_LINE_LOOP);
1327 glVertex2dv(t.data());
1328 glVertex2dv(endCentre.data());
1329 glVertex2dv(endL.data());
1331 glBegin(GL_LINE_LOOP);
1332 glVertex2dv(t.data());
1333 glVertex2dv(endCentre.data());
1334 glVertex2dv(endR.data());
1337 if (validDataForKey(loc)) {
1338 setAnchorForKey(loc, endR);
1343 ::snprintf(buffer, 1024, "%s\n%s\n%03d - %3.2fMHz",
1344 loc->ident().c_str(), loc->name().c_str(),
1345 displayHeading(radial),
1346 loc->get_freq()/100.0);
1348 MapData* d = createDataForKey(loc);
1350 d->setLabel(loc->ident());
1352 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1356 void MapWidget::drawTraffic()
1358 if (!_root->getBoolValue("draw-traffic")) {
1362 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1366 const SGPropertyNode* ai = fgGetNode("/ai/models", true);
1368 for (int i = 0; i < ai->nChildren(); ++i) {
1369 const SGPropertyNode *model = ai->getChild(i);
1370 // skip bad or dead entries
1371 if (!model || model->getIntValue("id", -1) == -1) {
1375 const std::string& name(model->getName());
1376 SGGeod pos = SGGeod::fromDegFt(
1377 model->getDoubleValue("position/longitude-deg"),
1378 model->getDoubleValue("position/latitude-deg"),
1379 model->getDoubleValue("position/altitude-ft"));
1381 double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
1382 if (dist > _drawRangeNm) {
1386 double heading = model->getDoubleValue("orientation/true-heading-deg");
1387 if ((name == "aircraft") || (name == "multiplayer") ||
1388 (name == "wingman") || (name == "tanker")) {
1389 drawAIAircraft(model, pos, heading);
1390 } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1391 drawAIShip(model, pos, heading);
1393 } // of ai/models iteration
1396 void MapWidget::drawAIAircraft(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1399 SGVec2d p = project(pos);
1401 glColor3f(0.0, 0.0, 0.0);
1403 circleAt(p, 4, 6.0); // black diamond
1405 // draw heading vector
1406 int speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1410 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1411 double distanceM = speedKts * SG_NM_TO_METER * dt;
1415 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1417 drawLine(p, project(advance));
1421 // draw callsign / altitude / speed
1423 ::snprintf(buffer, 1024, "%s\n%d'\n%dkts",
1424 model->getStringValue("callsign", "<>"),
1425 static_cast<int>(pos.getElevationFt() / 50.0) * 50,
1428 MapData* d = getOrCreateDataForKey((void*) model);
1430 d->setLabel(model->getStringValue("callsign", "<>"));
1431 d->setPriority(speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1432 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1437 void MapWidget::drawAIShip(const SGPropertyNode* model, const SGGeod& pos, double hdg)
1439 SGVec2d p = project(pos);
1441 glColor3f(0.0, 0.0, 0.5);
1443 circleAt(p, 4, 6.0); // blue diamond (to differentiate from aircraft.
1445 // draw heading vector
1446 int speedKts = static_cast<int>(model->getDoubleValue("velocities/speed-kts"));
1450 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1451 double distanceM = speedKts * SG_NM_TO_METER * dt;
1455 SGGeodesy::direct(pos, hdg, distanceM, advance, az2);
1457 drawLine(p, project(advance));
1460 // draw callsign / speed
1462 ::snprintf(buffer, 1024, "%s\n%dkts",
1463 model->getStringValue("name", "<>"),
1466 MapData* d = getOrCreateDataForKey((void*) model);
1468 d->setLabel(model->getStringValue("name", "<>"));
1469 d->setPriority(speedKts > 2 ? 30 : 10); // low priority for slow moving ships
1470 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1474 SGVec2d MapWidget::project(const SGGeod& geod) const
1477 double r = earth_radius_lat(geod.getLatitudeRad());
1479 if (_orthoAzimuthProject) {
1480 // http://mathworld.wolfram.com/OrthographicProjection.html
1481 double cosTheta = cos(geod.getLatitudeRad());
1482 double sinDLambda = sin(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1483 double cosDLambda = cos(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1484 double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1485 double sinTheta = sin(geod.getLatitudeRad());
1486 double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1488 p = SGVec2d(cosTheta * sinDLambda,
1489 (cosTheta1 * sinTheta) - (sinTheta1 * cosTheta * cosDLambda)) * r * currentScale();
1492 // Sanson-Flamsteed projection, relative to the projection center
1493 double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1494 latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1496 p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1500 // rotate as necessary
1501 double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS),
1502 sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1503 double rx = cost * p.x() - sint * p.y();
1504 double ry = sint * p.x() + cost * p.y();
1505 return SGVec2d(rx, ry);
1508 SGGeod MapWidget::unproject(const SGVec2d& p) const
1510 // unrotate, if necessary
1511 double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS),
1512 sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1513 SGVec2d ur(cost * p.x() - sint * p.y(),
1514 sint * p.x() + cost * p.y());
1516 double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1517 SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1519 if (_orthoAzimuthProject) {
1520 double phi = length(p);
1521 double c = asin(phi);
1522 double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1523 double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1525 double lat = asin(cos(c) * sinTheta1 + ((unscaled.y() * sin(c) * cosTheta1) / phi));
1526 double lon = _projectionCenter.getLongitudeRad() +
1527 atan((unscaled.x()* sin(c)) / (phi * cosTheta1 * cos(c) - unscaled.y() * sinTheta1 * sin(c)));
1528 return SGGeod::fromRad(lon, lat);
1530 double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1531 double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1532 return SGGeod::fromRad(lon, lat);
1536 double MapWidget::currentScale() const
1538 return 1.0 / pow(2.0, _cachedZoom);
1541 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1543 glBegin(GL_LINE_LOOP);
1544 double advance = (SGD_PI * 2) / nSides;
1545 glVertex2d(center.x(), center.y() + r);
1547 for (int i=1; i<nSides; ++i) {
1548 glVertex2d(center.x() + (sin(t) * r), center.y() + (cos(t) * r));
1554 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1556 glBegin(GL_LINE_LOOP);
1557 double advance = (SGD_PI * 2) / nSides;
1558 glVertex2d(center.x(), center.y() + r);
1560 for (int i=1; i<nSides; ++i) {
1561 double rr = (i%2 == 0) ? r : r2;
1562 glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1568 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1571 glVertex2dv(p1.data());
1572 glVertex2dv(p2.data());
1576 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1578 std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1579 const int LINE_LEADING = 4;
1580 const int MARGIN = 4;
1583 int maxWidth = -1, totalHeight = 0;
1584 int lineHeight = legendFont.getStringHeight();
1586 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1587 totalHeight += lineHeight;
1589 totalHeight += LINE_LEADING;
1592 int lw = legendFont.getStringWidth(lines[ln].c_str());
1593 maxWidth = std::max(maxWidth, lw);
1594 } // of line measurement
1597 return; // all lines are empty, don't draw
1600 totalHeight += MARGIN * 2;
1605 box.min[1] = -totalHeight;
1606 box.max[0] = maxWidth + (MARGIN * 2);
1609 box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1612 int xPos = pos.x() + MARGIN;
1613 int yPos = pos.y() - (lineHeight + MARGIN);
1614 glColor3f(0.8, 0.8, 0.8);
1616 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1617 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1618 yPos -= lineHeight + LINE_LEADING;
1622 void MapWidget::drawData()
1624 std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1626 int hw = _width >> 1,
1628 puBox visBox(makePuBox(-hw, -hh, _width, _height));
1632 std::vector<MapData*> drawQueue;
1634 bool drawData = _root->getBoolValue("draw-data");
1635 const int MAX_DRAW_DATA = 25;
1636 const int MAX_DRAW = 50;
1638 for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1639 MapData* md = _dataQueue[d];
1640 md->setDataVisible(drawData);
1642 if (md->isClipped(visBox)) {
1646 if (md->overlaps(drawQueue)) {
1647 if (drawData) { // overlapped with data, let's try just the label
1648 md->setDataVisible(false);
1649 if (md->overlaps(drawQueue)) {
1655 } // of overlaps case
1657 drawQueue.push_back(md);
1659 if (drawData && (drawn >= MAX_DRAW_DATA)) {
1664 // draw lowest-priority first, so higher-priorty items appear on top
1665 std::vector<MapData*>::reverse_iterator r;
1666 for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1671 KeyDataMap::iterator it = _mapData.begin();
1672 for (; it != _mapData.end(); ) {
1674 if (it->second->isExpired()) {
1676 KeyDataMap::iterator cur = it++;
1677 _mapData.erase(cur);
1681 } // of expiry iteration
1684 bool MapWidget::validDataForKey(void* key)
1686 KeyDataMap::iterator it = _mapData.find(key);
1687 if (it == _mapData.end()) {
1688 return false; // no valid data for the key!
1691 it->second->resetAge(); // mark data as valid this frame
1692 _dataQueue.push_back(it->second);
1696 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1698 KeyDataMap::iterator it = _mapData.find(key);
1699 if (it == _mapData.end()) {
1700 throw sg_exception("no valid data for key!");
1703 it->second->setAnchor(anchor);
1706 MapData* MapWidget::getOrCreateDataForKey(void* key)
1708 KeyDataMap::iterator it = _mapData.find(key);
1709 if (it == _mapData.end()) {
1710 return createDataForKey(key);
1713 it->second->resetAge(); // mark data as valid this frame
1714 _dataQueue.push_back(it->second);
1718 MapData* MapWidget::createDataForKey(void* key)
1720 KeyDataMap::iterator it = _mapData.find(key);
1721 if (it != _mapData.end()) {
1722 throw sg_exception("duplicate data requested for key!");
1725 MapData* d = new MapData(0);
1727 _dataQueue.push_back(d);
1732 void MapWidget::clearData()
1734 KeyDataMap::iterator it = _mapData.begin();
1735 for (; it != _mapData.end(); ++it) {
1742 int MapWidget::displayHeading(double h) const
1744 if (_magneticHeadings) {
1745 h -= _magVar->get_magvar() * SG_RADIANS_TO_DEGREES;
1748 SG_NORMALIZE_RANGE(h, 0.0, 360.0);
1749 return SGMiscd::roundToInt(h);