HUD.cc 48.5 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2
/*=====================================================================

3
QGroundControl Open Source Ground Control Station
pixhawk's avatar
pixhawk committed
4

5
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
pixhawk's avatar
pixhawk committed
6

7
This file is part of the QGROUNDCONTROL project
pixhawk's avatar
pixhawk committed
8

9
    QGROUNDCONTROL is free software: you can redistribute it and/or modify
pixhawk's avatar
pixhawk committed
10 11 12 13
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

14
    QGROUNDCONTROL is distributed in the hope that it will be useful,
pixhawk's avatar
pixhawk committed
15 16 17 18 19
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
20
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
pixhawk's avatar
pixhawk committed
21 22 23 24 25

======================================================================*/

/**
 * @file
26
 *   @brief Head Up Display (HUD)
pixhawk's avatar
pixhawk committed
27 28 29 30 31
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

32
#include <QShowEvent>
33 34 35 36
#include <QContextMenuEvent>
#include <QMenu>
#include <QDesktopServices>
#include <QFileDialog>
37
#include <QPaintEvent>
38

pixhawk's avatar
pixhawk committed
39 40
#include <QDebug>
#include <cmath>
pixhawk's avatar
pixhawk committed
41
#include <qmath.h>
pixhawk's avatar
pixhawk committed
42
#include <limits>
pixhawk's avatar
pixhawk committed
43 44

#include "UASManager.h"
45
#include "UAS.h"
pixhawk's avatar
pixhawk committed
46
#include "HUD.h"
47
#include "QGC.h"
pixhawk's avatar
pixhawk committed
48 49

/**
50 51
 * @warning The HUD widget will not start painting its content automatically
 *          to update the view, start the auto-update by calling HUD::start().
pixhawk's avatar
pixhawk committed
52 53 54 55 56
 *
 * @param width
 * @param height
 * @param parent
 */
57
HUD::HUD(int width, int height, QWidget* parent)
58
    : QLabel(parent),
59 60 61 62 63 64 65 66 67
      uas(NULL),
      yawInt(0.0f),
      mode(tr("UNKNOWN MODE")),
      state(tr("UNKNOWN STATE")),
      fuelStatus(tr("00.0V (00m:00s)")),
      xCenterOffset(0.0f),
      yCenterOffset(0.0f),
      vwidth(200.0f),
      vheight(150.0f),
68
      vGaugeSpacing(65.0f),
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
      vPitchPerDeg(6.0f), ///< 4 mm y translation per degree)
      rawBuffer1(NULL),
      rawBuffer2(NULL),
      rawImage(NULL),
      rawLastIndex(0),
      rawExpectedBytes(0),
      bytesPerLine(1),
      imageStarted(false),
      receivedDepth(8),
      receivedChannels(1),
      receivedWidth(640),
      receivedHeight(480),
      defaultColor(QColor(70, 200, 70)),
      setPointColor(QColor(200, 20, 200)),
      warningColor(Qt::yellow),
      criticalColor(Qt::red),
      infoColor(QColor(20, 200, 20)),
      fuelColor(criticalColor),
      warningBlinkRate(5),
      refreshTimer(new QTimer(this)),
      noCamera(true),
      hardwareAcceleration(true),
      strongStrokeWidth(1.5f),
      normalStrokeWidth(1.0f),
      fineStrokeWidth(0.5f),
      waypointName(""),
      roll(0.0f),
      pitch(0.0f),
      yaw(0.0f),
      rollLP(0.0f),
      pitchLP(0.0f),
      yawLP(0.0f),
      yawDiff(0.0f),
      xPos(0.0),
      yPos(0.0),
      zPos(0.0),
      xSpeed(0.0),
      ySpeed(0.0),
      zSpeed(0.0),
      lastSpeedUpdate(0),
      totalSpeed(0.0),
      totalAcc(0.0),
      lat(0.0),
      lon(0.0),
      alt(0.0),
      load(0.0f),
      offlineDirectory(""),
      nextOfflineImage(""),
117
      HUDInstrumentsEnabled(false),
118
      videoEnabled(true),
119
      xImageFactor(1.0),
120
      yImageFactor(1.0),
121
      imageRequested(false),
122 123
      imageLoggingEnabled(false),
    image(NULL)
pixhawk's avatar
pixhawk committed
124 125 126 127 128 129 130 131
{
    // Fill with black background
    QImage fill = QImage(width, height, QImage::Format_Indexed8);
    fill.setNumColors(3);
    fill.setColor(0, qRgb(0, 0, 0));
    fill.setColor(1, qRgb(0, 0, 0));
    fill.setColor(2, qRgb(0, 0, 0));
    fill.fill(0);
132
    glImage = fill;
pixhawk's avatar
pixhawk committed
133

134 135
    // Set auto fill to false
    setAutoFillBackground(false);
pixhawk's avatar
pixhawk committed
136

137 138 139 140 141
    // Set minimum size
    setMinimumSize(80, 60);
    // Set preferred size
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scalingFactor = this->width()/vwidth;
pixhawk's avatar
pixhawk committed
142 143

    // Refresh timer
144
    refreshTimer->setInterval(updateInterval);
145
    connect(refreshTimer, SIGNAL(timeout()), this, SLOT(repaint()));
pixhawk's avatar
pixhawk committed
146 147

    // Resize to correct size and fill with image
148
    QWidget::resize(this->width(), this->height());
pixhawk's avatar
pixhawk committed
149 150 151 152 153 154 155

    fontDatabase = QFontDatabase();
    const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
    const QString fontFamilyName = "Bitstream Vera Sans";
    if(!QFile::exists(fontFileName)) qDebug() << "ERROR! font file: " << fontFileName << " DOES NOT EXIST!";

    fontDatabase.addApplicationFont(fontFileName);
156 157
    font = fontDatabase.font(fontFamilyName, "Roman", qMax(5,(int)(10.0f*scalingFactor*1.2f+0.5f)));
    QFont* fontPtr = &font;
158
    if (!fontPtr) {
159
        qDebug() << "ERROR! FONT NOT LOADED!";
160
    } else {
161 162
        if (font.family() != fontFamilyName) qDebug() << "ERROR! WRONG FONT LOADED: " << fontFamilyName;
    }
pixhawk's avatar
pixhawk committed
163 164

    // Connect with UAS
165 166
    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setActiveUAS(UASInterface*)));

167 168 169
    createActions();

    if (UASManager::instance()->getActiveUAS() != NULL) setActiveUAS(UASManager::instance()->getActiveUAS());
pixhawk's avatar
pixhawk committed
170 171
}

172
HUD::~HUD()
pixhawk's avatar
pixhawk committed
173
{
174
    refreshTimer->stop();
pixhawk's avatar
pixhawk committed
175 176
}

177
QSize HUD::sizeHint() const
178
{
179
    return QSize(width(), (width()*3.0f)/4);
180 181
}

182
void HUD::showEvent(QShowEvent* event)
183
{
184 185
    // React only to internal (pre-display)
    // events
186
    QWidget::showEvent(event);
187
    refreshTimer->start(updateInterval);
LM's avatar
LM committed
188
    emit visibilityChanged(true);
189 190
}

191
void HUD::hideEvent(QHideEvent* event)
192 193 194
{
    // React only to internal (pre-display)
    // events
195
    refreshTimer->stop();
196
    QWidget::hideEvent(event);
LM's avatar
LM committed
197
    emit visibilityChanged(false);
pixhawk's avatar
pixhawk committed
198 199
}

200
void HUD::contextMenuEvent (QContextMenuEvent* event)
201 202
{
    QMenu menu(this);
203
    // Update actions
204
    enableHUDAction->setChecked(HUDInstrumentsEnabled);
205 206
    enableVideoAction->setChecked(videoEnabled);

207
    menu.addAction(enableHUDAction);
208
    //menu.addAction(selectHUDColorAction);
209 210
    menu.addAction(enableVideoAction);
    menu.addAction(selectOfflineDirectoryAction);
211
    menu.addAction(selectSaveDirectoryAction);
212 213 214
    menu.exec(event->globalPos());
}

215
void HUD::createActions()
216
{
217 218
    enableHUDAction = new QAction(tr("Enable HUD"), this);
    enableHUDAction->setStatusTip(tr("Show the HUD instruments in this window"));
219
    enableHUDAction->setCheckable(true);
220
    enableHUDAction->setChecked(HUDInstrumentsEnabled);
221 222 223 224 225 226 227 228
    connect(enableHUDAction, SIGNAL(triggered(bool)), this, SLOT(enableHUDInstruments(bool)));

    enableVideoAction = new QAction(tr("Enable Video Live feed"), this);
    enableVideoAction->setStatusTip(tr("Show the video live feed"));
    enableVideoAction->setCheckable(true);
    enableVideoAction->setChecked(videoEnabled);
    connect(enableVideoAction, SIGNAL(triggered(bool)), this, SLOT(enableVideo(bool)));

229
    selectOfflineDirectoryAction = new QAction(tr("Load image log"), this);
230 231
    selectOfflineDirectoryAction->setStatusTip(tr("Load previously logged images into simulation / replay"));
    connect(selectOfflineDirectoryAction, SIGNAL(triggered()), this, SLOT(selectOfflineDirectory()));
232 233 234 235 236

    selectSaveDirectoryAction = new QAction(tr("Save images to directory"), this);
    selectSaveDirectoryAction->setStatusTip(tr("Save images from image stream to a directory"));
    selectSaveDirectoryAction->setCheckable(true);
    connect(selectSaveDirectoryAction, SIGNAL(triggered(bool)), this, SLOT(saveImages(bool)));
237 238
}

pixhawk's avatar
pixhawk committed
239 240
/**
 *
241
 * @param uas the UAS/MAV to monitor/display with the HUD
pixhawk's avatar
pixhawk committed
242
 */
243
void HUD::setActiveUAS(UASInterface* uas)
pixhawk's avatar
pixhawk committed
244
{
245
    if (this->uas != NULL) {
pixhawk's avatar
pixhawk committed
246
        // Disconnect any previously connected active MAV
dongfang's avatar
dongfang committed
247 248 249
        disconnect(this->uas, SIGNAL(attitudeChanged(UASInterface*, double, double, double, quint64)), this, SLOT(updateAttitude(UASInterface*, double, double, double, quint64)));
        disconnect(this->uas, SIGNAL(attitudeChanged(UASInterface*,int, double, double, double, quint64)), this, SLOT(updateAttitude(UASInterface*,int,double, double, double, quint64)));
        disconnect(this->uas, SIGNAL(batteryChanged(UASInterface*, double, double, double, int)), this, SLOT(updateBattery(UASInterface*, double, double, double, int)));
250 251 252
        disconnect(this->uas, SIGNAL(statusChanged(UASInterface*,QString,QString)), this, SLOT(updateState(UASInterface*,QString)));
        disconnect(this->uas, SIGNAL(modeChanged(int,QString,QString)), this, SLOT(updateMode(int,QString,QString)));
        disconnect(this->uas, SIGNAL(heartbeat(UASInterface*)), this, SLOT(receiveHeartbeat(UASInterface*)));
253

254
        disconnect(this->uas, SIGNAL(localPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateLocalPosition(UASInterface*,double,double,double,quint64)));
pixhawk's avatar
pixhawk committed
255
        disconnect(this->uas, SIGNAL(globalPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateGlobalPosition(UASInterface*,double,double,double,quint64)));
256
        disconnect(this->uas, SIGNAL(velocityChanged_NEDspeedChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateSpeed(UASInterface*,double,double,double,quint64)));
257
        disconnect(this->uas, SIGNAL(waypointSelected(int,int)), this, SLOT(selectWaypoint(int, int)));
pixhawk's avatar
pixhawk committed
258

259
        // Try to disconnect the image link
260
        UAS* u = dynamic_cast<UAS*>(this->uas);
261
        if (u) {
262
            disconnect(u, SIGNAL(imageStarted(quint64)), this, SLOT(startImage(quint64)));
LM's avatar
LM committed
263
            disconnect(u, SIGNAL(imageReady(UASInterface*)), this, SLOT(copyImage()));
264 265
        }
    }
266

267
    if (uas) {
268 269 270
        // Now connect the new UAS
        // Setup communication
        connect(uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*, double, double, double, quint64)));
271
        connect(uas, SIGNAL(attitudeChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,int,double, double, double, quint64)));
dongfang's avatar
dongfang committed
272
        connect(uas, SIGNAL(batteryChanged(UASInterface*, double, double, double, int)), this, SLOT(updateBattery(UASInterface*, double, double, double, int)));
273 274 275 276 277
        connect(uas, SIGNAL(statusChanged(UASInterface*,QString,QString)), this, SLOT(updateState(UASInterface*,QString)));
        connect(uas, SIGNAL(modeChanged(int,QString,QString)), this, SLOT(updateMode(int,QString,QString)));
        connect(uas, SIGNAL(heartbeat(UASInterface*)), this, SLOT(receiveHeartbeat(UASInterface*)));

        connect(uas, SIGNAL(localPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateLocalPosition(UASInterface*,double,double,double,quint64)));
pixhawk's avatar
pixhawk committed
278
        connect(uas, SIGNAL(globalPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateGlobalPosition(UASInterface*,double,double,double,quint64)));
279
        connect(uas, SIGNAL(velocityChanged_NED(UASInterface*,double,double,double,quint64)), this, SLOT(updateSpeed(UASInterface*,double,double,double,quint64)));
280 281 282 283
        connect(uas, SIGNAL(waypointSelected(int,int)), this, SLOT(selectWaypoint(int, int)));

        // Try to connect the image link
        UAS* u = dynamic_cast<UAS*>(uas);
284
        if (u) {
285
            connect(u, SIGNAL(imageStarted(quint64)), this, SLOT(startImage(quint64)));
LM's avatar
LM committed
286
            connect(u, SIGNAL(imageReady(UASInterface*)), this, SLOT(copyImage()));
287
        }
288

289 290 291
        // Set new UAS
        this->uas = uas;
    }
pixhawk's avatar
pixhawk committed
292 293
}

294
//void HUD::updateAttitudeThrustSetPoint(UASInterface* uas, double rollDesired, double pitchDesired, double yawDesired, double thrustDesired, quint64 msec)
295 296 297 298 299 300
//{
////    updateValue(uas, "roll desired", rollDesired, msec);
////    updateValue(uas, "pitch desired", pitchDesired, msec);
////    updateValue(uas, "yaw desired", yawDesired, msec);
////    updateValue(uas, "thrust desired", thrustDesired, msec);
//}
pixhawk's avatar
pixhawk committed
301

302
void HUD::updateAttitude(UASInterface* uas, double roll, double pitch, double yaw, quint64 timestamp)
pixhawk's avatar
pixhawk committed
303
{
304 305
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
306 307 308 309 310 311
    if (!isnan(roll) && !isinf(roll) && !isnan(pitch) && !isinf(pitch) && !isnan(yaw) && !isinf(yaw))
    {
        this->roll = roll;
        this->pitch = pitch*3.35f; // Constant here is the 'focal length' of the projection onto the plane
        this->yaw = yaw;
    }
pixhawk's avatar
pixhawk committed
312 313
}

314
void HUD::updateAttitude(UASInterface* uas, int component, double roll, double pitch, double yaw, quint64 timestamp)
315 316 317
{
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
318 319 320 321
    if (!isnan(roll) && !isinf(roll) && !isnan(pitch) && !isinf(pitch) && !isnan(yaw) && !isinf(yaw))
    {
        attitudes.insert(component, QVector3D(roll, pitch*3.35f, yaw)); // Constant here is the 'focal length' of the projection onto the plane
    }
322 323
}

dongfang's avatar
dongfang committed
324
void HUD::updateBattery(UASInterface* uas, double voltage, double current, double percent, int seconds)
pixhawk's avatar
pixhawk committed
325
{
326
    Q_UNUSED(uas);
327
    Q_UNUSED(seconds);
dongfang's avatar
dongfang committed
328
    Q_UNUSED(current);
329
    fuelStatus = tr("BAT [%1% | %2V]").arg(percent, 2, 'f', 0, QChar('0')).arg(voltage, 4, 'f', 1, QChar('0'));
330
    if (percent < 20.0f) {
pixhawk's avatar
pixhawk committed
331
        fuelColor = warningColor;
332
    } else if (percent < 10.0f) {
pixhawk's avatar
pixhawk committed
333
        fuelColor = criticalColor;
334
    } else {
pixhawk's avatar
pixhawk committed
335 336 337 338
        fuelColor = infoColor;
    }
}

339
void HUD::receiveHeartbeat(UASInterface*)
pixhawk's avatar
pixhawk committed
340 341 342
{
}

343
void HUD::updateThrust(UASInterface* uas, double thrust)
pixhawk's avatar
pixhawk committed
344
{
345 346 347
    Q_UNUSED(uas);
    Q_UNUSED(thrust);
//    updateValue(uas, "thrust", thrust, MG::TIME::getGroundTimeNow());
pixhawk's avatar
pixhawk committed
348 349
}

350
void HUD::updateLocalPosition(UASInterface* uas,double x,double y,double z,quint64 timestamp)
pixhawk's avatar
pixhawk committed
351
{
352 353 354 355 356
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
    this->xPos = x;
    this->yPos = y;
    this->zPos = z;
pixhawk's avatar
pixhawk committed
357 358
}

359
void HUD::updateGlobalPosition(UASInterface* uas,double lat, double lon, double altitude, quint64 timestamp)
pixhawk's avatar
pixhawk committed
360
{
361 362 363 364 365
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
    this->lat = lat;
    this->lon = lon;
    this->alt = altitude;
pixhawk's avatar
pixhawk committed
366 367
}

368
void HUD::updateSpeed(UASInterface* uas,double x,double y,double z,quint64 timestamp)
pixhawk's avatar
pixhawk committed
369
{
370 371 372 373 374
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
    this->xSpeed = x;
    this->ySpeed = y;
    this->zSpeed = z;
pixhawk's avatar
pixhawk committed
375 376 377
    double newTotalSpeed = sqrt(xSpeed*xSpeed + ySpeed*ySpeed + zSpeed*zSpeed);
    totalAcc = (newTotalSpeed - totalSpeed) / ((double)(lastSpeedUpdate - timestamp)/1000.0);
    totalSpeed = newTotalSpeed;
pixhawk's avatar
pixhawk committed
378 379 380 381 382 383
}

/**
 * Updates the current system state, but only if the uas matches the currently monitored uas.
 *
 * @param uas the system the state message originates from
384
 * @param state short state text, displayed in HUD
pixhawk's avatar
pixhawk committed
385
 */
386
void HUD::updateState(UASInterface* uas,QString state)
pixhawk's avatar
pixhawk committed
387
{
388 389
    // Only one UAS is connected at a time
    Q_UNUSED(uas);
390 391 392 393 394 395 396
    this->state = state;
}

/**
 * Updates the current system mode, but only if the uas matches the currently monitored uas.
 *
 * @param uas the system the state message originates from
397
 * @param mode short mode text, displayed in HUD
398
 */
399
void HUD::updateMode(int id,QString mode, QString description)
400
{
401
    // Only one UAS is connected at a time
402 403
    Q_UNUSED(id);
    Q_UNUSED(description);
404
    this->mode = mode;
pixhawk's avatar
pixhawk committed
405 406
}

407
void HUD::updateLoad(UASInterface* uas, double load)
pixhawk's avatar
pixhawk committed
408
{
409 410 411
    Q_UNUSED(uas);
    this->load = load;
    //updateValue(uas, "load", load, MG::TIME::getGroundTimeNow());
pixhawk's avatar
pixhawk committed
412 413 414 415 416 417
}

/**
 * @param y coordinate in pixels to be converted to reference mm units
 * @return the screen coordinate relative to the QGLWindow origin
 */
418
float HUD::refToScreenX(float x)
pixhawk's avatar
pixhawk committed
419
{
420
    //qDebug() << "sX: " << (scalingFactor * x) << "Orig:" << x;
pixhawk's avatar
pixhawk committed
421 422 423 424 425 426
    return (scalingFactor * x);
}
/**
 * @param x coordinate in pixels to be converted to reference mm units
 * @return the screen coordinate relative to the QGLWindow origin
 */
427
float HUD::refToScreenY(float y)
pixhawk's avatar
pixhawk committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441
{
    //qDebug() << "sY: " << (scalingFactor * y);
    return (scalingFactor * y);
}

/**
 * Paint text on top of the image and OpenGL drawings
 *
 * @param text chars to write
 * @param color text color
 * @param fontSize text size in mm
 * @param refX position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels.
 * @param refY position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels.
 */
442
void HUD::paintText(QString text, QColor color, float fontSize, float refX, float refY, QPainter* painter)
pixhawk's avatar
pixhawk committed
443 444 445 446 447
{
    QPen prevPen = painter->pen();
    float pPositionX = refToScreenX(refX) - (fontSize*scalingFactor*0.072f);
    float pPositionY = refToScreenY(refY) - (fontSize*scalingFactor*0.212f);

448 449
    QFont font("Bitstream Vera Sans");
    // Enforce minimum font size of 5 pixels
450
    int fSize = qMax(5, (int)(fontSize*scalingFactor*1.26f));
451
    font.setPixelSize(fSize);
pixhawk's avatar
pixhawk committed
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

    QFontMetrics metrics = QFontMetrics(font);
    int border = qMax(4, metrics.leading());
    QRect rect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
                                      Qt::AlignLeft | Qt::TextWordWrap, text);
    painter->setPen(color);
    painter->setFont(font);
    painter->setRenderHint(QPainter::TextAntialiasing);
    painter->drawText(pPositionX, pPositionY,
                      rect.width(), rect.height(),
                      Qt::AlignCenter | Qt::TextWordWrap, text);
    painter->setPen(prevPen);
}

/**
 * @param referencePositionX horizontal position in the reference mm-unit space
 * @param referencePositionY horizontal position in the reference mm-unit space
 * @param referenceWidth width in the reference mm-unit space
 * @param referenceHeight width in the reference mm-unit space
 */
472
void HUD::setupGLView(float referencePositionX, float referencePositionY, float referenceWidth, float referenceHeight)
pixhawk's avatar
pixhawk committed
473 474 475 476 477 478 479 480
{
    int pixelWidth  = (int)(referenceWidth * scalingFactor);
    int pixelHeight = (int)(referenceHeight * scalingFactor);
    // Translate and scale the GL view in the virtual reference coordinate units on the screen
    int pixelPositionX = (int)((referencePositionX * scalingFactor) + xCenterOffset);
    int pixelPositionY = this->height() - (referencePositionY * scalingFactor) + yCenterOffset - pixelHeight;
}

481
void HUD::paintRollPitchStrips()
pixhawk's avatar
pixhawk committed
482 483 484 485
{
}


486
void HUD::paintEvent(QPaintEvent *event)
pixhawk's avatar
pixhawk committed
487
{
488 489

    paintHUD();
490 491
}

492
void HUD::paintHUD()
493
{
494
    if (isVisible()) {
495 496 497
        //    static quint64 interval = 0;
        //    qDebug() << "INTERVAL:" << MG::TIME::getGroundTimeNow() - interval << __FILE__ << __LINE__;
        //    interval = MG::TIME::getGroundTimeNow();
lm's avatar
lm committed
498

499
#if (QGC_EVENTLOOP_DEBUG)
500
        qDebug() << "EVENTLOOP:" << __FILE__ << __LINE__;
501 502
#endif

503 504
        // Read out most important values to limit hash table lookups
        // Low-pass roll, pitch and yaw
505 506
        rollLP = roll;//rollLP * 0.2f + 0.8f * roll;
        pitchLP = pitch;//pitchLP * 0.2f + 0.8f * pitch;
507
        yawLP = (!isinf(yaw) && !isnan(yaw)) ? yaw : yawLP;//yawLP * 0.2f + 0.8f * yaw;
pixhawk's avatar
pixhawk committed
508

509 510
        // Translate for yaw
        const float maxYawTrans = 60.0f;
511

512 513 514
        float newYawDiff = yawDiff;
        if (isinf(newYawDiff)) newYawDiff = yawDiff;
        if (newYawDiff > M_PI) newYawDiff = newYawDiff - M_PI;
515

516
        if (newYawDiff < -M_PI) newYawDiff = newYawDiff + M_PI;
517

518
        newYawDiff = yawDiff * 0.8 + newYawDiff * 0.2;
519

520
        yawDiff = newYawDiff;
521

522
        yawInt += newYawDiff;
523

524 525
        if (yawInt > M_PI) yawInt = (float)M_PI;
        if (yawInt < -M_PI) yawInt = (float)-M_PI;
526

527
        float yawTrans = yawInt * (float)maxYawTrans;
528
        yawInt *= 0.6f;
lm's avatar
lm committed
529

530
        if ((yawTrans < 5.0) && (yawTrans > -5.0)) yawTrans = 0;
lm's avatar
lm committed
531

532 533
        // Negate to correct direction
        yawTrans = -yawTrans;
lm's avatar
lm committed
534

535 536
        yawTrans = 0;

537
        //qDebug() << "yaw translation" << yawTrans << "integral" << yawInt << "difference" << yawDiff << "yaw" << yaw;
538

539 540 541 542 543
        // Update scaling factor
        // adjust scaling to fit both horizontally and vertically
        scalingFactor = this->width()/vwidth;
        double scalingFactorH = this->height()/vheight;
        if (scalingFactorH < scalingFactor) scalingFactor = scalingFactorH;
pixhawk's avatar
pixhawk committed
544

545
        // Fill with black background
546 547
        if (videoEnabled) {
            if (nextOfflineImage != "" && QFileInfo(nextOfflineImage).exists()) {
548 549
                qDebug() << __FILE__ << __LINE__ << "template image:" << nextOfflineImage;
                QImage fill = QImage(nextOfflineImage);
550

551
                glImage = fill;
552

553 554 555
                // Reset to save load efforts
                nextOfflineImage = "";
            }
556

557 558 559 560
        }

        if (dataStreamEnabled || videoEnabled)
        {
pixhawk's avatar
pixhawk committed
561

LM's avatar
LM committed
562 563 564
            xImageFactor = width() / (float)glImage.width();
            yImageFactor = height() / (float)glImage.height();
            float imageFactor = qMin(xImageFactor, yImageFactor);
565
            // Resize to correct size and fill with image
566
            // FIXME
567

568
        }
569

570 571 572 573 574 575 576
        QPainter painter;
        painter.begin(this);
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
        QPixmap pmap = QPixmap::fromImage(glImage).scaledToWidth(width());
        painter.drawPixmap(0, (height() - pmap.height()) / 2, pmap);

577 578
        // END OF OPENGL PAINTING

579
        if (HUDInstrumentsEnabled) {
580

581 582 583 584
            //glEnable(GL_MULTISAMPLE);

            // QT PAINTING
            //makeCurrent();
585

586 587 588 589 590 591 592
            painter.translate((this->vwidth/2.0+xCenterOffset)*scalingFactor, (this->vheight/2.0+yCenterOffset)*scalingFactor);

            // COORDINATE FRAME IS NOW (0,0) at CENTER OF WIDGET


            // Draw all fixed indicators
            // BATTERY
593
            paintText(fuelStatus, fuelColor, 6.0f, (-vwidth/2.0) + 10, -vheight/2.0 + 6, &painter);
594
            // Waypoint
595 596 597 598 599 600 601
            paintText(waypointName, defaultColor, 6.0f, (-vwidth/3.0) + 10, +vheight/3.0 + 15, &painter);

            QPen linePen(Qt::SolidLine);
            linePen.setWidth(refLineWidthToPen(1.0f));
            linePen.setColor(defaultColor);
            painter.setBrush(Qt::NoBrush);
            painter.setPen(linePen);
602

603 604 605 606 607 608
            // YAW INDICATOR
            //
            //      .
            //    .   .
            //   .......
            //
609 610
            const float yawIndicatorWidth = 12.0f;
            const float yawIndicatorY = vheight/2.0f - 15.0f;
611 612 613 614 615 616
            QPolygon yawIndicator(4);
            yawIndicator.setPoint(0, QPoint(refToScreenX(0.0f), refToScreenY(yawIndicatorY)));
            yawIndicator.setPoint(1, QPoint(refToScreenX(yawIndicatorWidth/2.0f), refToScreenY(yawIndicatorY+yawIndicatorWidth)));
            yawIndicator.setPoint(2, QPoint(refToScreenX(-yawIndicatorWidth/2.0f), refToScreenY(yawIndicatorY+yawIndicatorWidth)));
            yawIndicator.setPoint(3, QPoint(refToScreenX(0.0f), refToScreenY(yawIndicatorY)));
            painter.drawPolyline(yawIndicator);
617
            painter.setPen(linePen);
pixhawk's avatar
pixhawk committed
618

619
            // CENTER
pixhawk's avatar
pixhawk committed
620

621 622 623 624 625
            // HEADING INDICATOR
            //
            //    __      __
            //       \/\/
            //
626
            const float hIndicatorWidth = 20.0f;
627 628 629 630 631 632 633 634 635 636 637 638
            const float hIndicatorY = -25.0f;
            const float hIndicatorYLow = hIndicatorY + hIndicatorWidth / 6.0f;
            const float hIndicatorSegmentWidth = hIndicatorWidth / 7.0f;
            QPolygon hIndicator(7);
            hIndicator.setPoint(0, QPoint(refToScreenX(0.0f-hIndicatorWidth/2.0f), refToScreenY(hIndicatorY)));
            hIndicator.setPoint(1, QPoint(refToScreenX(0.0f-hIndicatorWidth/2.0f+hIndicatorSegmentWidth*1.75f), refToScreenY(hIndicatorY)));
            hIndicator.setPoint(2, QPoint(refToScreenX(0.0f-hIndicatorSegmentWidth*1.0f), refToScreenY(hIndicatorYLow)));
            hIndicator.setPoint(3, QPoint(refToScreenX(0.0f), refToScreenY(hIndicatorY)));
            hIndicator.setPoint(4, QPoint(refToScreenX(0.0f+hIndicatorSegmentWidth*1.0f), refToScreenY(hIndicatorYLow)));
            hIndicator.setPoint(5, QPoint(refToScreenX(0.0f+hIndicatorWidth/2.0f-hIndicatorSegmentWidth*1.75f), refToScreenY(hIndicatorY)));
            hIndicator.setPoint(6, QPoint(refToScreenX(0.0f+hIndicatorWidth/2.0f), refToScreenY(hIndicatorY)));
            painter.drawPolyline(hIndicator);
pixhawk's avatar
pixhawk committed
639 640


641
            // SETPOINT
642
            const float centerWidth = 8.0f;
643 644
            // TODO
            //painter.drawEllipse(QPointF(refToScreenX(qMin(10.0f, values.value("roll desired", 0.0f) * 10.0f)), refToScreenY(qMin(10.0f, values.value("pitch desired", 0.0f) * 10.0f))), refToScreenX(centerWidth/2.0f), refToScreenX(centerWidth/2.0f));
pixhawk's avatar
pixhawk committed
645

646
            const float centerCrossWidth = 20.0f;
647 648 649 650 651 652
            // left
            painter.drawLine(QPointF(refToScreenX(-centerWidth / 2.0f), refToScreenY(0.0f)), QPointF(refToScreenX(-centerCrossWidth / 2.0f), refToScreenY(0.0f)));
            // right
            painter.drawLine(QPointF(refToScreenX(centerWidth / 2.0f), refToScreenY(0.0f)), QPointF(refToScreenX(centerCrossWidth / 2.0f), refToScreenY(0.0f)));
            // top
            painter.drawLine(QPointF(refToScreenX(0.0f), refToScreenY(-centerWidth / 2.0f)), QPointF(refToScreenX(0.0f), refToScreenY(-centerCrossWidth / 2.0f)));
pixhawk's avatar
pixhawk committed
653

654

pixhawk's avatar
pixhawk committed
655

656
            // COMPASS
657 658
            const float compassY = -vheight/2.0f + 6.0f;
            QRectF compassRect(QPointF(refToScreenX(-12.0f), refToScreenY(compassY)), QSizeF(refToScreenX(24.0f), refToScreenY(12.0f)));
659
            painter.setBrush(Qt::NoBrush);
660 661
            painter.setPen(linePen);
            painter.drawRoundedRect(compassRect, 3, 3);
662
            QString yawAngle;
pixhawk's avatar
pixhawk committed
663

664
            //    const float yawDeg = ((values.value("yaw", 0.0f)/M_PI)*180.0f)+180.f;
pixhawk's avatar
pixhawk committed
665

666
            // YAW is in compass-human readable format, so 0 .. 360 deg.
barthess's avatar
barthess committed
667
            float yawDeg = (yawLP / M_PI) * 180.0f;
668 669 670
            if (yawDeg < 0) yawDeg += 360;
            if (yawDeg > 360) yawDeg -= 360;
            /* final safeguard for really stupid systems */
671 672
            int yawCompass = static_cast<int>(yawDeg) % 360;
            yawAngle.sprintf("%03d", yawCompass);
673 674 675 676
            paintText(yawAngle, defaultColor,8.5f, -9.8f, compassY+ 1.7f, &painter);

            painter.setBrush(Qt::NoBrush);
            painter.setPen(linePen);
pixhawk's avatar
pixhawk committed
677

678
            // CHANGE RATE STRIPS
679
            drawChangeRateStrip(-95.0f, -60.0f, 40.0f, -10.0f, 10.0f, -zSpeed, &painter);
pixhawk's avatar
pixhawk committed
680

681
            // CHANGE RATE STRIPS
682
            drawChangeRateStrip(95.0f, -60.0f, 40.0f, -10.0f, 10.0f, totalAcc, &painter,true);
683 684

            // GAUGES
pixhawk's avatar
pixhawk committed
685

686
            // Left altitude gauge
pixhawk's avatar
pixhawk committed
687 688
            float gaugeAltitude;

689
            if (this->alt != 0) {
pixhawk's avatar
pixhawk committed
690
                gaugeAltitude = alt;
691
            } else {
pixhawk's avatar
pixhawk committed
692 693 694
                gaugeAltitude = -zPos;
            }

695 696 697
            painter.setBrush(Qt::NoBrush);
            painter.setPen(linePen);

698
            drawChangeIndicatorGauge(-vGaugeSpacing, 35.0f, 15.0f, 10.0f, gaugeAltitude, defaultColor, &painter, false);
699
            paintText("alt m", defaultColor, 5.5f, -73.0f, 50, &painter);
700

701
            // Right speed gauge
702
            drawChangeIndicatorGauge(vGaugeSpacing, 35.0f, 15.0f, 10.0f, totalSpeed, defaultColor, &painter, false);
703
            paintText("v m/s", defaultColor, 5.5f, 55.0f, 50, &painter);
pixhawk's avatar
pixhawk committed
704 705


706 707 708 709 710 711 712 713
            // Waypoint name
            if (waypointName != "") paintText(waypointName, defaultColor, 2.0f, (-vwidth/3.0) + 10, +vheight/3.0 + 15, &painter);

            // MOVING PARTS


            painter.translate(refToScreenX(yawTrans), 0);

714 715 716 717 718 719 720
            // Old single-component pitch drawing
//            // Rotate view and draw all roll-dependent indicators
//            painter.rotate((rollLP/M_PI)* -180.0f);

//            painter.translate(0, (-pitchLP/(float)M_PI)* -180.0f * refToScreenY(1.8f));

//            //qDebug() << "ROLL" << roll << "PITCH" << pitch << "YAW DIFF" << valuesDot.value("roll", 0.0f);
721

722
//            // PITCH
723

724
//            paintPitchLines(pitchLP, &painter);
725

726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
            QColor attColor = painter.pen().color();

            // Draw multi-component attitude
            foreach (QVector3D att, attitudes.values())
            {
                attColor = attColor.darker(200);
                painter.setPen(attColor);
                // Rotate view and draw all roll-dependent indicators
                painter.rotate((att.x()/M_PI)* -180.0f);

                painter.translate(0, (-att.y()/(float)M_PI)* -180.0f * refToScreenY(1.8f));

                //qDebug() << "ROLL" << roll << "PITCH" << pitch << "YAW DIFF" << valuesDot.value("roll", 0.0f);

                // PITCH

                paintPitchLines(att.y(), &painter);
743 744
                painter.translate(0, -(-att.y()/(float)M_PI)* -180.0f * refToScreenY(1.8f));
                painter.rotate(-(att.x()/M_PI)* -180.0f);
745
            }
746

747

748
        }
749 750

        painter.end();
751
    }
752

pixhawk's avatar
pixhawk committed
753 754
}

pixhawk's avatar
pixhawk committed
755 756 757 758

/**
 * @param pitch pitch angle in degrees (-180 to 180)
 */
759
void HUD::paintPitchLines(float pitch, QPainter* painter)
pixhawk's avatar
pixhawk committed
760 761 762 763 764 765 766
{
    QString label;

    const float yDeg = vPitchPerDeg;
    const float lineDistance = 5.0f; ///< One pitch line every 10 degrees
    const float posIncrement = yDeg * lineDistance;
    float posY = posIncrement;
767
    const float posLimit = sqrt(pow(vwidth, 2.0f) + pow(vheight, 2.0f))*3.0f;
pixhawk's avatar
pixhawk committed
768 769 770 771 772 773

    const float offsetAbs = pitch * yDeg;

    float offset = pitch;
    if (offset < 0) offset = -offset;
    int offsetCount = 0;
774 775 776 777
    while (offset > lineDistance) {
        offset -= lineDistance;
        offsetCount++;
    }
pixhawk's avatar
pixhawk committed
778 779 780 781 782 783 784 785 786 787 788

    int iPos = (int)(0.5f + lineDistance); ///< The first line
    int iNeg = (int)(-0.5f - lineDistance); ///< The first line

    offset *= yDeg;


    painter->setPen(defaultColor);

    posY = -offsetAbs + posIncrement; //+ 100;// + lineDistance;

789
    while (posY < posLimit) {
pixhawk's avatar
pixhawk committed
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        paintPitchLinePos(label.sprintf("%3d", iPos), 0.0f, -posY, painter);
        posY += posIncrement;
        iPos += (int)lineDistance;
    }



    // HORIZON
    //
    //    ------------    ------------
    //
    const float pitchWidth = 30.0f;
    const float pitchGap = pitchWidth / 2.5f;
    const QColor horizonColor = defaultColor;
    const float diagonal = sqrt(pow(vwidth, 2.0f) + pow(vheight, 2.0f));
    const float lineWidth = refLineWidthToPen(0.5f);

    // Left horizon
    drawLine(0.0f-diagonal, offsetAbs, 0.0f-pitchGap/2.0f, offsetAbs, lineWidth, horizonColor, painter);
    // Right horizon
    drawLine(0.0f+pitchGap/2.0f, offsetAbs, 0.0f+diagonal, offsetAbs, lineWidth, horizonColor, painter);



    label.clear();

    posY = offsetAbs  + posIncrement;


819
    while (posY < posLimit) {
pixhawk's avatar
pixhawk committed
820 821 822 823 824 825
        paintPitchLineNeg(label.sprintf("%3d", iNeg), 0.0f, posY, painter);
        posY += posIncrement;
        iNeg -= (int)lineDistance;
    }
}

826
void HUD::paintPitchLinePos(QString text, float refPosX, float refPosY, QPainter* painter)
pixhawk's avatar
pixhawk committed
827 828 829 830 831 832
{
    //painter->setPen(QPen(QBrush, normalStrokeWidth));

    const float pitchWidth = 30.0f;
    const float pitchGap = pitchWidth / 2.5f;
    const float pitchHeight = pitchWidth / 12.0f;
833 834
    const float textSize = pitchHeight * 1.6f;
    const float lineWidth = 1.5f;
pixhawk's avatar
pixhawk committed
835 836 837 838 839 840 841 842 843 844 845 846

    // Positive pitch indicator:
    //
    //      _______      _______
    //     |10                  |
    //

    // Left vertical line
    drawLine(refPosX-pitchWidth/2.0f, refPosY, refPosX-pitchWidth/2.0f, refPosY+pitchHeight, lineWidth, defaultColor, painter);
    // Left horizontal line
    drawLine(refPosX-pitchWidth/2.0f, refPosY, refPosX-pitchGap/2.0f, refPosY, lineWidth, defaultColor, painter);
    // Text left
847
    paintText(text, defaultColor, textSize, refPosX-pitchWidth/2.0 + 0.75f, refPosY + pitchHeight - 1.3f, painter);
pixhawk's avatar
pixhawk committed
848 849 850 851 852 853 854

    // Right vertical line
    drawLine(refPosX+pitchWidth/2.0f, refPosY, refPosX+pitchWidth/2.0f, refPosY+pitchHeight, lineWidth, defaultColor, painter);
    // Right horizontal line
    drawLine(refPosX+pitchWidth/2.0f, refPosY, refPosX+pitchGap/2.0f, refPosY, lineWidth, defaultColor, painter);
}

855
void HUD::paintPitchLineNeg(QString text, float refPosX, float refPosY, QPainter* painter)
pixhawk's avatar
pixhawk committed
856 857 858 859
{
    const float pitchWidth = 30.0f;
    const float pitchGap = pitchWidth / 2.5f;
    const float pitchHeight = pitchWidth / 12.0f;
860
    const float textSize = pitchHeight * 1.6f;
pixhawk's avatar
pixhawk committed
861 862
    const float segmentWidth = ((pitchWidth - pitchGap)/2.0f) / 7.0f; ///< Four lines and three gaps -> 7 segments

863
    const float lineWidth = 1.5f;
pixhawk's avatar
pixhawk committed
864 865 866 867 868 869 870 871 872 873 874

    // Negative pitch indicator:
    //
    //      -10
    //     _ _ _ _|     |_ _ _ _
    //
    //

    // Left vertical line
    drawLine(refPosX-pitchGap/2.0, refPosY, refPosX-pitchGap/2.0, refPosY-pitchHeight, lineWidth, defaultColor, painter);
    // Left horizontal line with four segments
875
    for (int i = 0; i < 7; i+=2) {
pixhawk's avatar
pixhawk committed
876 877 878
        drawLine(refPosX-pitchWidth/2.0+(i*segmentWidth), refPosY, refPosX-pitchWidth/2.0+(i*segmentWidth)+segmentWidth, refPosY, lineWidth, defaultColor, painter);
    }
    // Text left
879
    paintText(text, defaultColor, textSize, refPosX-pitchWidth/2.0f + 0.75f, refPosY + pitchHeight - 1.3f, painter);
pixhawk's avatar
pixhawk committed
880 881 882 883

    // Right vertical line
    drawLine(refPosX+pitchGap/2.0, refPosY, refPosX+pitchGap/2.0, refPosY-pitchHeight, lineWidth, defaultColor, painter);
    // Right horizontal line with four segments
884
    for (int i = 0; i < 7; i+=2) {
pixhawk's avatar
pixhawk committed
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
        drawLine(refPosX+pitchWidth/2.0f-(i*segmentWidth), refPosY, refPosX+pitchWidth/2.0f-(i*segmentWidth)-segmentWidth, refPosY, lineWidth, defaultColor, painter);
    }
}

void rotatePointClockWise(QPointF& p, float angle)
{
    // Standard 2x2 rotation matrix, counter-clockwise
    //
    //   |  cos(phi)   sin(phi) |
    //   | -sin(phi)   cos(phi) |
    //

    //p.setX(cos(angle) * p.x() + sin(angle) * p.y());
    //p.setY(-sin(angle) * p.x() + cos(angle) * p.y());


    p.setX(cos(angle) * p.x() + sin(angle)* p.y());
    p.setY((-1.0f * sin(angle) * p.x()) + cos(angle) * p.y());
}

905
float HUD::refLineWidthToPen(float line)
pixhawk's avatar
pixhawk committed
906 907 908 909 910 911 912 913 914 915 916 917
{
    return line * 2.50f;
}

/**
 * Rotate a polygon around a point
 *
 * @param p polygon to rotate
 * @param origin the rotation center
 * @param angle rotation angle, in radians
 * @return p Polygon p rotated by angle around the origin point
 */
918
void HUD::rotatePolygonClockWiseRad(QPolygonF& p, float angle, QPointF origin)
pixhawk's avatar
pixhawk committed
919 920 921 922 923 924
{
    // Standard 2x2 rotation matrix, counter-clockwise
    //
    //   |  cos(phi)   sin(phi) |
    //   | -sin(phi)   cos(phi) |
    //
925
    for (int i = 0; i < p.size(); i++) {
pixhawk's avatar
pixhawk committed
926 927 928 929 930 931 932 933 934 935 936
        QPointF curr = p.at(i);

        const float x = curr.x();
        const float y = curr.y();

        curr.setX(((cos(angle) * (x-origin.x())) + (-sin(angle) * (y-origin.y()))) + origin.x());
        curr.setY(((sin(angle) * (x-origin.x())) + (cos(angle) * (y-origin.y()))) + origin.y());
        p.replace(i, curr);
    }
}

937
void HUD::drawPolygon(QPolygonF refPolygon, QPainter* painter)
pixhawk's avatar
pixhawk committed
938 939 940
{
    // Scale coordinates
    QPolygonF draw(refPolygon.size());
941
    for (int i = 0; i < refPolygon.size(); i++) {
pixhawk's avatar
pixhawk committed
942 943 944 945 946 947 948 949
        QPointF curr;
        curr.setX(refToScreenX(refPolygon.at(i).x()));
        curr.setY(refToScreenY(refPolygon.at(i).y()));
        draw.replace(i, curr);
    }
    painter->drawPolygon(draw);
}

950
void HUD::drawChangeRateStrip(float xRef, float yRef, float height, float minRate, float maxRate, float value, QPainter* painter,bool reverse)
pixhawk's avatar
pixhawk committed
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
{
    float scaledValue = value;

    // Saturate value
    if (value > maxRate) scaledValue = maxRate;
    if (value < minRate) scaledValue = minRate;

    //           x (Origin: xRef, yRef)
    //           -
    //           |
    //           |
    //           |
    //           =
    //           |
    //   -0.005 >|
    //           |
    //           -

    const float width = height / 8.0f;
970
    const float lineWidth = 1.5f;
pixhawk's avatar
pixhawk committed
971 972 973

    // Indicator lines
    // Top horizontal line
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    if (reverse)
    {
        drawLine(xRef, yRef, xRef-width, yRef, lineWidth, defaultColor, painter);
        // Vertical main line
        drawLine(xRef-width/2.0f, yRef, xRef-width/2.0f, yRef+height, lineWidth, defaultColor, painter);
        // Zero mark
        drawLine(xRef, yRef+height/2.0f, xRef-width, yRef+height/2.0f, lineWidth, defaultColor, painter);
        // Horizontal bottom line
        drawLine(xRef, yRef+height, xRef-width, yRef+height, lineWidth, defaultColor, painter);

        // Text
        QString label;
        label.sprintf("%+06.2f >", value);

        QFont font("Bitstream Vera Sans");
        // Enforce minimum font size of 5 pixels
        //int fSize = qMax(5, (int)(6.0f*scalingFactor*1.26f));
        font.setPixelSize(6.0f * 1.26f);

        QFontMetrics metrics = QFontMetrics(font);
        paintText(label, defaultColor, 6.0f, (xRef-width) - metrics.width(label), yRef+height-((scaledValue - minRate)/(maxRate-minRate))*height - 1.6f, painter);
    }
    else
    {
        drawLine(xRef, yRef, xRef+width, yRef, lineWidth, defaultColor, painter);
        // Vertical main line
        drawLine(xRef+width/2.0f, yRef, xRef+width/2.0f, yRef+height, lineWidth, defaultColor, painter);
        // Zero mark
        drawLine(xRef, yRef+height/2.0f, xRef+width, yRef+height/2.0f, lineWidth, defaultColor, painter);
        // Horizontal bottom line
        drawLine(xRef, yRef+height, xRef+width, yRef+height, lineWidth, defaultColor, painter);

        // Text
        QString label;
        label.sprintf("< %+06.2f", value);
        paintText(label, defaultColor, 6.0f, xRef+width/2.0f, yRef+height-((scaledValue - minRate)/(maxRate-minRate))*height - 1.6f, painter);
    }
pixhawk's avatar
pixhawk committed
1011 1012
}

1013
//void HUD::drawSystemIndicator(float xRef, float yRef, int maxNum, float maxWidth, float maxHeight, QPainter* painter)
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
//{
//    Q_UNUSED(maxWidth);
//    Q_UNUSED(maxHeight);
//    if (values.size() > 0)
//    {
//        QString selectedKey = values.begin().key();
//        //   | | | | | |
//        //   | | | | | |
//        //   x speed: 2.54

//        // One column per value
//        QMapIterator<QString, float> value(values);

//        float x = xRef;
//        float y = yRef;

//        const float vspacing = 1.0f;
//        float width = 1.5f;
//        float height = 1.5f;
//        const float hspacing = 0.6f;

//        // TODO ensure that instrument stays smaller than maxWidth and maxHeight


//        int i = 0;
//        while (value.hasNext() && i < maxNum)
//        {
//            value.next();
//            QBrush brush(Qt::SolidPattern);


//            if (value.value() < 0.01f && value.value() > -0.01f)
//            {
//                brush.setColor(Qt::gray);
//            }
//            else if (value.value() > 0.01f)
//            {
//                brush.setColor(Qt::blue);
//            }
//            else
//            {
//                brush.setColor(Qt::yellow);
//            }

//            painter->setBrush(brush);
//            painter->setPen(Qt::NoPen);

//            // Draw current value colormap
//            painter->drawRect(refToScreenX(x), refToScreenY(y), refToScreenX(width), refToScreenY(height));

//            // Draw change rate colormap
//            painter->drawRect(refToScreenX(x), refToScreenY(y+height+hspacing), refToScreenX(width), refToScreenY(height));

//            // Draw mean value colormap
//            painter->drawRect(refToScreenX(x), refToScreenY(y+2.0f*(height+hspacing)), refToScreenX(width), refToScreenY(height));

//            // Add spacing
//            x += width+vspacing;

//            // Iterate
//            i++;
//        }

//        // Draw detail label
//        QString detail = "NO DATA AVAILABLE";

//        if (values.contains(selectedKey))
//        {
//            detail = values.find(selectedKey).key();
//            detail.append(": ");
//            detail.append(QString::number(values.find(selectedKey).value()));
//        }
//        paintText(detail, QColor(255, 255, 255), 3.0f, xRef, yRef+3.0f*(height+hspacing)+1.0f, painter);
//    }
//}
pixhawk's avatar
pixhawk committed
1089

1090
void HUD::drawChangeIndicatorGauge(float xRef, float yRef, float radius, float expectedMaxChange, float value, const QColor& color, QPainter* painter, bool solid)
pixhawk's avatar
pixhawk committed
1091 1092 1093 1094 1095
{
    // Draw the circle
    QPen circlePen(Qt::SolidLine);
    if (!solid) circlePen.setStyle(Qt::DotLine);
    circlePen.setColor(defaultColor);
1096
    circlePen.setWidth(refLineWidthToPen(2.0f));
pixhawk's avatar
pixhawk committed
1097 1098
    painter->setBrush(Qt::NoBrush);
    painter->setPen(circlePen);
1099
    drawCircle(xRef, yRef, radius, 200.0f, 170.0f, 1.5f, color, painter);
pixhawk's avatar
pixhawk committed
1100 1101 1102 1103

    QString label;
    label.sprintf("%05.1f", value);

1104 1105
    float textSize = radius / 2.5;

pixhawk's avatar
pixhawk committed
1106
    // Draw the value
1107
    paintText(label, color, textSize, xRef-textSize*1.7f, yRef-textSize*0.4f, painter);
pixhawk's avatar
pixhawk committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135

    // Draw the needle
    // Scale the rotation so that the gauge does one revolution
    // per max. change
    const float rangeScale = (2.0f * M_PI) / expectedMaxChange;
    const float maxWidth = radius / 10.0f;
    const float minWidth = maxWidth * 0.3f;

    QPolygonF p(6);

    p.replace(0, QPointF(xRef-maxWidth/2.0f, yRef-radius * 0.5f));
    p.replace(1, QPointF(xRef-minWidth/2.0f, yRef-radius * 0.9f));
    p.replace(2, QPointF(xRef+minWidth/2.0f, yRef-radius * 0.9f));
    p.replace(3, QPointF(xRef+maxWidth/2.0f, yRef-radius * 0.5f));
    p.replace(4, QPointF(xRef,               yRef-radius * 0.46f));
    p.replace(5, QPointF(xRef-maxWidth/2.0f, yRef-radius * 0.5f));

    rotatePolygonClockWiseRad(p, value*rangeScale, QPointF(xRef, yRef));

    QBrush indexBrush;
    indexBrush.setColor(defaultColor);
    indexBrush.setStyle(Qt::SolidPattern);
    painter->setPen(Qt::SolidLine);
    painter->setPen(defaultColor);
    painter->setBrush(indexBrush);
    drawPolygon(p, painter);
}

1136
void HUD::drawLine(float refX1, float refY1, float refX2, float refY2, float width, const QColor& color, QPainter* painter)
pixhawk's avatar
pixhawk committed
1137 1138 1139 1140 1141 1142 1143 1144
{
    QPen pen(Qt::SolidLine);
    pen.setWidth(refLineWidthToPen(width));
    pen.setColor(color);
    painter->setPen(pen);
    painter->drawLine(QPoint(refToScreenX(refX1), refToScreenY(refY1)), QPoint(refToScreenX(refX2), refToScreenY(refY2)));
}

1145
void HUD::drawEllipse(float refX, float refY, float radiusX, float radiusY, float startDeg, float endDeg, float lineWidth, const QColor& color, QPainter* painter)
pixhawk's avatar
pixhawk committed
1146
{
lm's avatar
lm committed
1147 1148
    Q_UNUSED(startDeg);
    Q_UNUSED(endDeg);
pixhawk's avatar
pixhawk committed
1149 1150 1151 1152 1153 1154 1155
    QPen pen(painter->pen().style());
    pen.setWidth(refLineWidthToPen(lineWidth));
    pen.setColor(color);
    painter->setPen(pen);
    painter->drawEllipse(QPointF(refToScreenX(refX), refToScreenY(refY)), refToScreenX(radiusX), refToScreenY(radiusY));
}

1156
void HUD::drawCircle(float refX, float refY, float radius, float startDeg, float endDeg, float lineWidth, const QColor& color, QPainter* painter)
pixhawk's avatar
pixhawk committed
1157 1158 1159 1160
{
    drawEllipse(refX, refY, radius, radius, startDeg, endDeg, lineWidth, color, painter);
}

1161
void HUD::selectWaypoint(int uasId, int id)
pixhawk's avatar
pixhawk committed
1162
{
1163 1164
    Q_UNUSED(uasId);
    waypointName = tr("WP") + QString::number(id);
pixhawk's avatar
pixhawk committed
1165 1166
}

1167
void HUD::setImageSize(int width, int height, int depth, int channels)
pixhawk's avatar
pixhawk committed
1168 1169
{
    // Allocate raw image in correct size
1170
    if (width != receivedWidth || height != receivedHeight || depth != receivedDepth || channels != receivedChannels || image == NULL) {
pixhawk's avatar
pixhawk committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
        // Set new size
        if (width > 0) receivedWidth  = width;
        if (height > 0) receivedHeight = height;
        if (depth > 1) receivedDepth = depth;
        if (channels > 1) receivedChannels = channels;

        rawExpectedBytes = (receivedWidth * receivedHeight * receivedDepth * receivedChannels) / 8;
        bytesPerLine = rawExpectedBytes / receivedHeight;
        // Delete old buffers if necessary
        rawImage = NULL;
        if (rawBuffer1 != NULL) delete rawBuffer1;
        if (rawBuffer2 != NULL) delete rawBuffer2;

        rawBuffer1 = (unsigned char*)malloc(rawExpectedBytes);
        rawBuffer2 = (unsigned char*)malloc(rawExpectedBytes);
        rawImage = rawBuffer1;
1187 1188
        if (image)
            delete image;
pixhawk's avatar
pixhawk committed
1189 1190 1191

        // Set image format
        // 8 BIT GREYSCALE IMAGE
1192
        if (depth <= 8 && channels == 1) {
pixhawk's avatar
pixhawk committed
1193 1194 1195
            image = new QImage(receivedWidth, receivedHeight, QImage::Format_Indexed8);
            // Create matching color table
            image->setNumColors(256);
1196
            for (int i = 0; i < 256; i++) {
pixhawk's avatar
pixhawk committed
1197 1198 1199 1200 1201 1202
                image->setColor(i, qRgb(i, i, i));
                //qDebug() << __FILE__ << __LINE__ << std::hex << i;
            }

        }
        // 32 BIT COLOR IMAGE WITH ALPHA VALUES (#ARGB)
1203
        else {
pixhawk's avatar
pixhawk committed
1204 1205 1206 1207 1208
            image = new QImage(receivedWidth, receivedHeight, QImage::Format_ARGB32);
        }

        // Fill first channel of image with black pixels
        image->fill(0);
1209
        glImage = *image;
pixhawk's avatar
pixhawk committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

        qDebug() << __FILE__ << __LINE__ << "Setting up image";

        // Set size once
        setFixedSize(receivedWidth, receivedHeight);
        setMinimumSize(receivedWidth, receivedHeight);
        setMaximumSize(receivedWidth, receivedHeight);
        // Lock down the size
        //setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
        //resize(receivedWidth, receivedHeight);
    }

}

1224
void HUD::startImage(int imgid, int width, int height, int depth, int channels)
pixhawk's avatar
pixhawk committed
1225
{
1226
    Q_UNUSED(imgid);
1227
    //qDebug() << "HUD: starting image (" << width << "x" << height << ", " << depth << "bits) with " << channels << "channels";
pixhawk's avatar
pixhawk committed
1228 1229 1230 1231 1232 1233 1234 1235 1236

    // Copy previous image to screen if it hasn't been finished properly
    finishImage();

    // Reset image size if necessary
    setImageSize(width, height, depth, channels);
    imageStarted = true;
}

1237
void HUD::finishImage()
pixhawk's avatar
pixhawk committed
1238
{
1239
    if (imageStarted) {
pixhawk's avatar
pixhawk committed
1240 1241 1242 1243 1244
        commitRawDataToGL();
        imageStarted = false;
    }
}

1245
void HUD::commitRawDataToGL()
pixhawk's avatar
pixhawk committed
1246
{
1247
    qDebug() << __FILE__ << __LINE__ << "Copying raw data to GL buffer:" << rawImage << receivedWidth << receivedHeight << image->format();
1248
    if (image != NULL) {
pixhawk's avatar
pixhawk committed
1249 1250
        QImage::Format format = image->format();
        QImage* newImage = new QImage(rawImage, receivedWidth, receivedHeight, format);
1251
        if (format == QImage::Format_Indexed8) {
pixhawk's avatar
pixhawk committed
1252 1253
            // Create matching color table
            newImage->setNumColors(256);
1254
            for (int i = 0; i < 256; i++) {
pixhawk's avatar
pixhawk committed
1255 1256 1257 1258 1259
                newImage->setColor(i, qRgb(i, i, i));
                //qDebug() << __FILE__ << __LINE__ << std::hex << i;
            }
        }

1260
        glImage = *newImage;
pixhawk's avatar
pixhawk committed
1261 1262 1263
        delete image;
        image = newImage;
        // Switch buffers
1264
        if (rawImage == rawBuffer1) {
pixhawk's avatar
pixhawk committed
1265 1266
            rawImage = rawBuffer2;
            //qDebug() << "Now buffer 2";
1267
        } else {
pixhawk's avatar
pixhawk committed
1268 1269 1270 1271
            rawImage = rawBuffer1;
            //qDebug() << "Now buffer 1";
        }
    }
1272
    update();
pixhawk's avatar
pixhawk committed
1273 1274
}

1275
void HUD::saveImage(QString fileName)
pixhawk's avatar
pixhawk committed
1276 1277 1278 1279
{
    image->save(fileName);
}

1280
void HUD::saveImage()
pixhawk's avatar
pixhawk committed
1281 1282 1283 1284 1285 1286
{
    //Bring up popup
    QString fileName = "output.png";
    saveImage(fileName);
}

1287
void HUD::startImage(quint64 timestamp)
1288
{
1289
    if (videoEnabled && offlineDirectory != "") {
1290 1291 1292 1293 1294
        // Load and diplay image file
        nextOfflineImage = QString(offlineDirectory + "/%1.bmp").arg(timestamp);
    }
}

1295
void HUD::selectOfflineDirectory()
1296 1297
{
    QString fileName = QFileDialog::getExistingDirectory(this, tr("Select image directory"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
1298
    if (fileName != "") {
1299 1300 1301 1302
        offlineDirectory = fileName;
    }
}

1303
void HUD::enableHUDInstruments(bool enabled)
1304
{
1305
    HUDInstrumentsEnabled = enabled;
1306 1307
}

1308
void HUD::enableVideo(bool enabled)
1309 1310 1311 1312
{
    videoEnabled = enabled;
}

1313
void HUD::setPixels(int imgid, const unsigned char* imageData, int length, int startIndex)
pixhawk's avatar
pixhawk committed
1314
{
1315
    Q_UNUSED(imgid);
pixhawk's avatar
pixhawk committed
1316 1317
    //    qDebug() << "at" << __FILE__ << __LINE__ << ": Received startindex" << startIndex << "and length" << length << "(" << startIndex+length << "of" << rawExpectedBytes << "bytes)";

1318 1319
    if (imageStarted)
    {
pixhawk's avatar
pixhawk committed
1320 1321
        //if (rawLastIndex != startIndex) qDebug() << "PACKET LOSS!";

1322 1323
        if (startIndex+length > rawExpectedBytes)
        {
1324
            qDebug() << "HUD: OVERFLOW! startIndex:" << startIndex << "length:" << length << "image raw size" << ((receivedWidth * receivedHeight * receivedChannels * receivedDepth) / 8) - 1;
1325 1326 1327
        }
        else
        {
pixhawk's avatar
pixhawk committed
1328 1329 1330 1331 1332
            memcpy(rawImage+startIndex, imageData, length);

            rawLastIndex = startIndex+length;

            // Check if we just reached the end of the image
1333 1334
            if (startIndex+length == rawExpectedBytes)
            {
1335
                //qDebug() << "HUD: END OF IMAGE REACHED!";
pixhawk's avatar
pixhawk committed
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
                finishImage();
                rawLastIndex = 0;
            }
        }

        //        for (int i = 0; i < length; i++)
        //        {
        //            for (int j = 0; j < receivedChannels; j++)
        //            {
        //                unsigned int x = (startIndex+i) % receivedWidth;
        //                unsigned int y = (unsigned int)((startIndex+i) / receivedWidth);
        //                qDebug() << "Setting pixel" << x << "," << y << "to" << (unsigned int)*(rawImage+startIndex+i);
        //            }
        //        }
    }
}
1352

1353
void HUD::copyImage()
1354
{
1355 1356
    UAS* u = dynamic_cast<UAS*>(this->uas);
    if (u)
lm's avatar
lm committed
1357
    {
1358
        this->glImage = u->getImage();
1359

1360 1361 1362 1363 1364
        // Save to directory if logging is enabled
        if (imageLoggingEnabled)
        {
            u->getImage().save(QString("%1/%2.png").arg(imageLogDirectory).arg(imageLogCounter));
            imageLogCounter++;
1365 1366 1367 1368
        }
    }
}

1369
void HUD::saveImages(bool save)
1370 1371 1372 1373 1374 1375
{
    if (save)
    {
        QFileDialog dialog(this);
        dialog.setFileMode(QFileDialog::DirectoryOnly);

1376
        imageLogDirectory = QFileDialog::getExistingDirectory(this, tr("Select image log directory"), QDesktopServices::storageLocation(QDesktopServices::DesktopLocation));
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390

        qDebug() << "Logging to:" << imageLogDirectory;

        if (imageLogDirectory != "")
        {
            imageLogCounter = 0;
            imageLoggingEnabled = true;
            qDebug() << "Logging on";
        }
        else
        {
            imageLoggingEnabled = false;
            selectSaveDirectoryAction->setChecked(false);
        }
lm's avatar
lm committed
1391
    }
1392 1393 1394 1395 1396 1397
    else
    {
        imageLoggingEnabled = false;
        selectSaveDirectoryAction->setChecked(false);
    }

1398
}