1 // BaseDiagram.cxx - part of GUI launcher using Qt5
3 // Written by James Turner, started December 2014.
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 #include "BaseDiagram.hxx"
28 #include <QMouseEvent>
30 #include <Navaids/navrecord.hxx>
31 #include <Navaids/positioned.hxx>
32 #include <Airports/airport.hxx>
34 #include "QtLauncher_fwd.hxx"
36 /* equatorial and polar earth radius */
37 const float rec = 6378137; // earth radius, equator (?)
38 const float rpol = 6356752.314f; // earth radius, polar (?)
40 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
41 static float earth_radius_lat( float lat )
43 double a = cos(lat)/rec;
44 double b = sin(lat)/rpol;
45 return 1.0f / sqrt( a * a + b * b );
48 BaseDiagram::BaseDiagram(QWidget* pr) :
51 m_wheelAngleDeltaAccumulator(0)
53 setSizePolicy(QSizePolicy::MinimumExpanding,
54 QSizePolicy::MinimumExpanding);
55 setMinimumSize(100, 100);
58 QTransform BaseDiagram::transform() const
61 t.translate(width() / 2, height() / 2); // center projection origin in the widget
62 t.scale(m_scale, m_scale);
64 // apply any pan offset that exists
65 t.translate(m_panOffset.x(), m_panOffset.y());
66 // center the bounding box (may not be at the origin)
67 t.translate(-m_bounds.center().x(), -m_bounds.center().y());
71 void BaseDiagram::clearIgnoredNavaids()
76 void BaseDiagram::addIgnoredNavaid(FGPositionedRef pos)
78 if (isNavaidIgnored(pos))
80 m_ignored.push_back(pos);
83 void BaseDiagram::extendRect(QRectF &r, const QPointF &p)
85 if (p.x() < r.left()) {
87 } else if (p.x() > r.right()) {
91 if (p.y() < r.top()) {
93 } else if (p.y() > r.bottom()) {
98 void BaseDiagram::paintEvent(QPaintEvent* pe)
101 p.setRenderHints(QPainter::Antialiasing);
102 p.fillRect(rect(), QColor(0x3f, 0x3f, 0x3f));
104 if (m_autoScalePan) {
105 // fit bounds within our available space, allowing for a margin
106 const int MARGIN = 32; // pixels
107 double ratioInX = (width() - MARGIN * 2) / m_bounds.width();
108 double ratioInY = (height() - MARGIN * 2) / m_bounds.height();
109 m_scale = std::min(ratioInX, ratioInY);
112 QTransform t(transform());
120 void BaseDiagram::paintAirplaneIcon(QPainter* painter, const SGGeod& geod, int headingDeg)
122 QPointF pos = project(geod);
123 QPixmap pix(":/airplane-icon");
124 pos = painter->transform().map(pos);
125 painter->resetTransform();
126 painter->translate(pos.x(), pos.y());
127 painter->rotate(headingDeg);
129 painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
130 QRect airplaneIconRect = pix.rect();
131 airplaneIconRect.moveCenter(QPoint(0,0));
132 painter->drawPixmap(airplaneIconRect, pix);
135 class MapFilter : public FGPositioned::TypeFilter
139 MapFilter(LauncherAircraftType aircraft)
141 // addType(FGPositioned::FIX);
142 addType(FGPositioned::NDB);
143 addType(FGPositioned::VOR);
145 if (aircraft == Helicopter) {
146 addType(FGPositioned::HELIPAD);
149 if (aircraft == Seaplane) {
150 addType(FGPositioned::SEAPORT);
152 addType(FGPositioned::AIRPORT);
156 virtual bool pass(FGPositioned* aPos) const
158 bool ok = TypeFilter::pass(aPos);
159 // fix-filtering code disabled since fixed are entirely disabled
161 if (ok && (aPos->type() == FGPositioned::FIX)) {
162 // ignore fixes which end in digits
163 if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
172 void BaseDiagram::splitItems(const FGPositionedList& in, FGPositionedList& navaids,
173 FGPositionedList& ports)
175 FGPositionedList::const_iterator it = in.begin();
176 for (; it != in.end(); ++it) {
177 if (FGAirport::isAirportType(it->ptr())) {
178 ports.push_back(*it);
180 navaids.push_back(*it);
185 bool orderAirportsByRunwayLength(const FGPositionedRef& a,
186 const FGPositionedRef& b)
188 FGAirport* aptA = static_cast<FGAirport*>(a.ptr());
189 FGAirport* aptB = static_cast<FGAirport*>(b.ptr());
191 return aptA->longestRunway()->lengthFt() > aptB->longestRunway()->lengthFt();
194 void BaseDiagram::paintNavaids(QPainter* painter)
196 QTransform xf = painter->transform();
197 painter->setTransform(QTransform()); // reset to identity
198 QTransform invT = xf.inverted();
201 SGGeod topLeft = unproject(invT.map(rect().topLeft()), m_projectionCenter);
202 SGGeod viewCenter = unproject(invT.map(rect().center()), m_projectionCenter);
203 SGGeod bottomRight = unproject(invT.map(rect().bottomRight()), m_projectionCenter);
205 double drawRangeNm = std::max(SGGeodesy::distanceNm(viewCenter, topLeft),
206 SGGeodesy::distanceNm(viewCenter, bottomRight));
208 MapFilter f(m_aircraftType);
209 FGPositionedList items = FGPositioned::findWithinRange(viewCenter, drawRangeNm, &f);
211 FGPositionedList navaids, ports;
212 splitItems(items, navaids, ports);
214 if (ports.size() >= 40) {
215 FGPositionedList::iterator middle = ports.begin() + 40;
216 std::partial_sort(ports.begin(), middle, ports.end(),
217 orderAirportsByRunwayLength);
221 m_labelRects.clear();
222 m_labelRects.reserve(items.size());
224 FGPositionedList::const_iterator it;
225 for (it = ports.begin(); it != ports.end(); ++it) {
226 paintNavaid(painter, xf, *it);
229 for (it = navaids.begin(); it != navaids.end(); ++it) {
230 paintNavaid(painter, xf, *it);
235 painter->setTransform(xf);
238 QRect boundsOfLines(const QVector<QLineF>& lines)
241 Q_FOREACH(const QLineF& l, lines) {
242 r = r.united(QRectF(l.p1(), l.p2()).toRect());
248 void BaseDiagram::paintNavaid(QPainter* painter, const QTransform& t, const FGPositionedRef &pos)
250 if (isNavaidIgnored(pos))
253 bool drawAsIcon = true;
254 const double minRunwayLengthFt = (16 / m_scale) * SG_METER_TO_FEET;
255 const FGPositioned::Type ty(pos->type());
256 const bool isNDB = (ty == FGPositioned::NDB);
259 if (ty == FGPositioned::AIRPORT) {
260 FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
261 if (apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
264 painter->setTransform(t);
265 QVector<QLineF> lines = projectAirportRuwaysWithCenter(apt, m_projectionCenter);
267 QPen pen(QColor(0x03, 0x83, 0xbf), 8);
268 pen.setCosmetic(true);
269 painter->setPen(pen);
270 painter->drawLines(lines);
272 QPen linePen(Qt::white, 2);
273 linePen.setCosmetic(true);
274 painter->setPen(linePen);
275 painter->drawLines(lines);
277 painter->resetTransform();
279 iconRect = t.mapRect(boundsOfLines(lines));
284 QPixmap pm = iconForPositioned(pos);
285 QPointF loc = t.map(project(pos->geod()));
286 iconRect = pm.rect();
287 iconRect.moveCenter(loc.toPoint());
288 painter->drawPixmap(iconRect, pm);
291 // compute label text so we can measure it
293 if (FGAirport::isAirportType(pos.ptr())) {
294 label = QString::fromStdString(pos->name());
295 label = fixNavaidName(label);
297 label = QString::fromStdString(pos->ident());
300 if (ty == FGPositioned::NDB) {
301 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
302 label.append("\n").append(QString::number(nav->get_freq() / 100));
303 } else if (ty == FGPositioned::VOR) {
304 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
305 label.append("\n").append(QString::number(nav->get_freq() / 100.0, 'f', 1));
308 QRect textBounds = painter->boundingRect(QRect(0, 0, 100, 100),
309 Qt::TextWordWrap, label);
311 textBounds = rectAndFlagsForLabel(pos->guid(), iconRect,
315 painter->setPen(isNDB ? QColor(0x9b, 0x5d, 0xa2) : QColor(0x03, 0x83, 0xbf));
316 painter->drawText(textBounds, textFlags, label);
319 bool BaseDiagram::isNavaidIgnored(const FGPositionedRef &pos) const
321 return m_ignored.contains(pos);
324 bool BaseDiagram::isLabelRectAvailable(const QRect &r) const
326 Q_FOREACH(const QRect& lr, m_labelRects) {
327 if (lr.intersects(r))
334 int BaseDiagram::textFlagsForLabelPosition(LabelPosition pos)
338 case LABEL_RIGHT: return Qt::AlignLeft | Qt::AlignVCenter;
339 case LABEL_ABOVE: return Qt::AlignHCenter | Qt::A
345 QRect BaseDiagram::rectAndFlagsForLabel(PositionedID guid, const QRect& item,
349 m_labelRects.append(item);
350 int pos = m_labelPositions.value(guid, LABEL_RIGHT);
351 bool firstAttempt = true;
352 flags = Qt::TextWordWrap;
354 while (pos < LAST_POSITION) {
355 QRect r = labelPositioned(item, bounds, static_cast<LabelPosition>(pos));
356 if (isLabelRectAvailable(r)) {
357 m_labelRects.append(r);
358 m_labelPositions[guid] = static_cast<LabelPosition>(pos);
359 flags |= textFlagsForLabelPosition(static_cast<LabelPosition>(pos));
361 } else if (firstAttempt && (pos != LABEL_RIGHT)) {
367 firstAttempt = false;
370 return QRect(item.x(), item.y(), bounds.width(), bounds.height());
373 QRect BaseDiagram::labelPositioned(const QRect& itemRect,
375 LabelPosition lp) const
377 const int SHORT_MARGIN = 4;
378 const int DIAGONAL_MARGIN = 12;
380 QPoint topLeft = itemRect.topLeft();
383 // cardinal compass points are short (close in)
385 topLeft = QPoint(itemRect.right() + SHORT_MARGIN,
386 itemRect.center().y() - bounds.height() / 2);
389 topLeft = QPoint(itemRect.center().x() - (bounds.width() / 2),
390 itemRect.top() - (SHORT_MARGIN + bounds.height()));
393 topLeft = QPoint(itemRect.center().x() - (bounds.width() / 2),
394 itemRect.bottom() + SHORT_MARGIN);
397 topLeft = QPoint(itemRect.left() - (SHORT_MARGIN + bounds.width()),
398 itemRect.center().y() - bounds.height() / 2);
401 // first diagonals are further out (to hopefully have a better chance
402 // of finding clear space
405 topLeft = QPoint(itemRect.right() + DIAGONAL_MARGIN,
406 itemRect.top() - (DIAGONAL_MARGIN + bounds.height()));
410 topLeft = QPoint(itemRect.left() - (DIAGONAL_MARGIN + bounds.width()),
411 itemRect.top() - (DIAGONAL_MARGIN + bounds.height()));
415 topLeft = QPoint(itemRect.right() + DIAGONAL_MARGIN,
416 itemRect.bottom() + DIAGONAL_MARGIN);
420 topLeft = QPoint(itemRect.left() - (DIAGONAL_MARGIN + bounds.width()),
421 itemRect.bottom() + DIAGONAL_MARGIN);
424 qWarning() << Q_FUNC_INFO << "Implement me";
428 return QRect(topLeft, bounds);
431 void BaseDiagram::mousePressEvent(QMouseEvent *me)
433 m_lastMousePos = me->pos();
437 void BaseDiagram::mouseMoveEvent(QMouseEvent *me)
439 m_autoScalePan = false;
441 QPointF delta = me->pos() - m_lastMousePos;
442 m_lastMousePos = me->pos();
444 // offset is stored in metres so we don't have to modify it when
446 m_panOffset += (delta / m_scale);
454 return (v == 0) ? 0 : (v < 0) ? -1 : 1;
457 void BaseDiagram::wheelEvent(QWheelEvent *we)
459 m_autoScalePan = false;
461 int delta = we->angleDelta().y();
465 if (intSign(m_wheelAngleDeltaAccumulator) != intSign(delta)) {
466 m_wheelAngleDeltaAccumulator = 0;
469 m_wheelAngleDeltaAccumulator += delta;
470 if (m_wheelAngleDeltaAccumulator > 120) {
471 m_wheelAngleDeltaAccumulator = 0;
473 } else if (m_wheelAngleDeltaAccumulator < -120) {
474 m_wheelAngleDeltaAccumulator = 0;
481 void BaseDiagram::paintContents(QPainter* painter)
485 void BaseDiagram::recomputeBounds(bool resetZoom)
491 m_autoScalePan = true;
493 m_panOffset = QPointF();
499 void BaseDiagram::doComputeBounds()
501 // no-op in the base class
504 void BaseDiagram::extendBounds(const QPointF& p)
506 extendRect(m_bounds, p);
509 QPointF BaseDiagram::project(const SGGeod& geod, const SGGeod& center)
511 double r = earth_radius_lat(geod.getLatitudeRad());
512 double ref_lat = center.getLatitudeRad(),
513 ref_lon = center.getLongitudeRad(),
514 lat = geod.getLatitudeRad(),
515 lon = geod.getLongitudeRad(),
516 lonDiff = lon - ref_lon;
518 double c = acos( sin(ref_lat) * sin(lat) + cos(ref_lat) * cos(lat) * cos(lonDiff) );
520 // angular distance from center is 0
521 return QPointF(0.0, 0.0);
524 double k = c / sin(c);
526 if (ref_lat == (90 * SG_DEGREES_TO_RADIANS))
528 x = (SGD_PI / 2 - lat) * sin(lonDiff);
529 y = -(SGD_PI / 2 - lat) * cos(lonDiff);
531 else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS))
533 x = (SGD_PI / 2 + lat) * sin(lonDiff);
534 y = (SGD_PI / 2 + lat) * cos(lonDiff);
538 x = k * cos(lat) * sin(lonDiff);
539 y = k * ( cos(ref_lat) * sin(lat) - sin(ref_lat) * cos(lat) * cos(lonDiff) );
542 // flip for top-left origin
543 return QPointF(x, -y) * r;
546 SGGeod BaseDiagram::unproject(const QPointF& xy, const SGGeod& center)
548 double r = earth_radius_lat(center.getLatitudeRad());
551 ref_lat = center.getLatitudeRad(),
552 ref_lon = center.getLongitudeRad(),
553 rho = QVector2D(xy).length(),
560 // invert y to balance the equivalent in project()
563 lat = asin( cos(c) * sin(ref_lat) + (y * sin(c) * cos(ref_lat)) / rho);
565 if (ref_lat == (90 * SG_DEGREES_TO_RADIANS)) // north pole
567 lon = ref_lon + atan(-x/y);
569 else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS)) // south pole
571 lon = ref_lon + atan(x/y);
575 lon = ref_lon + atan(x* sin(c) / (rho * cos(ref_lat) * cos(c) - y * sin(ref_lat) * sin(c)));
578 return SGGeod::fromRad(lon, lat);
581 QPointF BaseDiagram::project(const SGGeod& geod) const
583 return project(geod, m_projectionCenter);
586 QPixmap BaseDiagram::iconForPositioned(const FGPositionedRef& pos,
587 const IconOptions& options)
589 // if airport type, check towered or untowered
590 bool small = options.testFlag(SmallIcons);
592 bool isTowered = false;
593 if (FGAirport::isAirportType(pos)) {
594 FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
595 isTowered = apt->hasTower();
598 switch (pos->type()) {
599 case FGPositioned::VOR:
600 if (static_cast<FGNavRecord*>(pos.ptr())->isVORTAC())
601 return QPixmap(":/vortac-icon");
603 if (static_cast<FGNavRecord*>(pos.ptr())->hasDME())
604 return QPixmap(":/vor-dme-icon");
606 return QPixmap(":/vor-icon");
608 case FGPositioned::AIRPORT:
609 return iconForAirport(static_cast<FGAirport*>(pos.ptr()), options);
611 case FGPositioned::HELIPORT:
612 return QPixmap(":/heliport-icon");
613 case FGPositioned::SEAPORT:
614 return QPixmap(isTowered ? ":/seaport-tower-icon" : ":/seaport-icon");
615 case FGPositioned::NDB:
616 return QPixmap(small ? ":/ndb-small-icon" : ":/ndb-icon");
617 case FGPositioned::FIX:
618 return QPixmap(":/waypoint-icon");
627 QPixmap BaseDiagram::iconForAirport(FGAirport* apt, const IconOptions& options)
629 if (apt->isClosed()) {
630 return QPixmap(":/airport-closed-icon");
633 if (!apt->hasHardRunwayOfLengthFt(1500)) {
634 return QPixmap(apt->hasTower() ? ":/airport-tower-icon" : ":/airport-icon");
637 if (options.testFlag(LargeAirportPlans) && apt->hasHardRunwayOfLengthFt(8500)) {
638 QPixmap result(32, 32);
639 result.fill(Qt::transparent);
642 p.setRenderHint(QPainter::Antialiasing, true);
643 QRectF b = result.rect().adjusted(4, 4, -4, -4);
644 QVector<QLineF> lines = projectAirportRuwaysIntoRect(apt, b);
646 p.setPen(QPen(QColor(0x03, 0x83, 0xbf), 8));
649 p.setPen(QPen(Qt::white, 2));
655 QPixmap result(25, 25);
656 result.fill(Qt::transparent);
660 p.setRenderHint(QPainter::Antialiasing, true);
663 p.setBrush(apt->hasTower() ? QColor(0x03, 0x83, 0xbf) :
664 QColor(0x9b, 0x5d, 0xa2));
665 p.drawEllipse(QPointF(13, 13), 10, 10);
667 FGRunwayRef r = apt->longestRunway();
669 p.setPen(QPen(Qt::white, 2));
671 p.rotate(r->headingDeg());
672 p.drawLine(0, -8, 0, 8);
678 QVector<QLineF> BaseDiagram::projectAirportRuwaysWithCenter(FGAirportRef apt, const SGGeod& c)
682 const FGRunwayList& runways(apt->getRunwaysWithoutReciprocals());
683 FGRunwayList::const_iterator it;
685 for (it = runways.begin(); it != runways.end(); ++it) {
686 FGRunwayRef rwy = *it;
687 QPointF p1 = project(rwy->geod(), c);
688 QPointF p2 = project(rwy->end(), c);
689 r.append(QLineF(p1, p2));
695 void BaseDiagram::setAircraftType(LauncherAircraftType type)
697 m_aircraftType = type;
701 QVector<QLineF> BaseDiagram::projectAirportRuwaysIntoRect(FGAirportRef apt, const QRectF &bounds)
703 QVector<QLineF> r = projectAirportRuwaysWithCenter(apt, apt->geod());
706 Q_FOREACH(const QLineF& l, r) {
707 extendRect(extent, l.p1());
708 extendRect(extent, l.p2());
711 // find constraining scale factor
712 double ratioInX = bounds.width() / extent.width();
713 double ratioInY = bounds.height() / extent.height();
716 t.translate(bounds.left(), bounds.top());
717 t.scale(std::min(ratioInX, ratioInY),
718 std::min(ratioInX, ratioInY));
719 t.translate(-extent.left(), -extent.top()); // move unscaled to 0,0
721 for (int i=0; i<r.size(); ++i) {