Pixhawk3DWidget.cc 45.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
///*=====================================================================
//
//QGroundControl Open Source Ground Control Station
//
//(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
//
//This file is part of the QGROUNDCONTROL project
//
//    QGROUNDCONTROL is free software: you can redistribute it and/or modify
//    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.
//
//    QGROUNDCONTROL is distributed in the hope that it will be useful,
//    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
//    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
//
//======================================================================*/

/**
 * @file
 *   @brief Definition of the class Pixhawk3DWidget.
 *
28
 *   @author Lionel Heng <hengli@inf.ethz.ch>
29 30 31 32 33 34 35 36
 *
 */

#include "Pixhawk3DWidget.h"

#include <sstream>

#include <osg/Geode>
37
#include <osg/Image>
38
#include <osgDB/ReadFile>
39 40 41 42 43
#include <osg/LineWidth>
#include <osg/ShapeDrawable>

#include "PixhawkCheetahGeode.h"
#include "UASManager.h"
44

45
#include "QGC.h"
46
#include "gpl.h"
47

48 49
#ifdef QGC_PROTOBUF_ENABLED
#include <tr1/memory>
LM's avatar
LM committed
50
#include <pixhawk/pixhawk.pb.h>
51 52
#endif

53
Pixhawk3DWidget::Pixhawk3DWidget(QWidget* parent)
54 55 56 57 58
    : Q3DWidget(parent)
    , uas(NULL)
    , mode(DEFAULT_MODE)
    , selectedWpIndex(-1)
    , displayGrid(true)
59
    , displayTrail(true)
60 61 62
    , displayImagery(true)
    , displayWaypoints(true)
    , displayRGBD2D(false)
63
    , displayRGBD3D(true)
64
    , displayObstacleList(true)
65
    , displayPath(true)
66
    , enableRGBDColor(false)
67 68
    , enableTarget(false)
    , followCamera(true)
69
    , frame(MAV_FRAME_LOCAL_NED)
70 71 72
    , lastRobotX(0.0f)
    , lastRobotY(0.0f)
    , lastRobotZ(0.0f)
73
{
74
    setCameraParams(2.0f, 30.0f, 0.01f, 10000.0f);
75 76 77
    init(15.0f);

    // generate Pixhawk Cheetah model
78 79
    vehicleModel = PixhawkCheetahGeode::instance();
    egocentricMap->addChild(vehicleModel);
80 81 82 83 84 85

    // generate grid model
    gridNode = createGrid();
    rollingMap->addChild(gridNode);

    // generate empty trail model
86
    trailNode = createTrail(osg::Vec4(1.0f, 0.0f, 0.0f, 1.0f));
87 88
    rollingMap->addChild(trailNode);

89 90
    // generate map model
    mapNode = createMap();
91
    rollingMap->addChild(mapNode);
92

93
    // generate waypoint model
94 95 96
    waypointGroupNode = new WaypointGroupNode;
    waypointGroupNode->init();
    rollingMap->addChild(waypointGroupNode);
97

98 99 100 101
    // generate target model
    targetNode = createTarget();
    rollingMap->addChild(targetNode);

102
    // generate RGBD model
103
    rgbd3DNode = createRGBD3D();
104 105 106 107 108 109
    rollingMap->addChild(rgbd3DNode);

#ifdef QGC_PROTOBUF_ENABLED
    obstacleGroupNode = new ObstacleGroupNode;
    obstacleGroupNode->init();
    rollingMap->addChild(obstacleGroupNode);
110 111 112 113

    // generate path model
    pathNode = createTrail(osg::Vec4(1.0f, 0.8f, 0.0f, 1.0f));
    rollingMap->addChild(pathNode);
114
#endif
115

116 117
    setupHUD();

118 119 120
    // find available vehicle models in models folder
    vehicleModels = findVehicleModels();

121 122
    buildLayout();

123
    updateHUD(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "32N");
124

125 126 127 128 129 130 131 132 133 134 135 136 137
    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)),
            this, SLOT(setActiveUAS(UASInterface*)));
}

Pixhawk3DWidget::~Pixhawk3DWidget()
{

}

/**
 *
 * @param uas the UAS/MAV to monitor/display with the HUD
 */
138 139
void
Pixhawk3DWidget::setActiveUAS(UASInterface* uas)
140
{
141 142
    if (this->uas != NULL && this->uas != uas)
    {
143 144 145 146 147 148 149
        // Disconnect any previously connected active MAV
        //disconnect(uas, SIGNAL(valueChanged(UASInterface*,QString,double,quint64)), this, SLOT(updateValue(UASInterface*,QString,double,quint64)));
    }

    this->uas = uas;
}

150 151 152
void
Pixhawk3DWidget::selectFrame(QString text)
{
153 154
    if (text.compare("Global") == 0)
    {
155
        frame = MAV_FRAME_GLOBAL;
156 157 158
    }
    else if (text.compare("Local") == 0)
    {
LM's avatar
LM committed
159
        frame = MAV_FRAME_LOCAL_NED;
160 161 162 163 164 165 166
    }

    getPosition(lastRobotX, lastRobotY, lastRobotZ);

    recenter();
}

167 168 169
void
Pixhawk3DWidget::showGrid(int32_t state)
{
170 171
    if (state == Qt::Checked)
    {
172
        displayGrid = true;
173 174 175
    }
    else
    {
176 177 178 179 180 181 182
        displayGrid = false;
    }
}

void
Pixhawk3DWidget::showTrail(int32_t state)
{
183 184 185 186
    if (state == Qt::Checked)
    {
        if (!displayTrail)
        {
187
            trail.clear();
188 189 190
        }

        displayTrail = true;
191 192 193
    }
    else
    {
194 195 196 197
        displayTrail = false;
    }
}

198 199 200
void
Pixhawk3DWidget::showWaypoints(int state)
{
201 202
    if (state == Qt::Checked)
    {
203
        displayWaypoints = true;
204 205 206
    }
    else
    {
207 208 209 210
        displayWaypoints = false;
    }
}

211 212 213 214
void
Pixhawk3DWidget::selectMapSource(int index)
{
    mapNode->setImageryType(static_cast<Imagery::ImageryType>(index));
215

216 217
    if (mapNode->getImageryType() == Imagery::BLANK_MAP)
    {
218
        displayImagery = false;
219 220 221
    }
    else
    {
222 223
        displayImagery = true;
    }
224 225
}

226 227 228
void
Pixhawk3DWidget::selectVehicleModel(int index)
{
229
    egocentricMap->removeChild(vehicleModel);
230
    vehicleModel = vehicleModels.at(index);
231
    egocentricMap->addChild(vehicleModel);
232 233
}

234
void
235
Pixhawk3DWidget::recenter(void)
236
{
237
    double robotX = 0.0f, robotY = 0.0f, robotZ = 0.0f;
238
    getPosition(robotX, robotY, robotZ);
239

240
    recenterCamera(robotY, robotX, -robotZ);
241 242 243
}

void
244
Pixhawk3DWidget::toggleFollowCamera(int32_t state)
245
{
246 247
    if (state == Qt::Checked)
    {
248
        followCamera = true;
249 250 251
    }
    else
    {
252
        followCamera = false;
253 254
    }
}
255

256
void
257
Pixhawk3DWidget::selectTargetHeading(void)
258
{
259 260 261 262
    if (!uas)
    {
        return;
    }
263

264 265
    osg::Vec2d p;

266 267 268
    if (frame == MAV_FRAME_GLOBAL)
    {
        double altitude = uas->getAltitude();
269

270 271
        std::pair<double,double> cursorWorldCoords =
            getGlobalCursorPosition(getMouseX(), getMouseY(), altitude);
272

273
        p.set(cursorWorldCoords.first, cursorWorldCoords.second);
274 275 276 277
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();
278

279 280
        std::pair<double,double> cursorWorldCoords =
            getGlobalCursorPosition(getMouseX(), getMouseY(), -z);
281

282
        p.set(cursorWorldCoords.first, cursorWorldCoords.second);
283
    }
284

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    target.z() = atan2(p.y() - target.y(), p.x() - target.x());
}

void
Pixhawk3DWidget::selectTarget(void)
{
    if (!uas)
    {
        return;
    }

    if (frame == MAV_FRAME_GLOBAL)
    {
        double altitude = uas->getAltitude();

        std::pair<double,double> cursorWorldCoords =
301 302
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(),
                                    altitude);
303 304 305 306 307 308 309 310

        target.set(cursorWorldCoords.first, cursorWorldCoords.second, 0.0);
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();

        std::pair<double,double> cursorWorldCoords =
311
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(), -z);
312 313 314

        target.set(cursorWorldCoords.first, cursorWorldCoords.second, 0.0);
    }
315 316

    enableTarget = true;
317

318
    mode = SELECT_TARGET_HEADING_MODE;
319 320 321 322 323 324 325
}

void
Pixhawk3DWidget::setTarget(void)
{
    selectTargetHeading();

326 327
    uas->setTargetPosition(target.x(), target.y(), 0.0,
                           osg::RadiansToDegrees(target.z()));
328 329
}

330 331 332
void
Pixhawk3DWidget::insertWaypoint(void)
{
333 334 335 336
    if (!uas)
    {
        return;
    }
337

338 339 340 341 342 343 344 345 346 347 348
    Waypoint* wp = NULL;
    if (frame == MAV_FRAME_GLOBAL)
    {
        double latitude = uas->getLatitude();
        double longitude = uas->getLongitude();
        double altitude = uas->getAltitude();
        double x, y;
        QString utmZone;
        Imagery::LLtoUTM(latitude, longitude, x, y, utmZone);

        std::pair<double,double> cursorWorldCoords =
349 350
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(),
                                    altitude);
351 352 353 354

        Imagery::UTMtoLL(cursorWorldCoords.first, cursorWorldCoords.second, utmZone,
                         latitude, longitude);

355
        wp = new Waypoint(0, longitude, latitude, altitude, 0.0, 0.25);
356 357 358 359 360 361
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();

        std::pair<double,double> cursorWorldCoords =
362
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(), -z);
363 364

        wp = new Waypoint(0, cursorWorldCoords.first,
365
                          cursorWorldCoords.second, z, 0.0, 0.25);
366 367 368 369 370 371
    }

    if (wp)
    {
        wp->setFrame(frame);
        uas->getWaypointManager()->addWaypointEditable(wp);
372 373
    }

374 375
    selectedWpIndex = wp->getId();
    mode = MOVE_WAYPOINT_HEADING_MODE;
376 377 378
}

void
379
Pixhawk3DWidget::moveWaypointPosition(void)
380
{
381 382 383 384 385 386
    if (mode != MOVE_WAYPOINT_POSITION_MODE)
    {
        mode = MOVE_WAYPOINT_POSITION_MODE;
        return;
    }

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    if (!uas)
    {
        return;
    }

    const QVector<Waypoint *> waypoints =
        uas->getWaypointManager()->getWaypointEditableList();
    Waypoint* waypoint = waypoints.at(selectedWpIndex);

    if (frame == MAV_FRAME_GLOBAL)
    {
        double latitude = uas->getLatitude();
        double longitude = uas->getLongitude();
        double altitude = uas->getAltitude();
        double x, y;
        QString utmZone;
        Imagery::LLtoUTM(latitude, longitude, x, y, utmZone);

        std::pair<double,double> cursorWorldCoords =
            getGlobalCursorPosition(getMouseX(), getMouseY(), altitude);

408 409
        Imagery::UTMtoLL(cursorWorldCoords.first, cursorWorldCoords.second,
                         utmZone, latitude, longitude);
410 411 412 413 414 415 416 417 418 419 420 421 422

        waypoint->setX(longitude);
        waypoint->setY(latitude);
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();

        std::pair<double,double> cursorWorldCoords =
            getGlobalCursorPosition(getMouseX(), getMouseY(), -z);

        waypoint->setX(cursorWorldCoords.first);
        waypoint->setY(cursorWorldCoords.second);
423 424 425
    }
}

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
void
Pixhawk3DWidget::moveWaypointHeading(void)
{
    if (mode != MOVE_WAYPOINT_HEADING_MODE)
    {
        mode = MOVE_WAYPOINT_HEADING_MODE;
        return;
    }

    if (!uas)
    {
        return;
    }

    const QVector<Waypoint *> waypoints =
        uas->getWaypointManager()->getWaypointEditableList();
    Waypoint* waypoint = waypoints.at(selectedWpIndex);

    double x = 0.0, y = 0.0, z = 0.0;

    if (frame == MAV_FRAME_GLOBAL)
    {
        double latitude = waypoint->getY();
        double longitude = waypoint->getX();
        z = -waypoint->getZ();
        QString utmZone;
        Imagery::LLtoUTM(latitude, longitude, x, y, utmZone);
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        z = uas->getLocalZ();
    }

    std::pair<double,double> cursorWorldCoords =
        getGlobalCursorPosition(getMouseX(), getMouseY(), -z);

    double yaw = atan2(cursorWorldCoords.second - waypoint->getY(),
                       cursorWorldCoords.first - waypoint->getX());
    yaw = osg::RadiansToDegrees(yaw);

    waypoint->setYaw(yaw);
}

469 470 471
void
Pixhawk3DWidget::deleteWaypoint(void)
{
472 473
    if (uas)
    {
474
        uas->getWaypointManager()->removeWaypoint(selectedWpIndex);
475 476 477 478 479 480
    }
}

void
Pixhawk3DWidget::setWaypointAltitude(void)
{
481 482 483 484
    if (!uas)
    {
        return;
    }
485

486 487 488 489
    bool ok;
    const QVector<Waypoint *> waypoints =
        uas->getWaypointManager()->getWaypointEditableList();
    Waypoint* waypoint = waypoints.at(selectedWpIndex);
490

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    double altitude = waypoint->getZ();
    if (frame == MAV_FRAME_LOCAL_NED)
    {
        altitude = -altitude;
    }

    double newAltitude =
        QInputDialog::getDouble(this, tr("Set altitude of waypoint %1").arg(selectedWpIndex),
                                tr("Altitude (m):"), waypoint->getZ(), -1000.0, 1000.0, 1, &ok);
    if (ok)
    {
        if (frame == MAV_FRAME_GLOBAL)
        {
            waypoint->setZ(newAltitude);
        }
        else if (frame == MAV_FRAME_LOCAL_NED)
        {
            waypoint->setZ(-newAltitude);
509
        }
510 511 512 513 514 515
    }
}

void
Pixhawk3DWidget::clearAllWaypoints(void)
{
516 517
    if (uas)
    {
518
        const QVector<Waypoint *> waypoints =
pixhawk's avatar
pixhawk committed
519
            uas->getWaypointManager()->getWaypointEditableList();
520 521
        for (int i = waypoints.size() - 1; i >= 0; --i)
        {
522
            uas->getWaypointManager()->removeWaypoint(i);
523
        }
524 525 526
    }
}

527 528 529 530
QVector< osg::ref_ptr<osg::Node> >
Pixhawk3DWidget::findVehicleModels(void)
{
    QDir directory("models");
lm's avatar
lm committed
531
    QStringList files = directory.entryList(QStringList("*.osg"), QDir::Files);
532 533 534 535

    QVector< osg::ref_ptr<osg::Node> > nodes;

    // add Pixhawk Bravo model
536
    nodes.push_back(PixhawkCheetahGeode::instance());
537

hengli's avatar
hengli committed
538 539 540
    // add sphere of 0.05m radius
    osg::ref_ptr<osg::Sphere> sphere = new osg::Sphere(osg::Vec3f(0.0f, 0.0f, 0.0f), 0.05f);
    osg::ref_ptr<osg::ShapeDrawable> sphereDrawable = new osg::ShapeDrawable(sphere);
541
    sphereDrawable->setColor(osg::Vec4f(0.5f, 0.0f, 0.5f, 1.0f));
hengli's avatar
hengli committed
542 543 544 545 546
    osg::ref_ptr<osg::Geode> sphereGeode = new osg::Geode;
    sphereGeode->addDrawable(sphereDrawable);
    sphereGeode->setName("Sphere (0.1m)");
    nodes.push_back(sphereGeode);

547
    // add all other models in folder
548 549
    for (int i = 0; i < files.size(); ++i)
    {
550
        osg::ref_ptr<osg::Node> node =
551
            osgDB::readNodeFile(directory.absoluteFilePath(files[i]).toStdString().c_str());
552

553 554
        if (node)
        {
555
            nodes.push_back(node);
556 557 558
        }
        else
        {
559
            printf("%s\n", QString("ERROR: Could not load file " + directory.absoluteFilePath(files[i]) + "\n").toStdString().c_str());
lm's avatar
lm committed
560
        }
561 562
    }

lm's avatar
lm committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
//    QStringList dirs = directory.entryList(QDir::Dirs);
//    // Add models in subfolders
//    for (int i = 0; i < dirs.size(); ++i)
//    {
//        // Handling the current directory
//        QStringList currFiles = QDir(dirs[i]).entryList(QStringList("*.ac"), QDir::Files);

//        // Load the file
//        osg::ref_ptr<osg::Node> node =
//                osgDB::readNodeFile(directory.absoluteFilePath(currFiles.first()).toStdString().c_str());

//        if (node)
//        {

//        nodes.push_back(node);
//        }
//        else
//        {
//            printf(QString("ERROR: Could not load file " + directory.absoluteFilePath(files[i]) + "\n").toStdString().c_str());
//        }
//    }

585 586 587 588 589 590
    return nodes;
}

void
Pixhawk3DWidget::buildLayout(void)
{
591 592
    QComboBox* frameComboBox = new QComboBox(this);
    frameComboBox->addItem("Local");
593
    frameComboBox->addItem("Global");
594 595
    frameComboBox->setFixedWidth(70);

596 597 598 599 600 601 602 603 604 605 606 607
    QCheckBox* gridCheckBox = new QCheckBox(this);
    gridCheckBox->setText("Grid");
    gridCheckBox->setChecked(displayGrid);

    QCheckBox* trailCheckBox = new QCheckBox(this);
    trailCheckBox->setText("Trail");
    trailCheckBox->setChecked(displayTrail);

    QCheckBox* waypointsCheckBox = new QCheckBox(this);
    waypointsCheckBox->setText("Waypoints");
    waypointsCheckBox->setChecked(displayWaypoints);

608 609 610 611 612 613
    QLabel* mapLabel = new QLabel("Map", this);
    QComboBox* mapComboBox = new QComboBox(this);
    mapComboBox->addItem("None");
    mapComboBox->addItem("Map (Google)");
    mapComboBox->addItem("Satellite (Google)");

614
    QLabel* modelLabel = new QLabel("Vehicle", this);
615
    QComboBox* modelComboBox = new QComboBox(this);
616 617
    for (int i = 0; i < vehicleModels.size(); ++i)
    {
618 619 620 621 622 623 624 625 626 627 628 629 630
        modelComboBox->addItem(vehicleModels[i]->getName().c_str());
    }

    QPushButton* recenterButton = new QPushButton(this);
    recenterButton->setText("Recenter Camera");

    QCheckBox* followCameraCheckBox = new QCheckBox(this);
    followCameraCheckBox->setText("Follow Camera");
    followCameraCheckBox->setChecked(followCamera);

    QGridLayout* layout = new QGridLayout(this);
    layout->setMargin(0);
    layout->setSpacing(2);
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    layout->addWidget(frameComboBox, 0, 10);
    layout->addWidget(gridCheckBox, 2, 0);
    layout->addWidget(trailCheckBox, 2, 1);
    layout->addWidget(waypointsCheckBox, 2, 2);
    layout->addItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 2, 3);
    layout->addWidget(mapLabel, 2, 4);
    layout->addWidget(mapComboBox, 2, 5);
    layout->addWidget(modelLabel, 2, 6);
    layout->addWidget(modelComboBox, 2, 7);
    layout->addItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 2, 8);
    layout->addWidget(recenterButton, 2, 9);
    layout->addWidget(followCameraCheckBox, 2, 10);
    layout->setRowStretch(0, 1);
    layout->setRowStretch(1, 100);
    layout->setRowStretch(2, 1);
646 647
    setLayout(layout);

648 649
    connect(frameComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(selectFrame(QString)));
650 651 652 653 654 655
    connect(gridCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showGrid(int)));
    connect(trailCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showTrail(int)));
    connect(waypointsCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showWaypoints(int)));
656 657
    connect(mapComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(selectMapSource(int)));
658 659 660 661 662 663
    connect(modelComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(selectVehicleModel(int)));
    connect(recenterButton, SIGNAL(clicked()), this, SLOT(recenter()));
    connect(followCameraCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(toggleFollowCamera(int)));
}
664

665 666 667 668 669 670 671 672
void
Pixhawk3DWidget::resizeGL(int width, int height)
{
    Q3DWidget::resizeGL(width, height);

    resizeHUD();
}

673 674 675
void
Pixhawk3DWidget::display(void)
{
676 677 678 679 680 681 682 683
    // set node visibility
    rollingMap->setChildValue(gridNode, displayGrid);
    rollingMap->setChildValue(trailNode, displayTrail);
    rollingMap->setChildValue(mapNode, displayImagery);
    rollingMap->setChildValue(waypointGroupNode, displayWaypoints);
    rollingMap->setChildValue(targetNode, enableTarget);
#ifdef QGC_PROTOBUF_ENABLED
    rollingMap->setChildValue(obstacleGroupNode, displayObstacleList);
684
    rollingMap->setChildValue(pathNode, displayPath);
685 686 687 688 689
#endif
    rollingMap->setChildValue(rgbd3DNode, displayRGBD3D);
    hudGroup->setChildValue(rgb2DGeode, displayRGBD2D);
    hudGroup->setChildValue(depth2DGeode, displayRGBD2D);

690 691
    if (!uas)
    {
692 693 694
        return;
    }

695
    double robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw;
696
    QString utmZone;
697
    getPose(robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw, utmZone);
698

699 700
    if (lastRobotX == 0.0f && lastRobotY == 0.0f && lastRobotZ == 0.0f)
    {
701 702 703 704 705
        lastRobotX = robotX;
        lastRobotY = robotY;
        lastRobotZ = robotZ;

        recenterCamera(robotY, robotX, -robotZ);
706 707
    }

708 709
    if (followCamera)
    {
710 711 712
        double dx = robotY - lastRobotY;
        double dy = robotX - lastRobotX;
        double dz = lastRobotZ - robotZ;
713 714

        moveCamera(dx, dy, dz);
715 716
    }

717 718 719 720
    robotPosition->setPosition(osg::Vec3d(robotY, robotX, -robotZ));
    robotAttitude->setAttitude(osg::Quat(-robotYaw, osg::Vec3d(0.0f, 0.0f, 1.0f),
                                         robotPitch, osg::Vec3d(1.0f, 0.0f, 0.0f),
                                         robotRoll, osg::Vec3d(0.0f, 1.0f, 0.0f)));
721

722 723
    if (displayTrail)
    {
724 725 726
        updateTrail(robotX, robotY, robotZ);
    }

727 728
    if (frame == MAV_FRAME_GLOBAL && displayImagery)
    {
729
        updateImagery(robotX, robotY, robotZ, utmZone);
730 731
    }

732 733
    if (displayWaypoints)
    {
734 735 736
        updateWaypoints();
    }

737 738
    if (enableTarget)
    {
739 740 741
        updateTarget(robotX, robotY);
    }

742
#ifdef QGC_PROTOBUF_ENABLED
743 744
    if (displayRGBD2D || displayRGBD3D)
    {
745
        updateRGBD(robotX, robotY, robotZ);
746
    }
747 748 749 750 751

    if (displayObstacleList)
    {
        updateObstacles();
    }
752 753 754 755 756

    if (displayPath)
    {
        updatePath(robotX, robotY, robotZ);
    }
757
#endif
758

759
    updateHUD(robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw, utmZone);
760

761 762 763
    lastRobotX = robotX;
    lastRobotY = robotY;
    lastRobotZ = robotZ;
LM's avatar
LM committed
764 765

    layout()->update();
766 767
}

768 769 770
void
Pixhawk3DWidget::keyPressEvent(QKeyEvent* event)
{
771 772 773 774
    if (!event->text().isEmpty())
    {
        switch (*(event->text().toAscii().data()))
        {
775 776 777
        case '1':
            displayRGBD2D = !displayRGBD2D;
            break;
778 779 780
        case '2':
            displayRGBD3D = !displayRGBD3D;
            break;
781 782
        case 'c':
        case 'C':
783 784
            enableRGBDColor = !enableRGBDColor;
            break;
785 786 787 788
        case 'o':
        case 'O':
            displayObstacleList = !displayObstacleList;
            break;
789 790 791 792
        case 'p':
        case 'P':
            displayPath = !displayPath;
            break;
793 794 795 796 797 798
        }
    }

    Q3DWidget::keyPressEvent(event);
}

799 800 801
void
Pixhawk3DWidget::mousePressEvent(QMouseEvent* event)
{
802 803
    if (event->button() == Qt::LeftButton)
    {
804
        if (mode == SELECT_TARGET_HEADING_MODE)
805
        {
806
            setTarget();
807 808
        }

809
        if (mode != DEFAULT_MODE)
810 811
        {
            mode = DEFAULT_MODE;
812 813
        }

814 815
        if (event->modifiers() == Qt::ShiftModifier)
        {
816
            selectedWpIndex = findWaypoint(event->pos());
817 818
            if (selectedWpIndex == -1)
            {
819 820
                cachedMousePos = event->pos();

821
                showInsertWaypointMenu(event->globalPos());
822 823 824
            }
            else
            {
825 826 827 828 829
                showEditWaypointMenu(event->globalPos());
            }

            return;
        }
830 831 832 833 834
    }

    Q3DWidget::mousePressEvent(event);
}

835 836 837 838 839 840 841 842 843 844 845 846 847 848
void
Pixhawk3DWidget::showEvent(QShowEvent* event)
{
    Q3DWidget::showEvent(event);
    emit visibilityChanged(true);
}

void
Pixhawk3DWidget::hideEvent(QHideEvent* event)
{
    Q3DWidget::hideEvent(event);
    emit visibilityChanged(false);
}

849 850 851
void
Pixhawk3DWidget::mouseMoveEvent(QMouseEvent* event)
{
852
    if (mode == SELECT_TARGET_HEADING_MODE)
853 854 855
    {
        selectTargetHeading();
    }
856 857 858 859 860 861 862 863
    if (mode == MOVE_WAYPOINT_POSITION_MODE)
    {
        moveWaypointPosition();
    }
    if (mode == MOVE_WAYPOINT_HEADING_MODE)
    {
        moveWaypointHeading();
    }
864 865 866 867

    Q3DWidget::mouseMoveEvent(event);
}

868 869 870 871 872
void
Pixhawk3DWidget::getPose(double& x, double& y, double& z,
                         double& roll, double& pitch, double& yaw,
                         QString& utmZone)
{
873 874 875 876
    if (!uas)
    {
        return;
    }
877

878 879 880 881 882 883 884 885
    if (frame == MAV_FRAME_GLOBAL)
    {
        double latitude = uas->getLatitude();
        double longitude = uas->getLongitude();
        double altitude = uas->getAltitude();

        Imagery::LLtoUTM(latitude, longitude, x, y, utmZone);
        z = -altitude;
886
    }
887 888 889 890 891
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        x = uas->getLocalX();
        y = uas->getLocalY();
        z = uas->getLocalZ();
892
    }
893 894 895 896

    roll = uas->getRoll();
    pitch = uas->getPitch();
    yaw = uas->getYaw();
897 898 899 900 901 902 903 904 905 906 907 908 909 910
}

void
Pixhawk3DWidget::getPose(double& x, double& y, double& z,
                         double& roll, double& pitch, double& yaw)
{
    QString utmZone;
    getPose(x, y, z, roll, pitch, yaw);
}

void
Pixhawk3DWidget::getPosition(double& x, double& y, double& z,
                             QString& utmZone)
{
911
    if (!uas)
Lorenz Meier's avatar
Lorenz Meier committed
912
    {
913 914
        return;
    }
915

916 917 918 919 920 921 922 923 924 925 926 927 928 929
    if (frame == MAV_FRAME_GLOBAL)
    {
        double latitude = uas->getLatitude();
        double longitude = uas->getLongitude();
        double altitude = uas->getAltitude();

        Imagery::LLtoUTM(latitude, longitude, x, y, utmZone);
        z = -altitude;
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        x = uas->getLocalX();
        y = uas->getLocalY();
        z = uas->getLocalZ();
930 931 932 933 934 935 936 937 938 939
    }
}

void
Pixhawk3DWidget::getPosition(double& x, double& y, double& z)
{
    QString utmZone;
    getPosition(x, y, z, utmZone);
}

940 941 942 943
osg::ref_ptr<osg::Geode>
Pixhawk3DWidget::createGrid(void)
{
    osg::ref_ptr<osg::Geode> geode(new osg::Geode());
944 945 946 947
    osg::ref_ptr<osg::Geometry> fineGeometry(new osg::Geometry());
    osg::ref_ptr<osg::Geometry> coarseGeometry(new osg::Geometry());
    geode->addDrawable(fineGeometry);
    geode->addDrawable(coarseGeometry);
948 949 950 951

    float radius = 10.0f;
    float resolution = 0.25f;

952 953
    osg::ref_ptr<osg::Vec3Array> fineCoords(new osg::Vec3Array);
    osg::ref_ptr<osg::Vec3Array> coarseCoords(new osg::Vec3Array);
954 955

    // draw a 20m x 20m grid with 0.25m resolution
956 957 958 959
    for (float i = -radius; i <= radius; i += resolution)
    {
        if (fabs(i - floor(i + 0.5f)) < 0.01f)
        {
960 961 962 963
            coarseCoords->push_back(osg::Vec3(i, -radius, 0.0f));
            coarseCoords->push_back(osg::Vec3(i, radius, 0.0f));
            coarseCoords->push_back(osg::Vec3(-radius, i, 0.0f));
            coarseCoords->push_back(osg::Vec3(radius, i, 0.0f));
964 965 966
        }
        else
        {
967 968 969 970 971
            fineCoords->push_back(osg::Vec3(i, -radius, 0.0f));
            fineCoords->push_back(osg::Vec3(i, radius, 0.0f));
            fineCoords->push_back(osg::Vec3(-radius, i, 0.0f));
            fineCoords->push_back(osg::Vec3(radius, i, 0.0f));
        }
972 973
    }

974 975
    fineGeometry->setVertexArray(fineCoords);
    coarseGeometry->setVertexArray(coarseCoords);
976 977 978

    osg::ref_ptr<osg::Vec4Array> color(new osg::Vec4Array);
    color->push_back(osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f));
979 980 981 982 983 984
    fineGeometry->setColorArray(color);
    coarseGeometry->setColorArray(color);
    fineGeometry->setColorBinding(osg::Geometry::BIND_OVERALL);
    coarseGeometry->setColorBinding(osg::Geometry::BIND_OVERALL);

    fineGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,
985
                                  0, fineCoords->size()));
986
    coarseGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0,
987
                                    coarseCoords->size()));
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

    osg::ref_ptr<osg::StateSet> fineStateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> fineLinewidth(new osg::LineWidth());
    fineLinewidth->setWidth(0.25f);
    fineStateset->setAttributeAndModes(fineLinewidth, osg::StateAttribute::ON);
    fineStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    fineGeometry->setStateSet(fineStateset);

    osg::ref_ptr<osg::StateSet> coarseStateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> coarseLinewidth(new osg::LineWidth());
    coarseLinewidth->setWidth(2.0f);
    coarseStateset->setAttributeAndModes(coarseLinewidth, osg::StateAttribute::ON);
    coarseStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    coarseGeometry->setStateSet(coarseStateset);
1002 1003 1004 1005 1006

    return geode;
}

osg::ref_ptr<osg::Geode>
1007
Pixhawk3DWidget::createTrail(const osg::Vec4& color)
1008 1009
{
    osg::ref_ptr<osg::Geode> geode(new osg::Geode());
1010 1011 1012
    osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry());
    geometry->setUseDisplayList(false);
    geode->addDrawable(geometry.get());
1013

1014 1015
    osg::ref_ptr<osg::Vec3dArray> vertices(new osg::Vec3dArray());
    geometry->setVertexArray(vertices);
1016

1017 1018
    osg::ref_ptr<osg::DrawArrays> drawArrays(new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP));
    geometry->addPrimitiveSet(drawArrays);
1019

1020 1021 1022 1023
    osg::ref_ptr<osg::Vec4Array> colorArray(new osg::Vec4Array);
    colorArray->push_back(color);
    geometry->setColorArray(colorArray);
    geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
1024 1025 1026 1027 1028 1029

    osg::ref_ptr<osg::StateSet> stateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> linewidth(new osg::LineWidth());
    linewidth->setWidth(1.0f);
    stateset->setAttributeAndModes(linewidth, osg::StateAttribute::ON);
    stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1030
    geometry->setStateSet(stateset);
1031 1032 1033 1034

    return geode;
}

1035
osg::ref_ptr<Imagery>
1036 1037
Pixhawk3DWidget::createMap(void)
{
1038
    return osg::ref_ptr<Imagery>(new Imagery());
1039 1040
}

1041
osg::ref_ptr<osg::Geode>
1042
Pixhawk3DWidget::createRGBD3D(void)
1043
{
1044
    int frameSize = 752 * 480;
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

    osg::ref_ptr<osg::Geode> geode(new osg::Geode);
    osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry);

    osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array(frameSize));
    geometry->setVertexArray(vertices);

    osg::ref_ptr<osg::Vec4Array> colors(new osg::Vec4Array(frameSize));
    geometry->setColorArray(colors);
    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
    geometry->setUseDisplayList(false);

    geode->addDrawable(geometry);

    return geode;
1060 1061
}

1062 1063 1064 1065
osg::ref_ptr<osg::Node>
Pixhawk3DWidget::createTarget(void)
{
    osg::ref_ptr<osg::PositionAttitudeTransform> pat =
1066
        new osg::PositionAttitudeTransform;
1067 1068 1069

    pat->setPosition(osg::Vec3d(0.0, 0.0, 0.0));

1070
    osg::ref_ptr<osg::Cone> cone = new osg::Cone(osg::Vec3f(0.0f, 0.0f, 0.0f), 0.2f, 0.6f);
1071 1072 1073 1074 1075 1076
    osg::ref_ptr<osg::ShapeDrawable> coneDrawable = new osg::ShapeDrawable(cone);
    coneDrawable->setColor(osg::Vec4f(0.0f, 1.0f, 0.0f, 1.0f));
    coneDrawable->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
    osg::ref_ptr<osg::Geode> coneGeode = new osg::Geode;
    coneGeode->addDrawable(coneDrawable);
    coneGeode->setName("Target");
1077

1078
    pat->addChild(coneGeode);
1079 1080 1081 1082

    return pat;
}

1083 1084 1085 1086
void
Pixhawk3DWidget::setupHUD(void)
{
    osg::ref_ptr<osg::Vec4Array> hudColors(new osg::Vec4Array);
1087 1088
    hudColors->push_back(osg::Vec4(0.0f, 0.0f, 0.0f, 0.5f));
    hudColors->push_back(osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
1089 1090

    hudBackgroundGeometry = new osg::Geometry;
1091
    hudBackgroundGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON,
1092
                                           0, 4));
1093
    hudBackgroundGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON,
1094
                                           4, 4));
1095
    hudBackgroundGeometry->setColorArray(hudColors);
1096
    hudBackgroundGeometry->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
1097
    hudBackgroundGeometry->setUseDisplayList(false);
1098 1099 1100

    statusText = new osgText::Text;
    statusText->setCharacterSize(11);
1101
    statusText->setFont(font);
1102 1103 1104
    statusText->setAxisAlignment(osgText::Text::SCREEN);
    statusText->setColor(osg::Vec4(255, 255, 255, 1));

1105 1106 1107 1108 1109 1110
    osg::ref_ptr<osg::Geode> statusGeode = new osg::Geode;
    statusGeode->addDrawable(hudBackgroundGeometry);
    statusGeode->addDrawable(statusText);
    hudGroup->addChild(statusGeode);

    rgbImage = new osg::Image;
1111 1112 1113
    rgb2DGeode = new ImageWindowGeode;
    rgb2DGeode->init("RGB Image", osg::Vec4(0.0f, 0.0f, 0.1f, 1.0f),
                     rgbImage, font);
1114 1115 1116
    hudGroup->addChild(rgb2DGeode);

    depthImage = new osg::Image;
1117 1118 1119
    depth2DGeode = new ImageWindowGeode;
    depth2DGeode->init("Depth Image", osg::Vec4(0.0f, 0.0f, 0.1f, 1.0f),
                       depthImage, font);
1120
    hudGroup->addChild(depth2DGeode);
1121 1122

    scaleGeode = new HUDScaleGeode;
1123
    scaleGeode->init(font);
1124
    hudGroup->addChild(scaleGeode);
1125 1126 1127
}

void
1128
Pixhawk3DWidget::resizeHUD(void)
1129
{
1130
    int topHUDHeight = 25;
1131 1132 1133
    int bottomHUDHeight = 25;

    osg::Vec3Array* vertices = static_cast<osg::Vec3Array*>(hudBackgroundGeometry->getVertexArray());
Lorenz Meier's avatar
Lorenz Meier committed
1134 1135
    if (vertices == NULL || vertices->size() != 8)
    {
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
        osg::ref_ptr<osg::Vec3Array> newVertices = new osg::Vec3Array(8);
        hudBackgroundGeometry->setVertexArray(newVertices);

        vertices = static_cast<osg::Vec3Array*>(hudBackgroundGeometry->getVertexArray());
    }

    (*vertices)[0] = osg::Vec3(0, height(), -1);
    (*vertices)[1] = osg::Vec3(width(), height(), -1);
    (*vertices)[2] = osg::Vec3(width(), height() - topHUDHeight, -1);
    (*vertices)[3] = osg::Vec3(0, height() - topHUDHeight, -1);
    (*vertices)[4] = osg::Vec3(0, 0, -1);
    (*vertices)[5] = osg::Vec3(width(), 0, -1);
    (*vertices)[6] = osg::Vec3(width(), bottomHUDHeight, -1);
    (*vertices)[7] = osg::Vec3(0, bottomHUDHeight, -1);
1150

1151
    statusText->setPosition(osg::Vec3(10, height() - 15, -1.5));
1152

Lorenz Meier's avatar
Lorenz Meier committed
1153 1154
    if (rgb2DGeode.valid() && depth2DGeode.valid())
    {
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
        int windowWidth = (width() - 20) / 2;
        int windowHeight = 3 * windowWidth / 4;
        rgb2DGeode->setAttributes(10, (height() - windowHeight) / 2,
                                  windowWidth, windowHeight);
        depth2DGeode->setAttributes(width() / 2, (height() - windowHeight) / 2,
                                    windowWidth, windowHeight);
    }
}

void
1165
Pixhawk3DWidget::updateHUD(double robotX, double robotY, double robotZ,
1166 1167
                           double robotRoll, double robotPitch, double robotYaw,
                           const QString& utmZone)
1168
{
1169
    std::pair<double,double> cursorPosition =
1170
        getGlobalCursorPosition(getMouseX(), getMouseY(), -robotZ);
1171 1172 1173 1174

    std::ostringstream oss;
    oss.setf(std::ios::fixed, std::ios::floatfield);
    oss.precision(2);
Lorenz Meier's avatar
Lorenz Meier committed
1175 1176
    if (frame == MAV_FRAME_GLOBAL)
    {
1177 1178 1179 1180 1181 1182 1183 1184 1185
        double latitude, longitude;
        Imagery::UTMtoLL(robotX, robotY, utmZone, latitude, longitude);

        double cursorLatitude, cursorLongitude;
        Imagery::UTMtoLL(cursorPosition.first, cursorPosition.second,
                         utmZone, cursorLatitude, cursorLongitude);

        oss.precision(6);
        oss << " Lat = " << latitude <<
1186
            " Lon = " << longitude;
1187 1188 1189

        oss.precision(2);
        oss << " Altitude = " << -robotZ <<
1190 1191 1192
            " r = " << robotRoll <<
            " p = " << robotPitch <<
            " y = " << robotYaw;
1193 1194 1195

        oss.precision(6);
        oss << " Cursor [" << cursorLatitude <<
1196
            " " << cursorLongitude << "]";
Lorenz Meier's avatar
Lorenz Meier committed
1197 1198 1199
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
1200
        oss << " x = " << robotX <<
1201 1202 1203 1204 1205 1206 1207
            " y = " << robotY <<
            " z = " << robotZ <<
            " r = " << robotRoll <<
            " p = " << robotPitch <<
            " y = " << robotYaw <<
            " Cursor [" << cursorPosition.first <<
            " " << cursorPosition.second << "]";
1208 1209
    }

1210
    statusText->setText(oss.str());
1211

1212
    bool darkBackground = true;
Lorenz Meier's avatar
Lorenz Meier committed
1213 1214
    if (mapNode->getImageryType() == Imagery::GOOGLE_MAP)
    {
1215 1216 1217 1218 1219
        darkBackground = false;
    }

    scaleGeode->update(height(), cameraParams.cameraFov,
                       cameraManipulator->getDistance(), darkBackground);
1220 1221 1222
}

void
1223
Pixhawk3DWidget::updateTrail(double robotX, double robotY, double robotZ)
1224
{
Lorenz Meier's avatar
Lorenz Meier committed
1225 1226
    if (robotX == 0.0f || robotY == 0.0f || robotZ == 0.0f)
    {
1227 1228 1229 1230
        return;
    }

    bool addToTrail = false;
Lorenz Meier's avatar
Lorenz Meier committed
1231 1232
    if (trail.size() > 0)
    {
1233
        if (fabs(robotX - trail[trail.size() - 1].x()) > 0.01f ||
1234
                fabs(robotY - trail[trail.size() - 1].y()) > 0.01f ||
Lorenz Meier's avatar
Lorenz Meier committed
1235 1236
                fabs(robotZ - trail[trail.size() - 1].z()) > 0.01f)
        {
1237 1238
            addToTrail = true;
        }
Lorenz Meier's avatar
Lorenz Meier committed
1239 1240 1241
    }
    else
    {
1242 1243 1244
        addToTrail = true;
    }

Lorenz Meier's avatar
Lorenz Meier committed
1245 1246
    if (addToTrail)
    {
1247
        osg::Vec3d p(robotX, robotY, robotZ);
Lorenz Meier's avatar
Lorenz Meier committed
1248 1249
        if (trail.size() == trail.capacity())
        {
1250
            memcpy(trail.data(), trail.data() + 1,
1251
                   (trail.size() - 1) * sizeof(osg::Vec3d));
1252
            trail[trail.size() - 1] = p;
Lorenz Meier's avatar
Lorenz Meier committed
1253 1254 1255
        }
        else
        {
1256 1257 1258 1259
            trail.append(p);
        }
    }

1260
    osg::Geometry* geometry = trailNode->getDrawable(0)->asGeometry();
1261
    osg::DrawArrays* drawArrays = reinterpret_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));
1262 1263

    osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array);
Lorenz Meier's avatar
Lorenz Meier committed
1264 1265
    for (int i = 0; i < trail.size(); ++i)
    {
1266 1267 1268
        vertices->push_back(osg::Vec3d(trail[i].y() - robotY,
                                       trail[i].x() - robotX,
                                       -(trail[i].z() - robotZ)));
1269 1270
    }

1271
    geometry->setVertexArray(vertices);
1272 1273 1274
    drawArrays->setFirst(0);
    drawArrays->setCount(vertices->size());
    geometry->dirtyBound();
1275 1276
}

1277
void
1278
Pixhawk3DWidget::updateImagery(double originX, double originY, double originZ,
1279
                               const QString& zone)
1280
{
Lorenz Meier's avatar
Lorenz Meier committed
1281 1282
    if (mapNode->getImageryType() == Imagery::BLANK_MAP)
    {
1283 1284 1285
        return;
    }

1286
    double viewingRadius = cameraManipulator->getDistance() * 10.0;
Lorenz Meier's avatar
Lorenz Meier committed
1287 1288
    if (viewingRadius < 100.0)
    {
1289 1290 1291 1292
        viewingRadius = 100.0;
    }

    double minResolution = 0.25;
1293
    double centerResolution = cameraManipulator->getDistance() / 50.0;
1294 1295 1296
    double maxResolution = 1048576.0;

    Imagery::ImageryType imageryType = mapNode->getImageryType();
Lorenz Meier's avatar
Lorenz Meier committed
1297 1298
    switch (imageryType)
    {
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    case Imagery::GOOGLE_MAP:
        minResolution = 0.25;
        break;
    case Imagery::GOOGLE_SATELLITE:
        minResolution = 0.5;
        break;
    case Imagery::SWISSTOPO_SATELLITE:
        minResolution = 0.25;
        maxResolution = 0.25;
        break;
1309
    default:
1310
        {}
1311 1312 1313
    }

    double resolution = minResolution;
Lorenz Meier's avatar
Lorenz Meier committed
1314 1315
    while (resolution * 2.0 < centerResolution)
    {
1316 1317
        resolution *= 2.0;
    }
Lorenz Meier's avatar
Lorenz Meier committed
1318 1319 1320

    if (resolution > maxResolution)
    {
1321 1322 1323 1324 1325 1326 1327
        resolution = maxResolution;
    }

    mapNode->draw3D(viewingRadius,
                    resolution,
                    cameraManipulator->getCenter().y(),
                    cameraManipulator->getCenter().x(),
1328 1329
                    originX,
                    originY,
1330
                    originZ,
1331 1332 1333
                    zone);

    // prefetch map tiles
Lorenz Meier's avatar
Lorenz Meier committed
1334 1335
    if (resolution / 2.0 >= minResolution)
    {
1336 1337 1338 1339 1340 1341
        mapNode->prefetch3D(viewingRadius / 2.0,
                            resolution / 2.0,
                            cameraManipulator->getCenter().y(),
                            cameraManipulator->getCenter().x(),
                            zone);
    }
Lorenz Meier's avatar
Lorenz Meier committed
1342 1343
    if (resolution * 2.0 <= maxResolution)
    {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        mapNode->prefetch3D(viewingRadius * 2.0,
                            resolution * 2.0,
                            cameraManipulator->getCenter().y(),
                            cameraManipulator->getCenter().x(),
                            zone);
    }

    mapNode->update();
}

1354 1355 1356
void
Pixhawk3DWidget::updateWaypoints(void)
{
1357
    waypointGroupNode->update(frame, uas);
1358
}
1359

1360 1361 1362 1363
void
Pixhawk3DWidget::updateTarget(double robotX, double robotY)
{
    osg::PositionAttitudeTransform* pat =
1364 1365
        dynamic_cast<osg::PositionAttitudeTransform*>(targetNode.get());

1366
    pat->setPosition(osg::Vec3d(target.y() - robotY, target.x() - robotX, 0.0));
1367 1368 1369 1370 1371 1372
    pat->setAttitude(osg::Quat(target.z() - M_PI_2, osg::Vec3d(1.0f, 0.0f, 0.0f),
                               M_PI_2, osg::Vec3d(0.0f, 1.0f, 0.0f),
                               0.0, osg::Vec3d(0.0f, 0.0f, 1.0f)));

    osg::Geode* geode = dynamic_cast<osg::Geode*>(pat->getChild(0));
    osg::ShapeDrawable* sd = dynamic_cast<osg::ShapeDrawable*>(geode->getDrawable(0));
1373 1374 1375


    sd->setColor(osg::Vec4f(1.0f, 0.8f, 0.0f, 1.0f));
1376 1377
}

1378
#ifdef QGC_PROTOBUF_ENABLED
1379
void
1380
Pixhawk3DWidget::updateRGBD(double robotX, double robotY, double robotZ)
1381
{
1382
    px::RGBDImage rgbdImage = uas->getRGBDImage();
1383 1384
    px::PointCloudXYZRGB pointCloud = uas->getPointCloud();

1385
    if (rgbdImage.rows() > 0 && rgbdImage.cols() > 0)
1386
    {
1387 1388 1389 1390 1391 1392 1393 1394
        rgbImage->setImage(rgbdImage.cols(), rgbdImage.rows(), 1,
                           GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE,
                           reinterpret_cast<unsigned char *>(&(*(rgbdImage.mutable_imagedata1()))[0]),
                           osg::Image::NO_DELETE);
        rgbImage->dirty();

        QByteArray coloredDepth(rgbdImage.cols() * rgbdImage.rows() * 3, 0);
        for (uint32_t r = 0; r < rgbdImage.rows(); ++r)
1395
        {
1396 1397 1398
            const float* depth = reinterpret_cast<const float*>(rgbdImage.imagedata2().c_str() + r * rgbdImage.step2());
            uint8_t* pixel = reinterpret_cast<uint8_t*>(coloredDepth.data()) + r * rgbdImage.cols() * 3;
            for (uint32_t c = 0; c < rgbdImage.cols(); ++c)
1399
            {
1400 1401
                if (depth[c] != 0)
                {
pixhawk's avatar
pixhawk committed
1402
                    int idx = fminf(depth[c], 7.0f) / 7.0f * 127.0f;
1403
                    idx = 127 - idx;
1404

1405 1406 1407 1408 1409
                    float r, g, b;
                    qgc::colormap("jet", idx, r, g, b);
                    pixel[0] = r * 255.0f;
                    pixel[1] = g * 255.0f;
                    pixel[2] = b * 255.0f;
1410
                }
1411

1412 1413
                pixel += 3;
            }
1414 1415
        }

1416 1417 1418 1419 1420 1421
        depthImage->setImage(rgbdImage.cols(), rgbdImage.rows(), 1,
                             GL_RGB, GL_RGB, GL_UNSIGNED_BYTE,
                             reinterpret_cast<unsigned char *>(coloredDepth.data()),
                             osg::Image::NO_DELETE);
        depthImage->dirty();
    }
1422 1423 1424 1425 1426

    osg::Geometry* geometry = rgbd3DNode->getDrawable(0)->asGeometry();

    osg::Vec3Array* vertices = static_cast<osg::Vec3Array*>(geometry->getVertexArray());
    osg::Vec4Array* colors = static_cast<osg::Vec4Array*>(geometry->getColorArray());
1427 1428
    for (int i = 0; i < pointCloud.points_size(); ++i)
    {
1429 1430 1431 1432 1433 1434
        const px::PointCloudXYZRGB_PointXYZRGB& p = pointCloud.points(i);

        double x = p.x() - robotX;
        double y = p.y() - robotY;
        double z = p.z() - robotZ;

1435

1436
        (*vertices)[i].set(y, x, -z);
1437

1438 1439
        if (enableRGBDColor)
        {
1440 1441 1442 1443 1444 1445 1446
            float rgb = p.rgb();

            float b = *(reinterpret_cast<unsigned char*>(&rgb)) / 255.0f;
            float g = *(1 + reinterpret_cast<unsigned char*>(&rgb)) / 255.0f;
            float r = *(2 + reinterpret_cast<unsigned char*>(&rgb)) / 255.0f;

            (*colors)[i].set(r, g, b, 1.0f);
1447 1448 1449
        }
        else
        {
1450 1451
            double dist = sqrt(x * x + y * y + z * z);
            int colorIndex = static_cast<int>(fmin(dist / 7.0 * 127.0, 127.0));
1452 1453 1454 1455 1456

            float r, g, b;
            qgc::colormap("jet", colorIndex, r, g, b);

            (*colors)[i].set(r, g, b, 1.0f);
1457
        }
1458 1459
    }

1460 1461
    if (geometry->getNumPrimitiveSets() == 0)
    {
1462
        geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS,
1463
                                  0, pointCloud.points_size()));
1464 1465 1466
    }
    else
    {
1467
        osg::DrawArrays* drawarrays = static_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));
1468
        drawarrays->setCount(pointCloud.points_size());
1469
    }
1470
}
1471 1472 1473 1474 1475 1476 1477

void
Pixhawk3DWidget::updateObstacles(void)
{
    obstacleGroupNode->update(frame, uas);
}

1478 1479 1480 1481 1482
void
Pixhawk3DWidget::updatePath(double robotX, double robotY, double robotZ)
{
    px::Path path = uas->getPath();

1483
    osg::Geometry* geometry = pathNode->getDrawable(0)->asGeometry();
1484
    osg::DrawArrays* drawArrays = reinterpret_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    osg::Vec4Array* colorArray = reinterpret_cast<osg::Vec4Array*>(geometry->getColorArray());

    geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
    osg::ref_ptr<osg::LineWidth> linewidth(new osg::LineWidth());
    linewidth->setWidth(2.0f);
    geometry->getStateSet()->setAttributeAndModes(linewidth, osg::StateAttribute::ON);

    colorArray->clear();

    osg::ref_ptr<osg::Vec3Array> vertices(new osg::Vec3Array);

    // find path length
    float length = 0.0f;
    for (int i = 0; i < path.waypoints_size() - 1; ++i)
    {
        const px::Waypoint& wp0 = path.waypoints(i);
        const px::Waypoint& wp1 = path.waypoints(i+1);

        length += qgc::hypot3f(wp0.x() - wp1.x(),
                               wp0.y() - wp1.y(),
                               wp0.z() - wp1.z());
    }

    // build path
    if (path.waypoints_size() > 0)
    {
        const px::Waypoint& wp0 = path.waypoints(0);

        vertices->push_back(osg::Vec3d(wp0.y() - robotY,
                                       wp0.x() - robotX,
                                       -(wp0.z() - robotZ)));

        float r, g, b;
        qgc::colormap("autumn", 0, r, g, b);
        colorArray->push_back(osg::Vec4d(r, g, b, 1.0f));
    }

    float lengthCurrent = 0.0f;
    for (int i = 0; i < path.waypoints_size() - 1; ++i)
1524
    {
1525 1526
        const px::Waypoint& wp0 = path.waypoints(i);
        const px::Waypoint& wp1 = path.waypoints(i+1);
1527

1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
        lengthCurrent += qgc::hypot3f(wp0.x() - wp1.x(),
                                      wp0.y() - wp1.y(),
                                      wp0.z() - wp1.z());

        vertices->push_back(osg::Vec3d(wp1.y() - robotY,
                                       wp1.x() - robotX,
                                       -(wp1.z() - robotZ)));

        int colorIdx = lengthCurrent / length * 127.0f;

        float r, g, b;
        qgc::colormap("autumn", colorIdx, r, g, b);
        colorArray->push_back(osg::Vec4f(r, g, b, 1.0f));
1541 1542
    }

1543
    geometry->setVertexArray(vertices);
1544 1545 1546 1547 1548
    drawArrays->setFirst(0);
    drawArrays->setCount(vertices->size());
    geometry->dirtyBound();
}

1549
#endif
1550

1551
int
1552
Pixhawk3DWidget::findWaypoint(const QPoint& mousePos)
1553
{
1554 1555
    if (getSceneData())
    {
1556 1557
        osgUtil::LineSegmentIntersector::Intersections intersections;

1558 1559
        if (computeIntersections(mousePos.x(), height() - mousePos.y(),
                                 intersections))
1560
        {
1561
            for (osgUtil::LineSegmentIntersector::Intersections::iterator
1562 1563 1564 1565
                    it = intersections.begin(); it != intersections.end(); it++)
            {
                for (uint i = 0 ; i < it->nodePath.size(); ++i)
                {
1566
                    std::string nodeName = it->nodePath[i]->getName();
1567 1568
                    if (nodeName.substr(0, 2).compare("wp") == 0)
                    {
1569
                        return atoi(nodeName.substr(2).c_str());
1570 1571 1572 1573 1574 1575 1576 1577 1578
                    }
                }
            }
        }
    }

    return -1;
}

1579 1580 1581
bool
Pixhawk3DWidget::findTarget(int mouseX, int mouseY)
{
1582 1583
    if (getSceneData())
    {
1584 1585
        osgUtil::LineSegmentIntersector::Intersections intersections;

1586 1587
        if (computeIntersections(mouseX, height() - mouseY, intersections))
        {
1588
            for (osgUtil::LineSegmentIntersector::Intersections::iterator
1589 1590 1591 1592
                    it = intersections.begin(); it != intersections.end(); it++)
            {
                for (uint i = 0 ; i < it->nodePath.size(); ++i)
                {
1593
                    std::string nodeName = it->nodePath[i]->getName();
1594 1595
                    if (nodeName.compare("Target") == 0)
                    {
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

1606 1607 1608 1609 1610 1611
void
Pixhawk3DWidget::showInsertWaypointMenu(const QPoint &cursorPos)
{
    QMenu menu;
    menu.addAction("Insert new waypoint", this, SLOT(insertWaypoint()));
    menu.addAction("Clear all waypoints", this, SLOT(clearAllWaypoints()));
1612
    menu.addAction("Select target", this, SLOT(selectTarget()));
1613 1614 1615 1616 1617 1618 1619 1620 1621
    menu.exec(cursorPos);
}

void
Pixhawk3DWidget::showEditWaypointMenu(const QPoint &cursorPos)
{
    QMenu menu;

    QString text;
1622
    text = QString("Move waypoint %1").arg(QString::number(selectedWpIndex));
1623 1624 1625 1626
    menu.addAction(text, this, SLOT(moveWaypointPosition()));

    text = QString("Change heading of waypoint %1").arg(QString::number(selectedWpIndex));
    menu.addAction(text, this, SLOT(moveWaypointHeading()));
1627

1628
    text = QString("Change altitude of waypoint %1").arg(QString::number(selectedWpIndex));
1629 1630
    menu.addAction(text, this, SLOT(setWaypointAltitude()));

1631
    text = QString("Delete waypoint %1").arg(QString::number(selectedWpIndex));
1632 1633 1634 1635 1636
    menu.addAction(text, this, SLOT(deleteWaypoint()));

    menu.addAction("Clear all waypoints", this, SLOT(clearAllWaypoints()));
    menu.exec(cursorPos);
}