]> git.mxchange.org Git - flightgear.git/blob - src/GUI/BaseDiagram.cxx
Label de-overlapping for diagrams
[flightgear.git] / src / GUI / BaseDiagram.cxx
1 // BaseDiagram.cxx - part of GUI launcher using Qt5
2 //
3 // Written by James Turner, started December 2014.
4 //
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
6 //
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.
11 //
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.
16 //
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.
20
21 #include "BaseDiagram.hxx"
22
23 #include <limits>
24
25 #include <QPainter>
26 #include <QDebug>
27 #include <QVector2D>
28 #include <QMouseEvent>
29
30 #include <Navaids/navrecord.hxx>
31 #include <Navaids/positioned.hxx>
32 #include <Airports/airport.hxx>
33
34 /* equatorial and polar earth radius */
35 const float rec  = 6378137;          // earth radius, equator (?)
36 const float rpol = 6356752.314f;      // earth radius, polar   (?)
37
38 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
39 static float earth_radius_lat( float lat )
40 {
41     double a = cos(lat)/rec;
42     double b = sin(lat)/rpol;
43     return 1.0f / sqrt( a * a + b * b );
44 }
45
46 BaseDiagram::BaseDiagram(QWidget* pr) :
47     QWidget(pr),
48     m_autoScalePan(true),
49     m_wheelAngleDeltaAccumulator(0)
50 {
51     setSizePolicy(QSizePolicy::MinimumExpanding,
52                   QSizePolicy::MinimumExpanding);
53     setMinimumSize(100, 100);
54 }
55
56 QTransform BaseDiagram::transform() const
57 {
58     QTransform t;
59     t.translate(width() / 2, height() / 2); // center projection origin in the widget
60     t.scale(m_scale, m_scale);
61
62     // apply any pan offset that exists
63     t.translate(m_panOffset.x(), m_panOffset.y());
64     // center the bounding box (may not be at the origin)
65     t.translate(-m_bounds.center().x(), -m_bounds.center().y());
66     return t;
67 }
68
69 void BaseDiagram::clearIgnoredNavaids()
70 {
71     m_ignored.clear();
72 }
73
74 void BaseDiagram::addIgnoredNavaid(FGPositionedRef pos)
75 {
76     if (isNavaidIgnored(pos))
77         return;
78     m_ignored.push_back(pos);
79 }
80
81 void BaseDiagram::extendRect(QRectF &r, const QPointF &p)
82 {
83     if (p.x() < r.left()) {
84         r.setLeft(p.x());
85     } else if (p.x() > r.right()) {
86         r.setRight(p.x());
87     }
88
89     if (p.y() < r.top()) {
90         r.setTop(p.y());
91     } else if (p.y() > r.bottom()) {
92         r.setBottom(p.y());
93     }
94 }
95
96 void BaseDiagram::paintEvent(QPaintEvent* pe)
97 {
98     QPainter p(this);
99     p.setRenderHints(QPainter::Antialiasing);
100     p.fillRect(rect(), QColor(0x3f, 0x3f, 0x3f));
101
102     if (m_autoScalePan) {
103         // fit bounds within our available space, allowing for a margin
104         const int MARGIN = 32; // pixels
105         double ratioInX = (width() - MARGIN * 2) / m_bounds.width();
106         double ratioInY = (height() - MARGIN * 2) / m_bounds.height();
107         m_scale = std::min(ratioInX, ratioInY);
108     }
109
110     QTransform t(transform());
111     p.setTransform(t);
112
113     paintNavaids(&p);
114
115     paintContents(&p);
116 }
117
118 void BaseDiagram::paintAirplaneIcon(QPainter* painter, const SGGeod& geod, int headingDeg)
119 {
120     QPointF pos = project(geod);
121     QPixmap pix(":/airplane-icon");
122     pos = painter->transform().map(pos);
123     painter->resetTransform();
124     painter->translate(pos.x(), pos.y());
125     painter->rotate(headingDeg);
126
127     painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
128     QRect airplaneIconRect = pix.rect();
129     airplaneIconRect.moveCenter(QPoint(0,0));
130     painter->drawPixmap(airplaneIconRect, pix);
131 }
132
133 class MapFilter : public FGPositioned::TypeFilter
134 {
135 public:
136     MapFilter()
137     {
138       //  addType(FGPositioned::FIX);
139         addType(FGPositioned::AIRPORT);
140         addType(FGPositioned::NDB);
141         addType(FGPositioned::VOR);
142     }
143
144     virtual bool pass(FGPositioned* aPos) const
145     {
146         bool ok = TypeFilter::pass(aPos);
147         if (ok && (aPos->type() == FGPositioned::FIX)) {
148             // ignore fixes which end in digits
149             if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
150                 return false;
151             }
152         }
153
154         return ok;
155     }
156 };
157
158
159 void BaseDiagram::paintNavaids(QPainter* painter)
160 {
161     QTransform xf = painter->transform();
162     painter->setTransform(QTransform()); // reset to identity
163     QTransform invT = xf.inverted();
164     SGGeod topLeft = unproject(invT.map(QPointF(0,0)), m_projectionCenter);
165
166     double minRunwayLengthFt = (16 / m_scale) * SG_METER_TO_FEET;
167     // add 10nm fudge factor
168     double drawRangeNm = SGGeodesy::distanceNm(m_projectionCenter, topLeft) + 10.0;
169     //qDebug() << "draw range computed as:" << drawRangeNm;
170
171
172     MapFilter f;
173     FGPositionedList items = FGPositioned::findWithinRange(m_projectionCenter, drawRangeNm, &f);
174
175     m_labelRects.clear();
176     m_labelRects.reserve(items.size());
177
178     FGPositionedList::const_iterator it;
179     for (it = items.begin(); it != items.end(); ++it) {
180         FGPositionedRef pos(*it);
181         bool drawAsIcon = true;
182         if (isNavaidIgnored(pos))
183             continue;
184
185         FGPositioned::Type ty(pos->type());
186         if (ty == FGPositioned::AIRPORT) {
187             FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
188             if (apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
189
190                 drawAsIcon = false;
191                 painter->setTransform(xf);
192                 QVector<QLineF> lines = projectAirportRuwaysWithCenter(apt, m_projectionCenter);
193
194                 QPen pen(QColor(0x03, 0x83, 0xbf), 8);
195                 pen.setCosmetic(true);
196                 painter->setPen(pen);
197                 painter->drawLines(lines);
198
199                 QPen linePen(Qt::white, 2);
200                 linePen.setCosmetic(true);
201                 painter->setPen(linePen);
202                 painter->drawLines(lines);
203
204                 painter->resetTransform();
205             }
206         }
207
208         if (drawAsIcon) {
209             QPixmap pm = iconForPositioned(pos);
210             QPointF loc = xf.map(project(pos->geod()));
211             QRect iconRect = pm.rect();
212             iconRect.moveCenter(loc.toPoint());
213             painter->drawPixmap(iconRect, pm);
214
215        // compute label text so we can measure it
216             QString label;
217             if (FGAirport::isAirportType(pos.ptr())) {
218                 label = QString::fromStdString((*it)->name());
219             } else {
220                 label = QString::fromStdString((*it)->ident());
221             }
222
223             if (ty == FGPositioned::NDB) {
224                 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
225                 label.append("\n").append(QString::number(nav->get_freq() / 100));
226             } else if (ty == FGPositioned::VOR) {
227                 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
228                 label.append("\n").append(QString::number(nav->get_freq() / 100.0, 'f', 1));
229             }
230
231             QRect textBounds = painter->boundingRect(QRect(0, 0, 100, 100),
232                                                      Qt::TextWordWrap, label);
233             int textFlags;
234             textBounds = rectAndFlagsForLabel(pos->guid(), iconRect,
235                                               textBounds.size(),
236                                               textFlags);
237
238             painter->setPen(QColor(0x03, 0x83, 0xbf));
239             painter->drawText(textBounds, textFlags, label);
240         }
241     }
242
243     // restore transform
244     painter->setTransform(xf);
245 }
246
247 bool BaseDiagram::isNavaidIgnored(const FGPositionedRef &pos) const
248 {
249     return m_ignored.contains(pos);
250 }
251
252 bool BaseDiagram::isLabelRectAvailable(const QRect &r) const
253 {
254     Q_FOREACH(const QRect& lr, m_labelRects) {
255         if (lr.intersects(r))
256             return false;
257     }
258
259     return true;
260 }
261
262 int BaseDiagram::textFlagsForLabelPosition(LabelPosition pos)
263 {
264 #if 0
265     switch (pos) {
266     case LABEL_RIGHT:       return Qt::AlignLeft | Qt::AlignVCenter;
267     case LABEL_ABOVE:       return Qt::AlignHCenter | Qt::A
268     }
269 #endif
270     return 0;
271 }
272
273 QRect BaseDiagram::rectAndFlagsForLabel(PositionedID guid, const QRect& item,
274                                         const QSize &bounds,
275                                         int& flags) const
276 {
277     m_labelRects.append(item);
278     int pos = m_labelPositions.value(guid, LABEL_RIGHT);
279     bool firstAttempt = true;
280     flags = Qt::TextWordWrap;
281
282     while (pos < LAST_POSITION) {
283         QRect r = labelPositioned(item, bounds, static_cast<LabelPosition>(pos));
284         if (isLabelRectAvailable(r)) {
285             m_labelRects.append(r);
286             m_labelPositions[guid] = static_cast<LabelPosition>(pos);
287             flags |= textFlagsForLabelPosition(static_cast<LabelPosition>(pos));
288             return r;
289         } else if (firstAttempt && (pos != LABEL_RIGHT)) {
290             pos = LABEL_RIGHT;
291         } else {
292             ++pos;
293         }
294
295         firstAttempt = false;
296     }
297
298     return QRect(item.x(), item.y(), bounds.width(), bounds.height());
299 }
300
301 QRect BaseDiagram::labelPositioned(const QRect& itemRect,
302                                    const QSize& bounds,
303                                    LabelPosition lp) const
304 {
305     const int SHORT_MARGIN = 4;
306     const int DIAGONAL_MARGIN = 20;
307
308     switch (lp) {
309     // cardinal compass points are short (close in)
310     case LABEL_RIGHT:
311         return QRect(itemRect.right() + SHORT_MARGIN,
312                      itemRect.center().y() - bounds.height() / 2,
313                      bounds.width(),
314                      bounds.height());
315     case LABEL_ABOVE:
316         return QRect(itemRect.center().x() - (bounds.width() / 2),
317                      itemRect.top() - (SHORT_MARGIN + bounds.height()),
318                      bounds.width(),
319                      bounds.height());
320     case LABEL_BELOW:
321         return QRect(itemRect.center().x() - (bounds.width() / 2),
322                      itemRect.bottom() + SHORT_MARGIN,
323                      bounds.width(),
324                      bounds.height());
325     case LABEL_LEFT:
326         return QRect(itemRect.left() - (SHORT_MARGIN + bounds.width()),
327                      itemRect.center().y() - bounds.height() / 2,
328                      bounds.width(),
329                      bounds.height());
330
331     // first diagonals are further out (to hopefully have a better chance
332     // of finding clear space
333
334     case LABEL_NE:
335         return QRect(itemRect.right() + DIAGONAL_MARGIN,
336                      itemRect.top() - (DIAGONAL_MARGIN + bounds.height()),
337                      bounds.width(),
338                      bounds.height());
339
340     default:
341         qWarning() << Q_FUNC_INFO << "Implement me";
342
343     }
344
345     return QRect(itemRect.x(), itemRect.y(), bounds.width(), bounds.height());
346 }
347
348 void BaseDiagram::mousePressEvent(QMouseEvent *me)
349 {
350     m_lastMousePos = me->pos();
351     m_didPan = false;
352 }
353
354 void BaseDiagram::mouseMoveEvent(QMouseEvent *me)
355 {
356     m_autoScalePan = false;
357
358     QPointF delta = me->pos() - m_lastMousePos;
359     m_lastMousePos = me->pos();
360
361     // offset is stored in metres so we don't have to modify it when
362     // zooming
363     m_panOffset += (delta / m_scale);
364     m_didPan = true;
365
366     update();
367 }
368
369 int intSign(int v)
370 {
371     return (v == 0) ? 0 : (v < 0) ? -1 : 1;
372 }
373
374 void BaseDiagram::wheelEvent(QWheelEvent *we)
375 {
376     m_autoScalePan = false;
377
378     int delta = we->angleDelta().y();
379     if (delta == 0)
380         return;
381
382     if (intSign(m_wheelAngleDeltaAccumulator) != intSign(delta)) {
383         m_wheelAngleDeltaAccumulator = 0;
384     }
385
386     m_wheelAngleDeltaAccumulator += delta;
387     if (m_wheelAngleDeltaAccumulator > 120) {
388         m_wheelAngleDeltaAccumulator = 0;
389         m_scale *= 2.0;
390     } else if (m_wheelAngleDeltaAccumulator < -120) {
391         m_wheelAngleDeltaAccumulator = 0;
392         m_scale *= 0.5;
393     }
394
395     update();
396 }
397
398 void BaseDiagram::paintContents(QPainter* painter)
399 {
400 }
401
402 void BaseDiagram::recomputeBounds(bool resetZoom)
403 {
404     m_bounds = QRectF();
405     doComputeBounds();
406
407     if (resetZoom) {
408         m_autoScalePan = true;
409         m_scale = 1.0;
410         m_panOffset = QPointF();
411     }
412
413     update();
414 }
415
416 void BaseDiagram::doComputeBounds()
417 {
418     // no-op in the base class
419 }
420
421 void BaseDiagram::extendBounds(const QPointF& p)
422 {
423     extendRect(m_bounds, p);
424 }
425
426 QPointF BaseDiagram::project(const SGGeod& geod, const SGGeod& center)
427 {
428     double r = earth_radius_lat(geod.getLatitudeRad());
429     double ref_lat = center.getLatitudeRad(),
430     ref_lon = center.getLongitudeRad(),
431     lat = geod.getLatitudeRad(),
432     lon = geod.getLongitudeRad(),
433     lonDiff = lon - ref_lon;
434
435     double c = acos( sin(ref_lat) * sin(lat) + cos(ref_lat) * cos(lat) * cos(lonDiff) );
436     if (c == 0.0) {
437         // angular distance from center is 0
438         return QPointF(0.0, 0.0);
439     }
440
441     double k = c / sin(c);
442     double x, y;
443     if (ref_lat == (90 * SG_DEGREES_TO_RADIANS))
444     {
445         x = (SGD_PI / 2 - lat) * sin(lonDiff);
446         y = -(SGD_PI / 2 - lat) * cos(lonDiff);
447     }
448     else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS))
449     {
450         x = (SGD_PI / 2 + lat) * sin(lonDiff);
451         y = (SGD_PI / 2 + lat) * cos(lonDiff);
452     }
453     else
454     {
455         x = k * cos(lat) * sin(lonDiff);
456         y = k * ( cos(ref_lat) * sin(lat) - sin(ref_lat) * cos(lat) * cos(lonDiff) );
457     }
458
459     return QPointF(x, -y) * r;
460 }
461
462 SGGeod BaseDiagram::unproject(const QPointF& xy, const SGGeod& center)
463 {
464     double r = earth_radius_lat(center.getLatitudeRad());
465     double lat = 0,
466            lon = 0,
467            ref_lat = center.getLatitudeRad(),
468            ref_lon = center.getLongitudeRad(),
469            rho = QVector2D(xy).length(),
470            c = rho/r;
471
472     if (rho == 0) {
473         return center;
474     }
475
476     double x = xy.x(), y = xy.y();
477     lat = asin( cos(c) * sin(ref_lat) + (y * sin(c) * cos(ref_lat)) / rho);
478
479     if (ref_lat == (90 * SG_DEGREES_TO_RADIANS)) // north pole
480     {
481         lon = ref_lon + atan(-x/y);
482     }
483     else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS)) // south pole
484     {
485         lon = ref_lon + atan(x/y);
486     }
487     else
488     {
489         lon = ref_lon + atan(x* sin(c) / (rho * cos(ref_lat) * cos(c) - y * sin(ref_lat) * sin(c)));
490     }
491
492     return SGGeod::fromRad(lon, lat);
493 }
494
495 QPointF BaseDiagram::project(const SGGeod& geod) const
496 {
497     return project(geod, m_projectionCenter);
498 }
499
500 QPixmap BaseDiagram::iconForPositioned(const FGPositionedRef& pos,
501                                        const IconOptions& options)
502 {
503     // if airport type, check towered or untowered
504     bool small = options.testFlag(SmallIcons);
505
506     bool isTowered = false;
507     if (FGAirport::isAirportType(pos)) {
508         FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
509         isTowered = apt->hasTower();
510     }
511
512     switch (pos->type()) {
513     case FGPositioned::VOR:
514         if (static_cast<FGNavRecord*>(pos.ptr())->isVORTAC())
515             return QPixmap(":/vortac-icon");
516
517         if (static_cast<FGNavRecord*>(pos.ptr())->hasDME())
518             return QPixmap(":/vor-dme-icon");
519
520         return QPixmap(":/vor-icon");
521
522     case FGPositioned::AIRPORT:
523         return iconForAirport(static_cast<FGAirport*>(pos.ptr()), options);
524
525     case FGPositioned::HELIPORT:
526         return QPixmap(":/heliport-icon");
527     case FGPositioned::SEAPORT:
528         return QPixmap(isTowered ? ":/seaport-tower-icon" : ":/seaport-icon");
529     case FGPositioned::NDB:
530         return QPixmap(small ? ":/ndb-small-icon" : ":/ndb-icon");
531     case FGPositioned::FIX:
532         return QPixmap(":/waypoint-icon");
533
534     default:
535         break;
536     }
537
538     return QPixmap();
539 }
540
541 QPixmap BaseDiagram::iconForAirport(FGAirport* apt, const IconOptions& options)
542 {
543     if (!apt->hasHardRunwayOfLengthFt(1500)) {
544         return QPixmap(apt->hasTower() ? ":/airport-tower-icon" : ":/airport-icon");
545     }
546
547     if (options.testFlag(LargeAirportPlans) && apt->hasHardRunwayOfLengthFt(8500)) {
548         QPixmap result(32, 32);
549         result.fill(Qt::transparent);
550         {
551             QPainter p(&result);
552             p.setRenderHint(QPainter::Antialiasing, true);
553             QRectF b = result.rect().adjusted(4, 4, -4, -4);
554             QVector<QLineF> lines = projectAirportRuwaysIntoRect(apt, b);
555
556             p.setPen(QPen(QColor(0x03, 0x83, 0xbf), 8));
557             p.drawLines(lines);
558
559             p.setPen(QPen(Qt::white, 2));
560             p.drawLines(lines);
561         }
562         return result;
563     }
564
565     QPixmap result(25, 25);
566     result.fill(Qt::transparent);
567
568     {
569         QPainter p(&result);
570         p.setRenderHint(QPainter::Antialiasing, true);
571         p.setPen(Qt::NoPen);
572
573         p.setBrush(apt->hasTower() ? QColor(0x03, 0x83, 0xbf) :
574                                      QColor(0x9b, 0x5d, 0xa2));
575         p.drawEllipse(QPointF(13, 13), 10, 10);
576
577         FGRunwayRef r = apt->longestRunway();
578
579         p.setPen(QPen(Qt::white, 2));
580         p.translate(13, 13);
581         p.rotate(r->headingDeg());
582         p.drawLine(0, -8, 0, 8);
583     }
584
585     return result;
586 }
587
588 QVector<QLineF> BaseDiagram::projectAirportRuwaysWithCenter(FGAirportRef apt, const SGGeod& c)
589 {
590     QVector<QLineF> r;
591
592     const FGRunwayList& runways(apt->getRunwaysWithoutReciprocals());
593     FGRunwayList::const_iterator it;
594
595     for (it = runways.begin(); it != runways.end(); ++it) {
596         FGRunwayRef rwy = *it;
597         QPointF p1 = project(rwy->geod(), c);
598         QPointF p2 = project(rwy->end(), c);
599         r.append(QLineF(p1, p2));
600     }
601
602     return r;
603 }
604
605 QVector<QLineF> BaseDiagram::projectAirportRuwaysIntoRect(FGAirportRef apt, const QRectF &bounds)
606 {
607     QVector<QLineF> r = projectAirportRuwaysWithCenter(apt, apt->geod());
608
609     QRectF extent;
610     Q_FOREACH(const QLineF& l, r) {
611         extendRect(extent, l.p1());
612         extendRect(extent, l.p2());
613     }
614
615  // find constraining scale factor
616     double ratioInX = bounds.width() / extent.width();
617     double ratioInY = bounds.height() / extent.height();
618
619     QTransform t;
620     t.translate(bounds.left(), bounds.top());
621     t.scale(std::min(ratioInX, ratioInY),
622             std::min(ratioInX, ratioInY));
623     t.translate(-extent.left(), -extent.top()); // move unscaled to 0,0
624
625     for (int i=0; i<r.size(); ++i) {
626         r[i] = t.map(r[i]);
627     }
628
629     return r;
630 }