Pixhawk3DWidget.cc 57.4 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
#if defined(QGC_PROTOBUF_ENABLED) && defined(QGC_USE_PIXHAWK_MESSAGES)
49
#include <tr1/memory>
LM's avatar
LM committed
50
#include <pixhawk/pixhawk.pb.h>
51 52
#endif

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

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

83 84 85 86 87 88
    // generate grid models
    localGridNode = createLocalGrid();
    rollingMap->addChild(localGridNode);

    worldGridNode = createWorldGrid();
    allocentricMap->addChild(worldGridNode);
89 90

    // generate empty trail model
91
    trailNode = new osg::Geode;
92 93
    rollingMap->addChild(trailNode);

94 95 96
    orientationNode = new osg::Group;
    rollingMap->addChild(orientationNode);

97 98
    // generate map model
    mapNode = createMap();
99
    rollingMap->addChild(mapNode);
100

101
    // generate waypoint model
102 103 104
    waypointGroupNode = new WaypointGroupNode;
    waypointGroupNode->init();
    rollingMap->addChild(waypointGroupNode);
105

106 107 108 109
    // generate target model
    targetNode = createTarget();
    rollingMap->addChild(targetNode);

110
    // generate RGBD model
111
    rgbd3DNode = createRGBD3D();
112 113
    rollingMap->addChild(rgbd3DNode);

114
#if defined(QGC_PROTOBUF_ENABLED) && defined(QGC_USE_PIXHAWK_MESSAGES)
115 116 117
    obstacleGroupNode = new ObstacleGroupNode;
    obstacleGroupNode->init();
    rollingMap->addChild(obstacleGroupNode);
118 119

    // generate path model
120 121
    pathNode = new osg::Geode;
    pathNode->addDrawable(createTrail(osg::Vec4(1.0f, 0.8f, 0.0f, 1.0f)));
122
    rollingMap->addChild(pathNode);
123
#endif
124

125 126
    setupHUD();

127 128 129
    // find available vehicle models in models folder
    vehicleModels = findVehicleModels();

130 131
    buildLayout();

132
    updateHUD(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "32N");
133

134 135 136 137 138 139 140 141 142 143 144 145 146
    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)),
            this, SLOT(setActiveUAS(UASInterface*)));
}

Pixhawk3DWidget::~Pixhawk3DWidget()
{

}

/**
 *
 * @param uas the UAS/MAV to monitor/display with the HUD
 */
147 148
void
Pixhawk3DWidget::setActiveUAS(UASInterface* uas)
149
{
150 151 152 153 154 155
    if (this->uas == uas)
    {
        return;
    }

    if (this->uas != NULL)
156
    {
157
        // Disconnect any previously connected active MAV
158
        disconnect(this->uas, SIGNAL(localPositionChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(addToTrails(UASInterface*,int,double,double,double,quint64)));
159
        disconnect(this->uas, SIGNAL(attitudeChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,int,double,double,double,quint64)));
160 161
    }

162
    connect(uas, SIGNAL(localPositionChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(addToTrails(UASInterface*,int,double,double,double,quint64)));
163 164
    connect(uas, SIGNAL(attitudeChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,int,double,double,double,quint64)));

165
    trails.clear();
166 167
    trailNode->removeDrawables(0, trailNode->getNumDrawables());
    orientationNode->removeChildren(0, orientationNode->getNumChildren());
168

169 170 171
    this->uas = uas;
}

172 173 174 175 176 177 178 179 180 181 182 183
void
Pixhawk3DWidget::addToTrails(UASInterface* uas, int component, double x, double y, double z, quint64 time)
{
    if (this->uas->getUASID() != uas->getUASID())
    {
        return;
    }

    if (!trails.contains(component))
    {
        trails[component] = QVarLengthArray<osg::Vec3d, 10000>();
        trailDrawableIdxs[component] = trails.size() - 1;
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

        osg::Vec4 color((float)qrand() / RAND_MAX,
                        (float)qrand() / RAND_MAX,
                        (float)qrand() / RAND_MAX,
                        0.5);
        trailNode->addDrawable(createTrail(color));

        double radius = 0.5;

        osg::ref_ptr<osg::Group> group = new osg::Group;

        // cone indicates waypoint orientation
        osg::ref_ptr<osg::ShapeDrawable> sd = new osg::ShapeDrawable;
        double coneRadius = radius / 2.0;
        osg::ref_ptr<osg::Cone> cone =
            new osg::Cone(osg::Vec3d(0.0, 0.0, 0.0),
                          coneRadius, radius * 2.0);

        sd->setShape(cone);
        sd->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
        sd->setColor(color);

        osg::ref_ptr<osg::Geode> geode = new osg::Geode;
        geode->addDrawable(sd);

        osg::ref_ptr<osg::PositionAttitudeTransform> pat =
            new osg::PositionAttitudeTransform;
        pat->addChild(geode);
        pat->setAttitude(osg::Quat(- 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)));
        group->addChild(pat);

        // cylinder indicates waypoint position
        sd = new osg::ShapeDrawable;
        osg::ref_ptr<osg::Cylinder> cylinder =
            new osg::Cylinder(osg::Vec3d(0.0, 0.0, 0.0),
                              radius, 0);

        sd->setShape(cylinder);
        sd->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
        sd->setColor(color);

        geode = new osg::Geode;
        geode->addDrawable(sd);
        group->addChild(geode);

        pat = new osg::PositionAttitudeTransform;
        orientationNode->addChild(pat);
        pat->addChild(group);
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    }

    QVarLengthArray<osg::Vec3d, 10000>& trail = trails[component];

    bool addToTrail = false;
    if (trail.size() > 0)
    {
        if (fabs(x - trail[trail.size() - 1].x()) > 0.01f ||
                fabs(y - trail[trail.size() - 1].y()) > 0.01f ||
                fabs(z - trail[trail.size() - 1].z()) > 0.01f)
        {
            addToTrail = true;
        }
    }
    else
    {
        addToTrail = true;
    }

    if (addToTrail)
    {
        osg::Vec3d p(x, y, z);
        if (trail.size() == trail.capacity())
        {
            memcpy(trail.data(), trail.data() + 1,
                   (trail.size() - 1) * sizeof(osg::Vec3d));
            trail[trail.size() - 1] = p;
        }
        else
        {
            trail.append(p);
        }
    }
}

269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
void
Pixhawk3DWidget::updateAttitude(UASInterface* uas, int component, double roll, double pitch, double yaw, quint64 time)
{
    if (this->uas->getUASID() != uas->getUASID())
    {
        return;
    }

    if (!trails.contains(component))
    {
        return;
    }

    int idx = trailDrawableIdxs[component];

    osg::PositionAttitudeTransform* pat =
        dynamic_cast<osg::PositionAttitudeTransform*>(orientationNode->getChild(idx));

    pat->setAttitude(osg::Quat(-yaw, osg::Vec3d(0.0f, 0.0f, 1.0f),
                               0.0, osg::Vec3d(1.0f, 0.0f, 0.0f),
                               0.0, osg::Vec3d(0.0f, 1.0f, 0.0f)));
}

292 293 294
void
Pixhawk3DWidget::selectFrame(QString text)
{
295 296
    if (text.compare("Global") == 0)
    {
297
        frame = MAV_FRAME_GLOBAL;
298 299 300
    }
    else if (text.compare("Local") == 0)
    {
LM's avatar
LM committed
301
        frame = MAV_FRAME_LOCAL_NED;
302 303 304 305 306 307 308
    }

    getPosition(lastRobotX, lastRobotY, lastRobotZ);

    recenter();
}

309
void
310 311 312 313 314 315 316 317 318 319 320 321 322 323
Pixhawk3DWidget::showLocalGrid(int32_t state)
{
    if (state == Qt::Checked)
    {
        displayLocalGrid = true;
    }
    else
    {
        displayLocalGrid = false;
    }
}

void
Pixhawk3DWidget::showWorldGrid(int32_t state)
324
{
325 326
    if (state == Qt::Checked)
    {
327
        displayWorldGrid = true;
328 329 330
    }
    else
    {
331
        displayWorldGrid = false;
332 333 334 335
    }
}

void
336
Pixhawk3DWidget::showTrails(int32_t state)
337
{
338 339
    if (state == Qt::Checked)
    {
340
        if (!displayTrails)
341
        {
342
            trails.clear();
343 344
        }

345
        displayTrails = true;
346 347 348
    }
    else
    {
349
        displayTrails = false;
350 351 352
    }
}

353 354 355
void
Pixhawk3DWidget::showWaypoints(int state)
{
356 357
    if (state == Qt::Checked)
    {
358
        displayWaypoints = true;
359 360 361
    }
    else
    {
362 363 364 365
        displayWaypoints = false;
    }
}

366 367 368 369
void
Pixhawk3DWidget::selectMapSource(int index)
{
    mapNode->setImageryType(static_cast<Imagery::ImageryType>(index));
370

371 372
    if (mapNode->getImageryType() == Imagery::BLANK_MAP)
    {
373
        displayImagery = false;
374 375 376
    }
    else
    {
377 378
        displayImagery = true;
    }
379 380
}

381 382 383
void
Pixhawk3DWidget::selectVehicleModel(int index)
{
384
    egocentricMap->removeChild(vehicleModel);
385
    vehicleModel = vehicleModels.at(index);
386
    egocentricMap->addChild(vehicleModel);
387 388
}

389
void
390
Pixhawk3DWidget::recenter(void)
391
{
392
    double robotX = 0.0f, robotY = 0.0f, robotZ = 0.0f;
393
    getPosition(robotX, robotY, robotZ);
394

395
    recenterCamera(robotY, robotX, -robotZ);
396 397 398
}

void
399
Pixhawk3DWidget::toggleFollowCamera(int32_t state)
400
{
401 402
    if (state == Qt::Checked)
    {
403
        followCamera = true;
404 405 406
    }
    else
    {
407
        followCamera = false;
408 409
    }
}
410

411
void
412
Pixhawk3DWidget::selectTargetHeading(void)
413
{
414 415 416 417
    if (!uas)
    {
        return;
    }
418

419 420
    osg::Vec2d p;

421 422 423
    if (frame == MAV_FRAME_GLOBAL)
    {
        double altitude = uas->getAltitude();
424

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

428
        p.set(cursorWorldCoords.first, cursorWorldCoords.second);
429 430 431 432
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();
433

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

437
        p.set(cursorWorldCoords.first, cursorWorldCoords.second);
438
    }
439

440
    target.setW(atan2(p.y() - target.y(), p.x() - target.x()));
441 442 443 444 445 446 447 448 449
}

void
Pixhawk3DWidget::selectTarget(void)
{
    if (!uas)
    {
        return;
    }
450 451 452 453
    if (!uas->getParamManager())
    {
        return;
    }
454 455 456 457 458 459

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

        std::pair<double,double> cursorWorldCoords =
460 461
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(),
                                    altitude);
462

463 464 465 466 467 468 469 470
        QVariant zTarget;
        if (!uas->getParamManager()->getParameterValue(MAV_COMP_ID_PATHPLANNER, "TARGET-ALT", zTarget))
        {
            zTarget = -altitude;
        }

        target = QVector4D(cursorWorldCoords.first, cursorWorldCoords.second,
                           zTarget.toReal(), 0.0);
471 472 473 474 475 476
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();

        std::pair<double,double> cursorWorldCoords =
477
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(), -z);
478

479 480 481 482 483 484 485 486
        QVariant zTarget;
        if (!uas->getParamManager()->getParameterValue(MAV_COMP_ID_PATHPLANNER, "TARGET-ALT", zTarget))
        {
            zTarget = z;
        }

        target = QVector4D(cursorWorldCoords.first, cursorWorldCoords.second,
                           zTarget.toReal(), 0.0);
487
    }
488 489

    enableTarget = true;
490

491
    mode = SELECT_TARGET_HEADING_MODE;
492 493 494 495 496 497 498
}

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

499 500
    uas->setTargetPosition(target.x(), target.y(), target.z(),
                           osg::RadiansToDegrees(target.w()));
501 502
}

503 504 505
void
Pixhawk3DWidget::insertWaypoint(void)
{
506 507 508 509
    if (!uas)
    {
        return;
    }
510

511 512 513 514 515 516 517 518 519 520 521
    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 =
522 523
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(),
                                    altitude);
524 525 526 527

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

528
        wp = new Waypoint(0, longitude, latitude, altitude, 0.0, 0.25);
529 530 531 532 533 534
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        double z = uas->getLocalZ();

        std::pair<double,double> cursorWorldCoords =
535
            getGlobalCursorPosition(cachedMousePos.x(), cachedMousePos.y(), -z);
536 537

        wp = new Waypoint(0, cursorWorldCoords.first,
538
                          cursorWorldCoords.second, z, 0.0, 0.25);
539 540 541 542 543 544
    }

    if (wp)
    {
        wp->setFrame(frame);
        uas->getWaypointManager()->addWaypointEditable(wp);
545 546
    }

547 548
    selectedWpIndex = wp->getId();
    mode = MOVE_WAYPOINT_HEADING_MODE;
549 550 551
}

void
552
Pixhawk3DWidget::moveWaypointPosition(void)
553
{
554 555 556 557 558 559
    if (mode != MOVE_WAYPOINT_POSITION_MODE)
    {
        mode = MOVE_WAYPOINT_POSITION_MODE;
        return;
    }

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    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);

581 582
        Imagery::UTMtoLL(cursorWorldCoords.first, cursorWorldCoords.second,
                         utmZone, latitude, longitude);
583 584 585 586 587 588 589 590 591 592 593 594 595

        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);
596 597 598
    }
}

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
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);
}

642 643 644
void
Pixhawk3DWidget::deleteWaypoint(void)
{
645 646
    if (uas)
    {
647
        uas->getWaypointManager()->removeWaypoint(selectedWpIndex);
648 649 650 651 652 653
    }
}

void
Pixhawk3DWidget::setWaypointAltitude(void)
{
654 655 656 657
    if (!uas)
    {
        return;
    }
658

659 660 661 662
    bool ok;
    const QVector<Waypoint *> waypoints =
        uas->getWaypointManager()->getWaypointEditableList();
    Waypoint* waypoint = waypoints.at(selectedWpIndex);
663

664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    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);
682
        }
683 684 685 686 687 688
    }
}

void
Pixhawk3DWidget::clearAllWaypoints(void)
{
689 690
    if (uas)
    {
691
        const QVector<Waypoint *> waypoints =
pixhawk's avatar
pixhawk committed
692
            uas->getWaypointManager()->getWaypointEditableList();
693 694
        for (int i = waypoints.size() - 1; i >= 0; --i)
        {
695
            uas->getWaypointManager()->removeWaypoint(i);
696
        }
697 698 699
    }
}

700 701 702 703
QVector< osg::ref_ptr<osg::Node> >
Pixhawk3DWidget::findVehicleModels(void)
{
    QDir directory("models");
lm's avatar
lm committed
704
    QStringList files = directory.entryList(QStringList("*.osg"), QDir::Files);
705 706 707 708

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

    // add Pixhawk Bravo model
709
    nodes.push_back(PixhawkCheetahGeode::instance());
710

hengli's avatar
hengli committed
711 712 713
    // 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);
714
    sphereDrawable->setColor(osg::Vec4f(0.5f, 0.0f, 0.5f, 1.0f));
hengli's avatar
hengli committed
715 716 717 718 719
    osg::ref_ptr<osg::Geode> sphereGeode = new osg::Geode;
    sphereGeode->addDrawable(sphereDrawable);
    sphereGeode->setName("Sphere (0.1m)");
    nodes.push_back(sphereGeode);

720
    // add all other models in folder
721 722
    for (int i = 0; i < files.size(); ++i)
    {
723
        osg::ref_ptr<osg::Node> node =
724
            osgDB::readNodeFile(directory.absoluteFilePath(files[i]).toStdString().c_str());
725

726 727
        if (node)
        {
728
            nodes.push_back(node);
729 730 731
        }
        else
        {
732
            printf("%s\n", QString("ERROR: Could not load file " + directory.absoluteFilePath(files[i]) + "\n").toStdString().c_str());
lm's avatar
lm committed
733
        }
734 735
    }

lm's avatar
lm committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
//    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());
//        }
//    }

758 759 760 761 762 763
    return nodes;
}

void
Pixhawk3DWidget::buildLayout(void)
{
764 765
    QComboBox* frameComboBox = new QComboBox(this);
    frameComboBox->addItem("Local");
766
    frameComboBox->addItem("Global");
767 768
    frameComboBox->setFixedWidth(70);

769 770 771 772 773 774 775
    QCheckBox* localGridCheckBox = new QCheckBox(this);
    localGridCheckBox->setText("Local Grid");
    localGridCheckBox->setChecked(displayLocalGrid);

    QCheckBox* worldGridCheckBox = new QCheckBox(this);
    worldGridCheckBox->setText("World Grid");
    worldGridCheckBox->setChecked(displayWorldGrid);
776 777

    QCheckBox* trailCheckBox = new QCheckBox(this);
778 779
    trailCheckBox->setText("Trails");
    trailCheckBox->setChecked(displayTrails);
780 781 782 783 784

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

785 786 787 788 789 790
    QLabel* mapLabel = new QLabel("Map", this);
    QComboBox* mapComboBox = new QComboBox(this);
    mapComboBox->addItem("None");
    mapComboBox->addItem("Map (Google)");
    mapComboBox->addItem("Satellite (Google)");

791
    QLabel* modelLabel = new QLabel("Vehicle", this);
792
    QComboBox* modelComboBox = new QComboBox(this);
793 794
    for (int i = 0; i < vehicleModels.size(); ++i)
    {
795 796 797 798 799 800 801 802 803 804 805 806 807
        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);
808
    layout->addWidget(frameComboBox, 0, 10);
809 810 811 812 813 814 815 816 817 818 819 820
    layout->addWidget(localGridCheckBox, 2, 0);
    layout->addWidget(worldGridCheckBox, 2, 1);
    layout->addWidget(trailCheckBox, 2, 2);
    layout->addWidget(waypointsCheckBox, 2, 3);
    layout->addItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 2, 4);
    layout->addWidget(mapLabel, 2, 5);
    layout->addWidget(mapComboBox, 2, 6);
    layout->addWidget(modelLabel, 2, 7);
    layout->addWidget(modelComboBox, 2, 8);
    layout->addItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 2, 9);
    layout->addWidget(recenterButton, 2, 10);
    layout->addWidget(followCameraCheckBox, 2, 11);
821 822 823
    layout->setRowStretch(0, 1);
    layout->setRowStretch(1, 100);
    layout->setRowStretch(2, 1);
824 825
    setLayout(layout);

826 827
    connect(frameComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(selectFrame(QString)));
828 829 830 831
    connect(localGridCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showLocalGrid(int)));
    connect(worldGridCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showWorldGrid(int)));
832
    connect(trailCheckBox, SIGNAL(stateChanged(int)),
833
            this, SLOT(showTrails(int)));
834 835
    connect(waypointsCheckBox, SIGNAL(stateChanged(int)),
            this, SLOT(showWaypoints(int)));
836 837
    connect(mapComboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(selectMapSource(int)));
838 839 840 841 842 843
    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)));
}
844

845 846 847 848 849 850 851 852
void
Pixhawk3DWidget::resizeGL(int width, int height)
{
    Q3DWidget::resizeGL(width, height);

    resizeHUD();
}

853 854 855
void
Pixhawk3DWidget::display(void)
{
856
    // set node visibility
857 858
    allocentricMap->setChildValue(worldGridNode, displayWorldGrid);
    rollingMap->setChildValue(localGridNode, displayLocalGrid);
859
    rollingMap->setChildValue(trailNode, displayTrails);
860
    rollingMap->setChildValue(orientationNode, displayTrails);
861 862 863
    rollingMap->setChildValue(mapNode, displayImagery);
    rollingMap->setChildValue(waypointGroupNode, displayWaypoints);
    rollingMap->setChildValue(targetNode, enableTarget);
864
#if defined(QGC_PROTOBUF_ENABLED) && defined(QGC_USE_PIXHAWK_MESSAGES)
865
    rollingMap->setChildValue(obstacleGroupNode, displayObstacleList);
866
    rollingMap->setChildValue(pathNode, displayPath);
867 868 869 870 871
#endif
    rollingMap->setChildValue(rgbd3DNode, displayRGBD3D);
    hudGroup->setChildValue(rgb2DGeode, displayRGBD2D);
    hudGroup->setChildValue(depth2DGeode, displayRGBD2D);

872 873
    if (!uas)
    {
874 875 876
        return;
    }

877
    double robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw;
878
    QString utmZone;
879
    getPose(robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw, utmZone);
880

881 882
    if (lastRobotX == 0.0f && lastRobotY == 0.0f && lastRobotZ == 0.0f)
    {
883 884 885 886 887
        lastRobotX = robotX;
        lastRobotY = robotY;
        lastRobotZ = robotZ;

        recenterCamera(robotY, robotX, -robotZ);
888 889
    }

890 891
    if (followCamera)
    {
892 893 894
        double dx = robotY - lastRobotY;
        double dy = robotX - lastRobotX;
        double dz = lastRobotZ - robotZ;
895 896

        moveCamera(dx, dy, dz);
897 898
    }

899 900 901 902
    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)));
903

904
    if (displayTrails)
905
    {
906
        updateTrails(robotX, robotY, robotZ);
907 908
    }

909 910
    if (frame == MAV_FRAME_GLOBAL && displayImagery)
    {
911
        updateImagery(robotX, robotY, robotZ, utmZone);
912 913
    }

914 915
    if (displayWaypoints)
    {
916 917 918
        updateWaypoints();
    }

919 920
    if (enableTarget)
    {
921
        updateTarget(robotX, robotY, robotZ);
922 923
    }

924
#if defined(QGC_PROTOBUF_ENABLED) && defined(QGC_USE_PIXHAWK_MESSAGES)
925 926
    if (displayRGBD2D || displayRGBD3D)
    {
927
        updateRGBD(robotX, robotY, robotZ);
928
    }
929 930 931

    if (displayObstacleList)
    {
932
        updateObstacles(robotX, robotY, robotZ);
933
    }
934 935 936 937 938

    if (displayPath)
    {
        updatePath(robotX, robotY, robotZ);
    }
939
#endif
940

941
    updateHUD(robotX, robotY, robotZ, robotRoll, robotPitch, robotYaw, utmZone);
942

943 944 945
    lastRobotX = robotX;
    lastRobotY = robotY;
    lastRobotZ = robotZ;
LM's avatar
LM committed
946 947

    layout()->update();
948 949
}

950 951 952
void
Pixhawk3DWidget::keyPressEvent(QKeyEvent* event)
{
953 954 955 956
    if (!event->text().isEmpty())
    {
        switch (*(event->text().toAscii().data()))
        {
957 958 959
        case '1':
            displayRGBD2D = !displayRGBD2D;
            break;
960 961 962
        case '2':
            displayRGBD3D = !displayRGBD3D;
            break;
963 964
        case 'c':
        case 'C':
965 966
            enableRGBDColor = !enableRGBDColor;
            break;
967 968 969 970
        case 'o':
        case 'O':
            displayObstacleList = !displayObstacleList;
            break;
971 972 973 974
        case 'p':
        case 'P':
            displayPath = !displayPath;
            break;
975 976 977 978 979 980
        }
    }

    Q3DWidget::keyPressEvent(event);
}

981 982 983
void
Pixhawk3DWidget::mousePressEvent(QMouseEvent* event)
{
984 985
    if (event->button() == Qt::LeftButton)
    {
986
        if (mode == SELECT_TARGET_HEADING_MODE)
987
        {
988
            setTarget();
989 990
        }

991
        if (mode != DEFAULT_MODE)
992 993
        {
            mode = DEFAULT_MODE;
994 995
        }

996 997
        if (event->modifiers() == Qt::ShiftModifier)
        {
998
            selectedWpIndex = findWaypoint(event->pos());
999 1000
            if (selectedWpIndex == -1)
            {
1001 1002
                cachedMousePos = event->pos();

1003
                showInsertWaypointMenu(event->globalPos());
1004 1005 1006
            }
            else
            {
1007 1008 1009 1010 1011
                showEditWaypointMenu(event->globalPos());
            }

            return;
        }
1012 1013 1014 1015 1016
    }

    Q3DWidget::mousePressEvent(event);
}

1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
void
Pixhawk3DWidget::showEvent(QShowEvent* event)
{
    Q3DWidget::showEvent(event);
    emit visibilityChanged(true);
}

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

1031 1032 1033
void
Pixhawk3DWidget::mouseMoveEvent(QMouseEvent* event)
{
1034
    if (mode == SELECT_TARGET_HEADING_MODE)
1035 1036 1037
    {
        selectTargetHeading();
    }
1038 1039 1040 1041 1042 1043 1044 1045
    if (mode == MOVE_WAYPOINT_POSITION_MODE)
    {
        moveWaypointPosition();
    }
    if (mode == MOVE_WAYPOINT_HEADING_MODE)
    {
        moveWaypointHeading();
    }
1046 1047 1048 1049

    Q3DWidget::mouseMoveEvent(event);
}

1050 1051 1052 1053 1054
void
Pixhawk3DWidget::getPose(double& x, double& y, double& z,
                         double& roll, double& pitch, double& yaw,
                         QString& utmZone)
{
1055 1056 1057 1058
    if (!uas)
    {
        return;
    }
1059

1060 1061 1062 1063 1064 1065 1066 1067
    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;
1068
    }
1069 1070 1071 1072 1073
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
        x = uas->getLocalX();
        y = uas->getLocalY();
        z = uas->getLocalZ();
1074
    }
1075 1076 1077 1078

    roll = uas->getRoll();
    pitch = uas->getPitch();
    yaw = uas->getYaw();
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
}

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)
{
1093
    if (!uas)
Lorenz Meier's avatar
Lorenz Meier committed
1094
    {
1095 1096
        return;
    }
1097

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    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();
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    }
}

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

1122
osg::ref_ptr<osg::Geode>
1123
Pixhawk3DWidget::createLocalGrid(void)
1124 1125
{
    osg::ref_ptr<osg::Geode> geode(new osg::Geode());
1126 1127 1128 1129
    osg::ref_ptr<osg::Geometry> fineGeometry(new osg::Geometry());
    osg::ref_ptr<osg::Geometry> coarseGeometry(new osg::Geometry());
    geode->addDrawable(fineGeometry);
    geode->addDrawable(coarseGeometry);
1130

1131
    float radius = 5.0f;
1132 1133
    float resolution = 0.25f;

1134 1135
    osg::ref_ptr<osg::Vec3Array> fineCoords(new osg::Vec3Array);
    osg::ref_ptr<osg::Vec3Array> coarseCoords(new osg::Vec3Array);
1136

1137
    // draw a 10m x 10m grid with 0.25m resolution
1138 1139
    for (float i = -radius; i <= radius; i += resolution)
    {
1140
        if (fabs(i / 1.0f - floor(i / 1.0f)) < 0.01f)
1141
        {
1142 1143 1144 1145
            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));
1146 1147 1148
        }
        else
        {
1149 1150 1151 1152 1153
            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));
        }
1154 1155
    }

1156 1157
    fineGeometry->setVertexArray(fineCoords);
    coarseGeometry->setVertexArray(coarseCoords);
1158 1159 1160

    osg::ref_ptr<osg::Vec4Array> color(new osg::Vec4Array);
    color->push_back(osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f));
1161 1162 1163 1164 1165 1166
    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,
1167
                                  0, fineCoords->size()));
1168
    coarseGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0,
1169
                                    coarseCoords->size()));
1170 1171 1172 1173 1174 1175

    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);
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    fineStateset->setMode(GL_LINE_SMOOTH, osg::StateAttribute::ON);
    fineStateset->setMode(GL_BLEND, osg::StateAttribute::ON);
    fineGeometry->setStateSet(fineStateset);

    osg::ref_ptr<osg::StateSet> coarseStateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> coarseLinewidth(new osg::LineWidth());
    coarseLinewidth->setWidth(1.0f);
    coarseStateset->setAttributeAndModes(coarseLinewidth, osg::StateAttribute::ON);
    coarseStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    coarseStateset->setMode(GL_LINE_SMOOTH, osg::StateAttribute::ON);
    coarseStateset->setMode(GL_BLEND, osg::StateAttribute::ON);
    coarseGeometry->setStateSet(coarseStateset);

    return geode;
}

osg::ref_ptr<osg::Geode>
Pixhawk3DWidget::createWorldGrid(void)
{
    osg::ref_ptr<osg::Geode> geode(new osg::Geode());
    osg::ref_ptr<osg::Geometry> fineGeometry(new osg::Geometry());
    osg::ref_ptr<osg::Geometry> coarseGeometry(new osg::Geometry());
    osg::ref_ptr<osg::Geometry> axisGeometry(new osg::Geometry());
    geode->addDrawable(fineGeometry);
    geode->addDrawable(coarseGeometry);
    geode->addDrawable(axisGeometry.get());

    float radius = 20.0f;
    float resolution = 1.0f;

    osg::ref_ptr<osg::Vec3Array> fineCoords(new osg::Vec3Array);
    osg::ref_ptr<osg::Vec3Array> coarseCoords(new osg::Vec3Array);

    // draw a 40m x 40m grid with 1.0m resolution
    for (float i = -radius; i <= radius; i += resolution)
    {
        if (fabs(i / 5.0f - floor(i / 5.0f)) < 0.01f)
        {
            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));
        }
        else
        {
            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));
        }
    }

    fineGeometry->setVertexArray(fineCoords);
    coarseGeometry->setVertexArray(coarseCoords);

    osg::ref_ptr<osg::Vec4Array> color(new osg::Vec4Array);
    color->push_back(osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f));
    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,
                                  0, fineCoords->size()));
    coarseGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0,
                                    coarseCoords->size()));

    osg::ref_ptr<osg::StateSet> fineStateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> fineLinewidth(new osg::LineWidth());
    fineLinewidth->setWidth(0.1f);
    fineStateset->setAttributeAndModes(fineLinewidth, osg::StateAttribute::ON);
    fineStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    fineStateset->setMode(GL_LINE_SMOOTH, osg::StateAttribute::ON);
    fineStateset->setMode(GL_BLEND, osg::StateAttribute::ON);
1250 1251 1252 1253 1254 1255 1256
    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);
1257 1258
    coarseStateset->setMode(GL_LINE_SMOOTH, osg::StateAttribute::ON);
    coarseStateset->setMode(GL_BLEND, osg::StateAttribute::ON);
1259
    coarseGeometry->setStateSet(coarseStateset);
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    // add axes
    osg::ref_ptr<osg::Vec3Array> coords(new osg::Vec3Array(6));
    (*coords)[0] = (*coords)[2] = (*coords)[4] =
                                      osg::Vec3(0.0f, 0.0f, 0.0f);
    (*coords)[1] = osg::Vec3(0.0f, 1.0f, 0.0f);
    (*coords)[3] = osg::Vec3(1.0f, 0.0f, 0.0f);
    (*coords)[5] = osg::Vec3(0.0f, 0.0f, -1.0f);

    axisGeometry->setVertexArray(coords);

    osg::Vec4 redColor(1.0f, 0.0f, 0.0f, 0.0f);
    osg::Vec4 greenColor(0.0f, 1.0f, 0.0f, 0.0f);
    osg::Vec4 blueColor(0.0f, 0.0f, 1.0f, 0.0f);

    osg::ref_ptr<osg::Vec4Array> axisColors(new osg::Vec4Array(6));
    (*axisColors)[0] = redColor;
    (*axisColors)[1] = redColor;
    (*axisColors)[2] = greenColor;
    (*axisColors)[3] = greenColor;
    (*axisColors)[4] = blueColor;
    (*axisColors)[5] = blueColor;

    axisGeometry->setColorArray(axisColors);
    axisGeometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);

    axisGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 6));

    osg::ref_ptr<osg::StateSet> axisStateset(new osg::StateSet);
    osg::ref_ptr<osg::LineWidth> axisLinewidth(new osg::LineWidth());
    axisLinewidth->setWidth(4.0f);
    axisStateset->setAttributeAndModes(axisLinewidth, osg::StateAttribute::ON);
    axisStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
    axisGeometry->setStateSet(axisStateset);

1295 1296 1297
    return geode;
}

1298
osg::ref_ptr<osg::Geometry>
1299
Pixhawk3DWidget::createTrail(const osg::Vec4& color)
1300
{
1301 1302
    osg::ref_ptr<osg::Geometry> geometry(new osg::Geometry());
    geometry->setUseDisplayList(false);
1303

1304 1305
    osg::ref_ptr<osg::Vec3dArray> vertices(new osg::Vec3dArray());
    geometry->setVertexArray(vertices);
1306

1307 1308
    osg::ref_ptr<osg::DrawArrays> drawArrays(new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP));
    geometry->addPrimitiveSet(drawArrays);
1309

1310 1311 1312 1313
    osg::ref_ptr<osg::Vec4Array> colorArray(new osg::Vec4Array);
    colorArray->push_back(color);
    geometry->setColorArray(colorArray);
    geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
1314 1315 1316 1317 1318 1319

    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);
1320
    geometry->setStateSet(stateset);
1321

1322
    return geometry;
1323 1324
}

1325
osg::ref_ptr<Imagery>
1326 1327
Pixhawk3DWidget::createMap(void)
{
1328
    return osg::ref_ptr<Imagery>(new Imagery());
1329 1330
}

1331
osg::ref_ptr<osg::Geode>
1332
Pixhawk3DWidget::createRGBD3D(void)
1333
{
1334
    int frameSize = 752 * 480;
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

    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;
1350 1351
}

1352 1353 1354 1355
osg::ref_ptr<osg::Node>
Pixhawk3DWidget::createTarget(void)
{
    osg::ref_ptr<osg::PositionAttitudeTransform> pat =
1356
        new osg::PositionAttitudeTransform;
1357 1358 1359

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

1360
    osg::ref_ptr<osg::Cone> cone = new osg::Cone(osg::Vec3f(0.0f, 0.0f, 0.0f), 0.2f, 0.6f);
1361 1362 1363 1364 1365 1366
    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");
1367

1368
    pat->addChild(coneGeode);
1369 1370 1371 1372

    return pat;
}

1373 1374 1375 1376
void
Pixhawk3DWidget::setupHUD(void)
{
    osg::ref_ptr<osg::Vec4Array> hudColors(new osg::Vec4Array);
1377 1378
    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));
1379 1380

    hudBackgroundGeometry = new osg::Geometry;
1381
    hudBackgroundGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON,
1382
                                           0, 4));
1383
    hudBackgroundGeometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POLYGON,
1384
                                           4, 4));
1385
    hudBackgroundGeometry->setColorArray(hudColors);
1386
    hudBackgroundGeometry->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
1387
    hudBackgroundGeometry->setUseDisplayList(false);
1388 1389 1390

    statusText = new osgText::Text;
    statusText->setCharacterSize(11);
1391
    statusText->setFont(font);
1392 1393 1394
    statusText->setAxisAlignment(osgText::Text::SCREEN);
    statusText->setColor(osg::Vec4(255, 255, 255, 1));

1395 1396 1397 1398 1399 1400
    osg::ref_ptr<osg::Geode> statusGeode = new osg::Geode;
    statusGeode->addDrawable(hudBackgroundGeometry);
    statusGeode->addDrawable(statusText);
    hudGroup->addChild(statusGeode);

    rgbImage = new osg::Image;
1401 1402 1403
    rgb2DGeode = new ImageWindowGeode;
    rgb2DGeode->init("RGB Image", osg::Vec4(0.0f, 0.0f, 0.1f, 1.0f),
                     rgbImage, font);
1404 1405 1406
    hudGroup->addChild(rgb2DGeode);

    depthImage = new osg::Image;
1407 1408 1409
    depth2DGeode = new ImageWindowGeode;
    depth2DGeode->init("Depth Image", osg::Vec4(0.0f, 0.0f, 0.1f, 1.0f),
                       depthImage, font);
1410
    hudGroup->addChild(depth2DGeode);
1411 1412

    scaleGeode = new HUDScaleGeode;
1413
    scaleGeode->init(font);
1414
    hudGroup->addChild(scaleGeode);
1415 1416 1417
}

void
1418
Pixhawk3DWidget::resizeHUD(void)
1419
{
1420
    int topHUDHeight = 25;
1421 1422 1423
    int bottomHUDHeight = 25;

    osg::Vec3Array* vertices = static_cast<osg::Vec3Array*>(hudBackgroundGeometry->getVertexArray());
Lorenz Meier's avatar
Lorenz Meier committed
1424 1425
    if (vertices == NULL || vertices->size() != 8)
    {
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
        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);
1440

1441
    statusText->setPosition(osg::Vec3(10, height() - 15, -1.5));
1442

Lorenz Meier's avatar
Lorenz Meier committed
1443 1444
    if (rgb2DGeode.valid() && depth2DGeode.valid())
    {
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        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
1455
Pixhawk3DWidget::updateHUD(double robotX, double robotY, double robotZ,
1456 1457
                           double robotRoll, double robotPitch, double robotYaw,
                           const QString& utmZone)
1458
{
1459
    std::pair<double,double> cursorPosition =
1460
        getGlobalCursorPosition(getMouseX(), getMouseY(), -robotZ);
1461 1462 1463 1464

    std::ostringstream oss;
    oss.setf(std::ios::fixed, std::ios::floatfield);
    oss.precision(2);
Lorenz Meier's avatar
Lorenz Meier committed
1465 1466
    if (frame == MAV_FRAME_GLOBAL)
    {
1467 1468 1469 1470 1471 1472 1473 1474 1475
        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 <<
1476
            " Lon = " << longitude;
1477 1478 1479

        oss.precision(2);
        oss << " Altitude = " << -robotZ <<
1480 1481 1482
            " r = " << robotRoll <<
            " p = " << robotPitch <<
            " y = " << robotYaw;
1483 1484 1485

        oss.precision(6);
        oss << " Cursor [" << cursorLatitude <<
1486
            " " << cursorLongitude << "]";
Lorenz Meier's avatar
Lorenz Meier committed
1487 1488 1489
    }
    else if (frame == MAV_FRAME_LOCAL_NED)
    {
1490
        oss << " x = " << robotX <<
1491 1492 1493 1494 1495 1496 1497
            " y = " << robotY <<
            " z = " << robotZ <<
            " r = " << robotRoll <<
            " p = " << robotPitch <<
            " y = " << robotYaw <<
            " Cursor [" << cursorPosition.first <<
            " " << cursorPosition.second << "]";
1498 1499
    }

1500
    statusText->setText(oss.str());
1501

1502
    bool darkBackground = true;
Lorenz Meier's avatar
Lorenz Meier committed
1503 1504
    if (mapNode->getImageryType() == Imagery::GOOGLE_MAP)
    {
1505 1506 1507 1508 1509
        darkBackground = false;
    }

    scaleGeode->update(height(), cameraParams.cameraFov,
                       cameraManipulator->getDistance(), darkBackground);
1510 1511 1512
}

void
1513
Pixhawk3DWidget::updateTrails(double robotX, double robotY, double robotZ)
1514
{
1515
    QMapIterator<int,int> it(trailDrawableIdxs);
1516

1517
    while (it.hasNext())
Lorenz Meier's avatar
Lorenz Meier committed
1518
    {
1519
        it.next();
1520

1521 1522 1523 1524 1525 1526 1527 1528
        osg::Geometry* geometry = trailNode->getDrawable(it.value())->asGeometry();
        osg::DrawArrays* drawArrays = reinterpret_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));

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

        const QVarLengthArray<osg::Vec3d, 10000>& trail = trails.value(it.key());

        for (int i = 0; i < trail.size(); ++i)
Lorenz Meier's avatar
Lorenz Meier committed
1529
        {
1530 1531 1532
            vertices->push_back(osg::Vec3d(trail[i].y() - robotY,
                                           trail[i].x() - robotX,
                                           -(trail[i].z() - robotZ)));
1533 1534
        }

1535 1536 1537 1538
        geometry->setVertexArray(vertices);
        drawArrays->setFirst(0);
        drawArrays->setCount(vertices->size());
        geometry->dirtyBound();
1539 1540 1541 1542 1543 1544

        osg::PositionAttitudeTransform* pat =
            dynamic_cast<osg::PositionAttitudeTransform*>(orientationNode->getChild(it.value()));
        pat->setPosition(osg::Vec3(trail[trail.size() - 1].y() - robotY,
                                   trail[trail.size() - 1].x() - robotX,
                                   -(trail[trail.size() - 1].z() - robotZ)));
1545 1546 1547
    }
}

1548
void
1549
Pixhawk3DWidget::updateImagery(double originX, double originY, double originZ,
1550
                               const QString& zone)
1551
{
Lorenz Meier's avatar
Lorenz Meier committed
1552 1553
    if (mapNode->getImageryType() == Imagery::BLANK_MAP)
    {
1554 1555 1556
        return;
    }

1557
    double viewingRadius = cameraManipulator->getDistance() * 10.0;
Lorenz Meier's avatar
Lorenz Meier committed
1558 1559
    if (viewingRadius < 100.0)
    {
1560 1561 1562 1563
        viewingRadius = 100.0;
    }

    double minResolution = 0.25;
1564
    double centerResolution = cameraManipulator->getDistance() / 50.0;
1565 1566 1567
    double maxResolution = 1048576.0;

    Imagery::ImageryType imageryType = mapNode->getImageryType();
Lorenz Meier's avatar
Lorenz Meier committed
1568 1569
    switch (imageryType)
    {
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
    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;
1580
    default:
1581
        {}
1582 1583 1584
    }

    double resolution = minResolution;
Lorenz Meier's avatar
Lorenz Meier committed
1585 1586
    while (resolution * 2.0 < centerResolution)
    {
1587 1588
        resolution *= 2.0;
    }
Lorenz Meier's avatar
Lorenz Meier committed
1589 1590 1591

    if (resolution > maxResolution)
    {
1592 1593 1594 1595 1596 1597 1598
        resolution = maxResolution;
    }

    mapNode->draw3D(viewingRadius,
                    resolution,
                    cameraManipulator->getCenter().y(),
                    cameraManipulator->getCenter().x(),
1599 1600
                    originX,
                    originY,
1601
                    originZ,
1602 1603 1604
                    zone);

    // prefetch map tiles
Lorenz Meier's avatar
Lorenz Meier committed
1605 1606
    if (resolution / 2.0 >= minResolution)
    {
1607 1608 1609 1610 1611 1612
        mapNode->prefetch3D(viewingRadius / 2.0,
                            resolution / 2.0,
                            cameraManipulator->getCenter().y(),
                            cameraManipulator->getCenter().x(),
                            zone);
    }
Lorenz Meier's avatar
Lorenz Meier committed
1613 1614
    if (resolution * 2.0 <= maxResolution)
    {
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
        mapNode->prefetch3D(viewingRadius * 2.0,
                            resolution * 2.0,
                            cameraManipulator->getCenter().y(),
                            cameraManipulator->getCenter().x(),
                            zone);
    }

    mapNode->update();
}

1625 1626 1627
void
Pixhawk3DWidget::updateWaypoints(void)
{
1628
    waypointGroupNode->update(frame, uas);
1629
}
1630

1631
void
1632
Pixhawk3DWidget::updateTarget(double robotX, double robotY, double robotZ)
1633 1634
{
    osg::PositionAttitudeTransform* pat =
1635 1636
        dynamic_cast<osg::PositionAttitudeTransform*>(targetNode.get());

1637 1638 1639 1640
    pat->setPosition(osg::Vec3d(target.y() - robotY,
                                target.x() - robotX,
                                -(target.z() - robotZ)));
    pat->setAttitude(osg::Quat(target.w() - M_PI_2, osg::Vec3d(1.0f, 0.0f, 0.0f),
1641 1642 1643 1644 1645
                               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));
1646 1647

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

1650
#if defined(QGC_PROTOBUF_ENABLED) && defined(QGC_USE_PIXHAWK_MESSAGES)
1651
void
1652
Pixhawk3DWidget::updateRGBD(double robotX, double robotY, double robotZ)
1653
{
1654 1655 1656
    qreal receivedRGBDImageTimestamp, receivedPointCloudTimestamp;
    px::RGBDImage rgbdImage = uas->getRGBDImage(receivedRGBDImageTimestamp);
    px::PointCloudXYZRGB pointCloud = uas->getPointCloud(receivedPointCloudTimestamp);
1657

1658 1659
    if (rgbdImage.rows() > 0 && rgbdImage.cols() > 0 &&
        QGC::groundTimeSeconds() - receivedRGBDImageTimestamp < kMessageTimeout)
1660
    {
1661 1662 1663 1664 1665 1666 1667 1668
        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)
1669
        {
1670 1671 1672
            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)
1673
            {
1674 1675
                if (depth[c] != 0)
                {
pixhawk's avatar
pixhawk committed
1676
                    int idx = fminf(depth[c], 7.0f) / 7.0f * 127.0f;
1677
                    idx = 127 - idx;
1678

1679 1680 1681 1682 1683
                    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;
1684
                }
1685

1686 1687
                pixel += 3;
            }
1688 1689
        }

1690 1691 1692 1693 1694 1695
        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();
    }
1696 1697 1698 1699

    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());
1700 1701 1702 1703 1704 1705 1706

    if (QGC::groundTimeSeconds() - receivedPointCloudTimestamp > kMessageTimeout)
    {
        geometry->removePrimitiveSet(0, geometry->getNumPrimitiveSets());
        return;
    }

1707 1708
    for (int i = 0; i < pointCloud.points_size(); ++i)
    {
1709 1710 1711 1712 1713 1714
        const px::PointCloudXYZRGB_PointXYZRGB& p = pointCloud.points(i);

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

1715

1716
        (*vertices)[i].set(y, x, -z);
1717

1718 1719
        if (enableRGBDColor)
        {
1720 1721 1722 1723 1724 1725 1726
            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);
1727 1728 1729
        }
        else
        {
1730 1731
            double dist = sqrt(x * x + y * y + z * z);
            int colorIndex = static_cast<int>(fmin(dist / 7.0 * 127.0, 127.0));
1732 1733 1734 1735 1736

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

            (*colors)[i].set(r, g, b, 1.0f);
1737
        }
1738 1739
    }

1740 1741
    if (geometry->getNumPrimitiveSets() == 0)
    {
1742
        geometry->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS,
1743
                                  0, pointCloud.points_size()));
1744 1745 1746
    }
    else
    {
1747
        osg::DrawArrays* drawarrays = static_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));
1748
        drawarrays->setCount(pointCloud.points_size());
1749
    }
1750
}
1751 1752

void
1753
Pixhawk3DWidget::updateObstacles(double robotX, double robotY, double robotZ)
1754
{
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
    if (frame == MAV_FRAME_GLOBAL)
    {
        obstacleGroupNode->clear();
        return;
    }

    qreal receivedTimestamp;
    px::ObstacleList obstacleList = uas->getObstacleList(receivedTimestamp);

    if (QGC::groundTimeSeconds() - receivedTimestamp < kMessageTimeout)
1765
    {
1766
        obstacleGroupNode->update(robotX, robotY, robotZ, obstacleList);
1767 1768 1769 1770 1771
    }
    else
    {
        obstacleGroupNode->clear();
    }
1772 1773
}

1774 1775 1776
void
Pixhawk3DWidget::updatePath(double robotX, double robotY, double robotZ)
{
1777 1778
    qreal receivedTimestamp;
    px::Path path = uas->getPath(receivedTimestamp);
1779

1780
    osg::Geometry* geometry = pathNode->getDrawable(0)->asGeometry();
1781
    osg::DrawArrays* drawArrays = reinterpret_cast<osg::DrawArrays*>(geometry->getPrimitiveSet(0));
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
    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);

1793
    if (QGC::groundTimeSeconds() - receivedTimestamp < kMessageTimeout)
1794
    {
1795 1796 1797 1798 1799 1800
        // 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);
1801

1802 1803 1804 1805
            length += qgc::hypot3f(wp0.x() - wp1.x(),
                                   wp0.y() - wp1.y(),
                                   wp0.z() - wp1.z());
        }
1806

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

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

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

1821 1822 1823 1824 1825
        float lengthCurrent = 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);
1826

1827 1828 1829
            lengthCurrent += qgc::hypot3f(wp0.x() - wp1.x(),
                                          wp0.y() - wp1.y(),
                                          wp0.z() - wp1.z());
1830

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

1835
            int colorIdx = lengthCurrent / length * 127.0f;
1836

1837 1838 1839 1840
            float r, g, b;
            qgc::colormap("autumn", colorIdx, r, g, b);
            colorArray->push_back(osg::Vec4f(r, g, b, 1.0f));
        }
1841 1842
    }

1843
    geometry->setVertexArray(vertices);
1844 1845 1846 1847 1848
    drawArrays->setFirst(0);
    drawArrays->setCount(vertices->size());
    geometry->dirtyBound();
}

1849
#endif
1850

1851
int
1852
Pixhawk3DWidget::findWaypoint(const QPoint& mousePos)
1853
{
1854 1855
    if (getSceneData())
    {
1856 1857
        osgUtil::LineSegmentIntersector::Intersections intersections;

1858 1859
        if (computeIntersections(mousePos.x(), height() - mousePos.y(),
                                 intersections))
1860
        {
1861
            for (osgUtil::LineSegmentIntersector::Intersections::iterator
1862 1863 1864 1865
                    it = intersections.begin(); it != intersections.end(); it++)
            {
                for (uint i = 0 ; i < it->nodePath.size(); ++i)
                {
1866
                    std::string nodeName = it->nodePath[i]->getName();
1867 1868
                    if (nodeName.substr(0, 2).compare("wp") == 0)
                    {
1869
                        return atoi(nodeName.substr(2).c_str());
1870 1871 1872 1873 1874 1875 1876 1877 1878
                    }
                }
            }
        }
    }

    return -1;
}

1879 1880 1881
bool
Pixhawk3DWidget::findTarget(int mouseX, int mouseY)
{
1882 1883
    if (getSceneData())
    {
1884 1885
        osgUtil::LineSegmentIntersector::Intersections intersections;

1886 1887
        if (computeIntersections(mouseX, height() - mouseY, intersections))
        {
1888
            for (osgUtil::LineSegmentIntersector::Intersections::iterator
1889 1890 1891 1892
                    it = intersections.begin(); it != intersections.end(); it++)
            {
                for (uint i = 0 ; i < it->nodePath.size(); ++i)
                {
1893
                    std::string nodeName = it->nodePath[i]->getName();
1894 1895
                    if (nodeName.compare("Target") == 0)
                    {
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

1906 1907 1908 1909 1910 1911
void
Pixhawk3DWidget::showInsertWaypointMenu(const QPoint &cursorPos)
{
    QMenu menu;
    menu.addAction("Insert new waypoint", this, SLOT(insertWaypoint()));
    menu.addAction("Clear all waypoints", this, SLOT(clearAllWaypoints()));
1912
    menu.addAction("Select target", this, SLOT(selectTarget()));
1913 1914 1915 1916 1917 1918 1919 1920 1921
    menu.exec(cursorPos);
}

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

    QString text;
1922
    text = QString("Move waypoint %1").arg(QString::number(selectedWpIndex));
1923 1924 1925 1926
    menu.addAction(text, this, SLOT(moveWaypointPosition()));

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

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

1931
    text = QString("Delete waypoint %1").arg(QString::number(selectedWpIndex));
1932 1933 1934 1935 1936
    menu.addAction(text, this, SLOT(deleteWaypoint()));

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