StructureScanComplexItem.cc 20.2 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
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "StructureScanComplexItem.h"
#include "JsonHelper.h"
#include "MissionController.h"
#include "QGCGeo.h"
#include "QGroundControlQmlGlobal.h"
#include "QGCQGeoCoordinate.h"
#include "SettingsManager.h"
#include "AppSettings.h"
#include "QGCQGeoCoordinate.h"

#include <QPolygonF>

QGC_LOGGING_CATEGORY(StructureScanComplexItemLog, "StructureScanComplexItemLog")

24 25 26 27
const char* StructureScanComplexItem::settingsGroup =               "StructureScan";
const char* StructureScanComplexItem::altitudeName =                "Altitude";
const char* StructureScanComplexItem::structureHeightName =         "StructureHeight";
const char* StructureScanComplexItem::layersName =                  "Layers";
28

29 30 31
const char* StructureScanComplexItem::jsonComplexItemTypeValue =    "StructureScan";
const char* StructureScanComplexItem::_jsonCameraCalcKey =          "CameraCalc";
const char* StructureScanComplexItem::_jsonAltitudeRelativeKey =    "altitudeRelative";
32

33
StructureScanComplexItem::StructureScanComplexItem(Vehicle* vehicle, bool flyView, const QString& kmlFile, QObject* parent)
34
    : ComplexMissionItem        (vehicle, flyView, parent)
35
    , _metaDataMap              (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/StructureScan.SettingsGroup.json"), this /* QObject parent */))
36 37 38 39 40 41 42
    , _sequenceNumber           (0)
    , _dirty                    (false)
    , _altitudeRelative         (true)
    , _entryVertex              (0)
    , _ignoreRecalc             (false)
    , _scanDistance             (0.0)
    , _cameraShots              (0)
43 44 45 46
    , _cameraCalc               (vehicle, settingsGroup)
    , _altitudeFact             (settingsGroup, _metaDataMap[altitudeName])
    , _structureHeightFact      (settingsGroup, _metaDataMap[structureHeightName])
    , _layersFact               (settingsGroup, _metaDataMap[layersName])
47 48 49 50 51
{
    _editorQml = "qrc:/qml/StructureScanEditor.qml";

    _altitudeFact.setRawValue(qgcApp()->toolbox()->settingsManager()->appSettings()->defaultMissionItemAltitude()->rawValue());

52 53
    connect(&_altitudeFact,     &Fact::valueChanged, this, &StructureScanComplexItem::_setDirty);
    connect(&_layersFact,       &Fact::valueChanged, this, &StructureScanComplexItem::_setDirty);
54

DonLakeFlyer's avatar
DonLakeFlyer committed
55 56 57 58
    connect(&_layersFact,                           &Fact::valueChanged,    this, &StructureScanComplexItem::_recalcLayerInfo);
    connect(&_structureHeightFact,                  &Fact::valueChanged,    this, &StructureScanComplexItem::_recalcLayerInfo);
    connect(_cameraCalc.adjustedFootprintFrontal(), &Fact::valueChanged,    this, &StructureScanComplexItem::_recalcLayerInfo);

59 60 61
    connect(this, &StructureScanComplexItem::altitudeRelativeChanged,       this, &StructureScanComplexItem::_setDirty);
    connect(this, &StructureScanComplexItem::altitudeRelativeChanged,       this, &StructureScanComplexItem::coordinateHasRelativeAltitudeChanged);
    connect(this, &StructureScanComplexItem::altitudeRelativeChanged,       this, &StructureScanComplexItem::exitCoordinateHasRelativeAltitudeChanged);
62 63 64

    connect(&_altitudeFact, &Fact::valueChanged, this, &StructureScanComplexItem::_updateCoordinateAltitudes);

65 66 67 68 69 70
    connect(&_structurePolygon, &QGCMapPolygon::dirtyChanged,   this, &StructureScanComplexItem::_polygonDirtyChanged);
    connect(&_structurePolygon, &QGCMapPolygon::countChanged,   this, &StructureScanComplexItem::_polygonCountChanged);
    connect(&_structurePolygon, &QGCMapPolygon::pathChanged,    this, &StructureScanComplexItem::_rebuildFlightPolygon);

    connect(&_flightPolygon,    &QGCMapPolygon::pathChanged,    this, &StructureScanComplexItem::_flightPathChanged);

71
    connect(_cameraCalc.distanceToSurface(),    &Fact::valueChanged,                this, &StructureScanComplexItem::_rebuildFlightPolygon);
72 73 74 75

    connect(&_flightPolygon,                        &QGCMapPolygon::pathChanged,    this, &StructureScanComplexItem::_recalcCameraShots);
    connect(_cameraCalc.adjustedFootprintSide(),    &Fact::valueChanged,            this, &StructureScanComplexItem::_recalcCameraShots);
    connect(&_layersFact,                           &Fact::valueChanged,            this, &StructureScanComplexItem::_recalcCameraShots);
DonLakeFlyer's avatar
DonLakeFlyer committed
76 77

    _recalcLayerInfo();
78 79 80 81 82 83 84

    if (!kmlFile.isEmpty()) {
        _structurePolygon.loadKMLFile(kmlFile);
        _structurePolygon.setDirty(false);
    }

    setDirty(false);
85 86 87 88 89 90
}

void StructureScanComplexItem::_setScanDistance(double scanDistance)
{
    if (!qFuzzyCompare(_scanDistance, scanDistance)) {
        _scanDistance = scanDistance;
91
        emit complexDistanceChanged();
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
    }
}

void StructureScanComplexItem::_setCameraShots(int cameraShots)
{
    if (_cameraShots != cameraShots) {
        _cameraShots = cameraShots;
        emit cameraShotsChanged(this->cameraShots());
    }
}

void StructureScanComplexItem::_clearInternal(void)
{
    setDirty(true);

    emit specifiesCoordinateChanged();
    emit lastSequenceNumberChanged(lastSequenceNumber());
}

void StructureScanComplexItem::_polygonCountChanged(int count)
{
    Q_UNUSED(count);
    emit lastSequenceNumberChanged(lastSequenceNumber());
}

int StructureScanComplexItem::lastSequenceNumber(void) const
{
119 120 121 122 123 124 125 126 127 128
    // Each structure layer contains:
    //  1 waypoint for each polygon vertex + 1 to go back to first polygon vertex for each layer
    //  Two commands for camera trigger start/stop
    int layerItemCount = _flightPolygon.count() + 1 + 2;

    int multiLayerItemCount = layerItemCount * _layersFact.rawValue().toInt();

    int itemCount = multiLayerItemCount + 2;    // +2 for ROI_WPNEXT_OFFSET and ROI_NONE commands

    return _sequenceNumber + itemCount - 1;
129 130 131 132 133 134 135 136 137 138 139 140 141 142
}

void StructureScanComplexItem::setDirty(bool dirty)
{
    if (_dirty != dirty) {
        _dirty = dirty;
        emit dirtyChanged(_dirty);
    }
}

void StructureScanComplexItem::save(QJsonArray&  missionItems)
{
    QJsonObject saveObject;

143
    // Header
DonLakeFlyer's avatar
DonLakeFlyer committed
144
    saveObject[JsonHelper::jsonVersionKey] =                    2;
145 146 147
    saveObject[VisualMissionItem::jsonTypeKey] =                VisualMissionItem::jsonTypeComplexItemValue;
    saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =    jsonComplexItemTypeValue;

148 149 150 151
    saveObject[altitudeName] =              _altitudeFact.rawValue().toDouble();
    saveObject[structureHeightName] =      _structureHeightFact.rawValue().toDouble();
    saveObject[_jsonAltitudeRelativeKey] =   _altitudeRelative;
    saveObject[layersName] =                _layersFact.rawValue().toDouble();
152 153 154 155 156

    QJsonObject cameraCalcObject;
    _cameraCalc.save(cameraCalcObject);
    saveObject[_jsonCameraCalcKey] = cameraCalcObject;

157
    _structurePolygon.saveToJson(saveObject);
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

    missionItems.append(saveObject);
}

void StructureScanComplexItem::setSequenceNumber(int sequenceNumber)
{
    if (_sequenceNumber != sequenceNumber) {
        _sequenceNumber = sequenceNumber;
        emit sequenceNumberChanged(sequenceNumber);
        emit lastSequenceNumberChanged(lastSequenceNumber());
    }
}

bool StructureScanComplexItem::load(const QJsonObject& complexObject, int sequenceNumber, QString& errorString)
{
173
    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
174 175 176 177
        { JsonHelper::jsonVersionKey,                   QJsonValue::Double, true },
        { VisualMissionItem::jsonTypeKey,               QJsonValue::String, true },
        { ComplexMissionItem::jsonComplexItemTypeKey,   QJsonValue::String, true },
        { QGCMapPolygon::jsonPolygonKey,                QJsonValue::Array,  true },
178 179
        { altitudeName,                                 QJsonValue::Double, true },
        { structureHeightName,                          QJsonValue::Double, true },
DonLakeFlyer's avatar
DonLakeFlyer committed
180
        { _jsonAltitudeRelativeKey,                     QJsonValue::Bool,   true },
181
        { layersName,                                   QJsonValue::Double, true },
182
        { _jsonCameraCalcKey,                           QJsonValue::Object, true },
183
    };
184
    if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
185 186 187
        return false;
    }

188 189 190 191
    _structurePolygon.clear();

    QString itemType = complexObject[VisualMissionItem::jsonTypeKey].toString();
    QString complexType = complexObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
192 193 194 195 196
    if (itemType != VisualMissionItem::jsonTypeComplexItemValue || complexType != jsonComplexItemTypeValue) {
        errorString = tr("%1 does not support loading this complex mission item type: %2:%3").arg(qgcApp()->applicationName()).arg(itemType).arg(complexType);
        return false;
    }

197
    int version = complexObject[JsonHelper::jsonVersionKey].toInt();
DonLakeFlyer's avatar
DonLakeFlyer committed
198
    if (version != 2) {
199
        errorString = tr("%1 complex item version %2 not supported").arg(jsonComplexItemTypeValue).arg(version);
200 201 202
        return false;
    }

203
    setSequenceNumber(sequenceNumber);
204

205 206 207 208 209
    // Load CameraCalc first since it will trigger camera name change which will trounce gimbal angles
    if (!_cameraCalc.load(complexObject[_jsonCameraCalcKey].toObject(), errorString)) {
        return false;
    }

210 211
    _altitudeFact.setRawValue   (complexObject[altitudeName].toDouble());
    _layersFact.setRawValue     (complexObject[layersName].toDouble());
212
    _altitudeRelative =         complexObject[_jsonAltitudeRelativeKey].toBool(true);
213

214
    if (!_structurePolygon.loadFromJson(complexObject, true /* required */, errorString)) {
215
        _structurePolygon.clear();
216 217 218 219 220 221
        return false;
    }

    return true;
}

222
void StructureScanComplexItem::_flightPathChanged(void)
223 224 225 226 227 228 229 230 231
{
    emit coordinateChanged(coordinate());
    emit exitCoordinateChanged(exitCoordinate());
    emit greatestDistanceToChanged();
}

double StructureScanComplexItem::greatestDistanceTo(const QGeoCoordinate &other) const
{
    double greatestDistance = 0.0;
232
    QList<QGeoCoordinate> vertices = _flightPolygon.coordinateList();
233 234 235 236 237 238 239 240 241 242 243 244 245 246

    for (int i=0; i<vertices.count(); i++) {
        QGeoCoordinate vertex = vertices[i];
        double distance = vertex.distanceTo(other);
        if (distance > greatestDistance) {
            greatestDistance = distance;
        }
    }

    return greatestDistance;
}

bool StructureScanComplexItem::specifiesCoordinate(void) const
{
247
    return _flightPolygon.count() > 2;
248 249 250 251 252 253 254
}

void StructureScanComplexItem::appendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
{
    int seqNum = _sequenceNumber;
    double baseAltitude = _altitudeFact.rawValue().toDouble();

255
    MissionItem* item = new MissionItem(seqNum++,
256
                                        MAV_CMD_DO_SET_ROI_WPNEXT_OFFSET,
257
                                        MAV_FRAME_MISSION,
258 259 260
                                        0, 0, 0, 0,                         // param 1-4 not used
                                        0, 0,                               // Pitch and Roll stay in standard orientation
                                        90,                                 // 90 degreee yaw offset to point to structure
261 262 263 264
                                        true,                               // autoContinue
                                        false,                              // isCurrentItem
                                        missionItemParent);
    items.append(item);
265 266

    for (int layer=0; layer<_layersFact.rawValue().toInt(); layer++) {
267
        bool addTriggerStart = true;
DonLakeFlyer's avatar
DonLakeFlyer committed
268 269 270
        // baseAltitude is the bottom of the first layer. Hence we need to move up half the distance of the camera footprint to center the camera
        // within the layer.
        double layerAltitude = baseAltitude + (_cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble() / 2.0) + (layer * _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble());
271

272 273
        for (int i=0; i<_flightPolygon.count(); i++) {
            QGeoCoordinate vertexCoord = _flightPolygon.vertexCoordinate(i);
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

            MissionItem* item = new MissionItem(seqNum++,
                                                MAV_CMD_NAV_WAYPOINT,
                                                _altitudeRelative ? MAV_FRAME_GLOBAL_RELATIVE_ALT : MAV_FRAME_GLOBAL,
                                                0,                                          // No hold time
                                                0.0,                                        // No acceptance radius specified
                                                0.0,                                        // Pass through waypoint
                                                90, //std::numeric_limits<double>::quiet_NaN(),   // Yaw unchanged
                                                vertexCoord.latitude(),
                                                vertexCoord.longitude(),
                                                layerAltitude,
                                                true,                                       // autoContinue
                                                false,                                      // isCurrentItem
                                                missionItemParent);
            items.append(item);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303

            if (addTriggerStart) {
                addTriggerStart = false;
                item = new MissionItem(seqNum++,
                                       MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                                       MAV_FRAME_MISSION,
                                       _cameraCalc.adjustedFootprintSide()->rawValue().toDouble(),  // trigger distance
                                       0,                                                           // shutter integration (ignore)
                                       1,                                                           // trigger immediately when starting
                                       0, 0, 0, 0,                                                  // param 4-7 unused
                                       true,                                                        // autoContinue
                                       false,                                                       // isCurrentItem
                                       missionItemParent);
                items.append(item);
            }
304 305
        }

306
        QGeoCoordinate vertexCoord = _flightPolygon.vertexCoordinate(0);
307 308 309 310 311 312 313 314 315 316 317 318 319 320

        MissionItem* item = new MissionItem(seqNum++,
                                            MAV_CMD_NAV_WAYPOINT,
                                            _altitudeRelative ? MAV_FRAME_GLOBAL_RELATIVE_ALT : MAV_FRAME_GLOBAL,
                                            0,                                          // No hold time
                                            0.0,                                        // No acceptance radius specified
                                            0.0,                                        // Pass through waypoint
                                            std::numeric_limits<double>::quiet_NaN(),   // Yaw unchanged
                                            vertexCoord.latitude(),
                                            vertexCoord.longitude(),
                                            layerAltitude,
                                            true,                                       // autoContinue
                                            false,                                      // isCurrentItem
                                            missionItemParent);
321 322 323 324 325 326 327 328 329 330 331 332
        items.append(item);

        item = new MissionItem(seqNum++,
                               MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                               MAV_FRAME_MISSION,
                               0,           // stop triggering
                               0,           // shutter integration (ignore)
                               0,           // trigger immediately when starting
                               0, 0, 0, 0,  // param 4-7 unused
                               true,        // autoContinue
                               false,       // isCurrentItem
                               missionItemParent);
333 334
        items.append(item);
    }
335 336 337 338 339 340 341 342 343

    item = new MissionItem(seqNum++,
                           MAV_CMD_DO_SET_ROI_NONE,
                           MAV_FRAME_MISSION,
                           0, 0, 0,0, 0, 0, 0,                 // param 1-7 not used
                           true,                               // autoContinue
                           false,                              // isCurrentItem
                           missionItemParent);
    items.append(item);
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

int StructureScanComplexItem::cameraShots(void) const
{
    return true /*_triggerCamera()*/ ? _cameraShots : 0;
}

void StructureScanComplexItem::setMissionFlightStatus(MissionController::MissionFlightStatus_t& missionFlightStatus)
{
    ComplexMissionItem::setMissionFlightStatus(missionFlightStatus);
    if (!qFuzzyCompare(_cruiseSpeed, missionFlightStatus.vehicleSpeed)) {
        _cruiseSpeed = missionFlightStatus.vehicleSpeed;
        emit timeBetweenShotsChanged();
    }
}

void StructureScanComplexItem::_setDirty(void)
{
    setDirty(true);
}

void StructureScanComplexItem::applyNewAltitude(double newAltitude)
{
    _altitudeFact.setRawValue(newAltitude);
}

void StructureScanComplexItem::_polygonDirtyChanged(bool dirty)
{
    if (dirty) {
        setDirty(true);
    }
}

377
double StructureScanComplexItem::timeBetweenShots(void)
378
{
379
    return _cruiseSpeed == 0 ? 0 : _cameraCalc.adjustedFootprintSide()->rawValue().toDouble() / _cruiseSpeed;
380 381 382 383
}

QGeoCoordinate StructureScanComplexItem::coordinate(void) const
{
384 385 386
    if (_flightPolygon.count() > 0) {
        int entryVertex = qMax(qMin(_entryVertex, _flightPolygon.count() - 1), 0);
        return _flightPolygon.vertexCoordinate(entryVertex);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    } else {
        return QGeoCoordinate();
    }
}

QGeoCoordinate StructureScanComplexItem::exitCoordinate(void) const
{
    return coordinate();
}

void StructureScanComplexItem::_updateCoordinateAltitudes(void)
{
    emit coordinateChanged(coordinate());
    emit exitCoordinateChanged(exitCoordinate());
}

void StructureScanComplexItem::rotateEntryPoint(void)
{
    _entryVertex++;
406
    if (_entryVertex >= _flightPolygon.count()) {
407 408 409 410 411
        _entryVertex = 0;
    }
    emit coordinateChanged(coordinate());
    emit exitCoordinateChanged(exitCoordinate());
}
412 413 414 415

void StructureScanComplexItem::_rebuildFlightPolygon(void)
{
    _flightPolygon = _structurePolygon;
416
    _flightPolygon.offset(_cameraCalc.distanceToSurface()->rawValue().toDouble());
417
}
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

void StructureScanComplexItem::_recalcCameraShots(void)
{
    if (_flightPolygon.count() < 3) {
        _setCameraShots(0);
        return;
    }

    // Determine the distance for each polygon traverse
    double distance = 0;
    for (int i=0; i<_flightPolygon.count(); i++) {
        QGeoCoordinate coord1 = _flightPolygon.vertexCoordinate(i);
        QGeoCoordinate coord2 = _flightPolygon.vertexCoordinate(i + 1 == _flightPolygon.count() ? 0 : i + 1);
        distance += coord1.distanceTo(coord2);
    }
    if (distance == 0.0) {
        _setCameraShots(0);
        return;
    }

    int cameraShots = distance / _cameraCalc.adjustedFootprintSide()->rawValue().toDouble();
    _setCameraShots(cameraShots * _layersFact.rawValue().toInt());
}
441 442 443 444 445 446 447 448

void StructureScanComplexItem::setAltitudeRelative(bool altitudeRelative)
{
    if (altitudeRelative != _altitudeRelative) {
        _altitudeRelative = altitudeRelative;
        emit altitudeRelativeChanged(altitudeRelative);
    }
}
DonLakeFlyer's avatar
DonLakeFlyer committed
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465

void StructureScanComplexItem::_recalcLayerInfo(void)
{
    if (_cameraCalc.isManualCamera()) {
        // Structure height is calculated from layer count, layer height.
        _structureHeightFact.setSendValueChangedSignals(false);
        _structureHeightFact.setRawValue(_layersFact.rawValue().toInt() * _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble());
        _structureHeightFact.clearDeferredValueChangeSignal();
        _structureHeightFact.setSendValueChangedSignals(true);
    } else {
        // Layer count is calculated from structure and layer heights
        _layersFact.setSendValueChangedSignals(false);
        _layersFact.setRawValue(qCeil(_structureHeightFact.rawValue().toDouble() / _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble()));
        _layersFact.clearDeferredValueChangeSignal();
        _layersFact.setSendValueChangedSignals(true);
    }
}