RouteComplexItem.cc 20 KB
Newer Older
1 2 3 4
#include "RouteComplexItem.h"

#include "CircularGenerator.h"
#include "LinearGenerator.h"
5
#include "RoutingThread.h"
6 7 8 9 10 11 12
#include "geometry/GenericCircle.h"
#include "geometry/MeasurementArea.h"
#include "geometry/SafeArea.h"
#include "geometry/clipper/clipper.hpp"
#include "geometry/snake.h"
#include "nemo_interface/SnakeTile.h"

13 14 15 16 17 18 19 20 21
// QGC
#include "JsonHelper.h"
#include "QGCApplication.h"
#include "QGCLoggingCategory.h"

// boost
#include <boost/units/io.hpp>
#include <boost/units/systems/si.hpp>

22
#define CLIPPER_SCALE 1000000
23

24
QGC_LOGGING_CATEGORY(RouteComplexItemLog, "RouteComplexItemLog")
25 26 27 28 29 30

template <typename T>
constexpr typename std::underlying_type<T>::type integral(T value) {
  return static_cast<typename std::underlying_type<T>::type>(value);
}

31 32 33 34
const char *RouteComplexItem::settingsGroup = "Route";
const char *RouteComplexItem::jsonComplexItemTypeValue = "Route";
const char *RouteComplexItem::variantName = "Variant";
const QString RouteComplexItem::name(tr("Route"));
35

36 37 38
RouteComplexItem::RouteComplexItem(PlanMasterController *masterController,
                                   bool flyView, const QString &kmlOrShpFile,
                                   QObject *parent)
39 40 41 42
    : TransectStyleComplexItem(masterController, flyView, settingsGroup,
                               parent),
      _state(STATE::IDLE),
      _metaDataMap(FactMetaData::createMapFromJsonFile(
43
          QStringLiteral(":/json/RouteComplexItem.SettingsGroup.json"), this)),
44
      _variant(settingsGroup, _metaDataMap[variantName]),
45 46
      _areaData(new AreaData(this)), _editorData(new AreaData(this)),
      _currentData(_areaData), _pWorker(new RoutingThread(this)) {
47 48 49 50 51 52

  Q_UNUSED(kmlOrShpFile)
  _editorQml = "qrc:/qml/CircularSurveyItemEditor.qml";

  // Connect facts.
  connect(&this->_variant, &Fact::rawValueChanged, this,
53
          &RouteComplexItem::_changeVariant);
54 55

  // Connect worker.
56 57 58 59
  connect(this->_pWorker, &RoutingThread::result, this,
          &RouteComplexItem::_setTransects);
  connect(this->_pWorker, &RoutingThread::calculatingChanged, this,
          &RouteComplexItem::calculatingChanged);
60 61

  // Register Generators.
62
  auto lg = new routing::LinearGenerator(this->_areaData, this);
63
  registerGenerator(lg->name(), lg);
64
  auto cg = new routing::CircularGenerator(this->_areaData, this);
65 66 67
  registerGenerator(cg->name(), cg);
}

68
RouteComplexItem::~RouteComplexItem() {}
69

70
void RouteComplexItem::revertPath() {
71 72 73 74
  this->_setState(STATE::REVERT_PATH);
  this->_rebuildTransects();
}

75 76
const AreaData *RouteComplexItem::areaData() const {
  return this->_currentData;
77 78
}

79
AreaData *RouteComplexItem::areaData() { return this->_currentData; }
80

81
QStringList RouteComplexItem::variantNames() const { return _variantNames; }
82

83 84
bool RouteComplexItem::load(const QJsonObject &complexObject,
                            int sequenceNumber, QString &errorString) {
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  // We need to pull version first to determine what validation/conversion
  // needs to be performed
  QList<JsonHelper::KeyValidateInfo> versionKeyInfoList = {
      {JsonHelper::jsonVersionKey, QJsonValue::Double, true},
  };
  if (!JsonHelper::validateKeys(complexObject, versionKeyInfoList,
                                errorString)) {
    return false;
  }

  int version = complexObject[JsonHelper::jsonVersionKey].toInt();
  if (version != 1) {
    errorString = tr("Survey items do not support version %1").arg(version);
    return false;
  }

  QList<JsonHelper::KeyValidateInfo> keyInfoList = {
      {VisualMissionItem::jsonTypeKey, QJsonValue::String, true},
      {ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true},
      {variantName, QJsonValue::Double, false},
  };

  if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
    return false;
  }

  QString itemType = complexObject[VisualMissionItem::jsonTypeKey].toString();
  QString complexType =
      complexObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
  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;
  }

  _ignoreRecalc = true;

  setSequenceNumber(sequenceNumber);

  if (!_surveyAreaPolygon.loadFromJson(complexObject, true /* required */,
                                       errorString)) {
    _surveyAreaPolygon.clear();
    return false;
  }

  if (!load(complexObject, sequenceNumber, errorString)) {
    _ignoreRecalc = false;
    return false;
  }

  _variant.setRawValue(complexObject[variantName].toInt());

  _ignoreRecalc = false;

  if (_cameraShots == 0) {
    // Shot count was possibly not available from plan file
    _recalcCameraShots();
  }

  return true;
}

151
QString RouteComplexItem::mapVisualQML() const {
152 153 154
  return QStringLiteral("CircularSurveyMapVisual.qml");
}

155
void RouteComplexItem::save(QJsonArray &planItems) {
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
  QJsonObject saveObject;

  _save(saveObject);

  saveObject[JsonHelper::jsonVersionKey] = 1;
  saveObject[VisualMissionItem::jsonTypeKey] =
      VisualMissionItem::jsonTypeComplexItemValue;
  saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =
      jsonComplexItemTypeValue;

  saveObject[variantName] = double(_variant.rawValue().toUInt());

  // Polygon shape
  _surveyAreaPolygon.saveToJson(saveObject);

  planItems.append(saveObject);
}

174
bool RouteComplexItem::specifiesCoordinate() const {
175 176 177
  return _transects.count() > 0 ? _transects.first().count() > 0 : false;
}

178
bool RouteComplexItem::_setGenerator(PtrGenerator newG) {
179 180
  if (this->_pGenerator != newG) {
    if (this->_pGenerator != nullptr) {
181 182
      disconnect(this->_pGenerator, &routing::GeneratorBase::generatorChanged,
                 this, &RouteComplexItem::_rebuildTransects);
183 184 185
    }

    this->_pGenerator = newG;
186 187
    connect(this->_pGenerator, &routing::GeneratorBase::generatorChanged, this,
            &RouteComplexItem::_rebuildTransects);
188 189 190 191 192 193 194 195 196 197 198
    emit generatorChanged();

    this->_setState(STATE::IDLE);
    _rebuildTransects();

    return true;
  } else {
    return false;
  }
}

199
void RouteComplexItem::_setState(RouteComplexItem::STATE state) {
200 201 202 203 204 205 206 207 208
  if (this->_state != state) {
    auto oldState = this->_state;
    this->_state = state;
    if (_calculating(oldState) != _calculating(state)) {
      emit calculatingChanged();
    }
  }
}

209
bool RouteComplexItem::_calculating(RouteComplexItem::STATE state) const {
210 211 212
  return state == STATE::ROUTING;
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
void RouteComplexItem::_setEditing(bool editing) {
  if (editing != _editing) {
    _editing = editing;
    emit editingChanged();
  }
}

void RouteComplexItem::_setAreaData(RouteComplexItem::PtrAreaData data) {
  if (_currentData != data) {
    _currentData = data;
    emit areaDataChanged();
  }
}

void RouteComplexItem::_changeVariant() {
228 229 230 231
  this->_setState(STATE::CHANGE_VARIANT);
  this->_rebuildTransects();
}

232
bool RouteComplexItem::_updateWorker() {
233 234 235 236 237 238 239 240 241 242 243 244
  // Reset data.
  this->_transects.clear();
  this->_variantVector.clear();
  this->_variantNames.clear();
  emit variantNamesChanged();

  if (this->_areaData->isValid()) {

    // Prepare data.
    auto origin = this->_areaData->origin();
    origin.setAltitude(0);
    if (!origin.isValid()) {
245
      qCDebug(RouteComplexItemLog)
246 247 248 249 250
          << "_updateWorker(): origin invalid." << origin;
      return false;
    }

    // Convert safe area.
251 252 253
    auto serviceArea =
        getGeoArea<const SafeArea *>(*this->_areaData->areaList());
    auto geoSafeArea = serviceArea->coordinateList();
254
    if (!(geoSafeArea.size() >= 3)) {
255
      qCDebug(RouteComplexItemLog)
256 257 258 259 260 261 262
          << "_updateWorker(): safe area invalid." << geoSafeArea;
      return false;
    }
    for (auto &v : geoSafeArea) {
      if (v.isValid()) {
        v.setAltitude(0);
      } else {
263
        qCDebug(RouteComplexItemLog)
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
            << "_updateWorker(): safe area contains invalid coordinate."
            << geoSafeArea;
        return false;
      }
    }

    // Routing par.
    RoutingParameter par;
    par.numSolutions = 5;
    auto &safeAreaENU = par.safeArea;
    snake::areaToEnu(origin, geoSafeArea, safeAreaENU);

    // Create generator.
    if (this->_pGenerator) {
      routing::GeneratorBase::Generator g; // Transect generator.
      if (this->_pGenerator->get(g)) {
        // Start/Restart routing worker.
        this->_pWorker->route(par, g);
        return true;
      } else {
284
        qCDebug(RouteComplexItemLog)
285 286 287 288
            << "_updateWorker(): generator creation failed.";
        return false;
      }
    } else {
289
      qCDebug(RouteComplexItemLog)
290 291 292 293 294 295
          << "_updateWorker(): pGenerator == nullptr, number of registered "
             "generators: "
          << this->_generatorList.size();
      return false;
    }
  } else {
296
    qCDebug(RouteComplexItemLog) << "_updateWorker(): plan data invalid.";
297 298 299 300
    return false;
  }
}

301
void RouteComplexItem::_changeVariantWorker() {
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  auto variant = this->_variant.rawValue().toUInt();

  // Find old variant and run. Old run corresponts with empty list.
  std::size_t old_variant = std::numeric_limits<std::size_t>::max();
  for (std::size_t i = 0; i < std::size_t(this->_variantVector.size()); ++i) {
    const auto &variantCoordinates = this->_variantVector.at(i);
    if (variantCoordinates.isEmpty()) {
      old_variant = i;
      break;
    }
  }

  // Swap route.
  if (variant != old_variant) {
    // Swap in new variant.
    if (variant < std::size_t(this->_variantVector.size())) {
      if (old_variant != std::numeric_limits<std::size_t>::max()) {
        // this->_transects containes a route, swap it back to
        // this->_solutionVector
        auto &oldVariantCoordinates = this->_variantVector[old_variant];
        oldVariantCoordinates.swap(this->_transects);
      }
      auto &newVariantCoordinates = this->_variantVector[variant];
      this->_transects.swap(newVariantCoordinates);

    } else { // error
328
      qCDebug(RouteComplexItemLog)
329
          << "Variant out of bounds (variant =" << variant << ").";
330
      qCDebug(RouteComplexItemLog) << "Resetting variant to zero.";
331 332

      disconnect(&this->_variant, &Fact::rawValueChanged, this,
333
                 &RouteComplexItem::_changeVariant);
334 335
      this->_variant.setCookedValue(QVariant(0));
      connect(&this->_variant, &Fact::rawValueChanged, this,
336
              &RouteComplexItem::_changeVariant);
337 338 339 340 341 342 343 344

      if (this->_variantVector.size() > 0) {
        this->_changeVariantWorker();
      }
    }
  }
}

345
void RouteComplexItem::_reverseWorker() {
346 347 348 349 350 351
  if (this->_transects.size() > 0) {
    auto &t = this->_transects.front();
    std::reverse(t.begin(), t.end());
  }
}

352
double RouteComplexItem::timeBetweenShots() { return 0; }
353

354
QString RouteComplexItem::commandDescription() const { return tr("Route"); }
355

356
QString RouteComplexItem::commandName() const { return tr("Route"); }
357

358
QString RouteComplexItem::abbreviation() const { return tr("R"); }
359 360

TransectStyleComplexItem::ReadyForSaveState
361
RouteComplexItem::readyForSaveState() const {
362 363 364 365 366 367 368 369 370 371 372 373
  if (TransectStyleComplexItem::readyForSaveState() ==
      TransectStyleComplexItem::ReadyForSaveState::ReadyForSave) {
    if (this->_state == STATE::IDLE) {
      return ReadyForSaveState::ReadyForSave;
    } else {
      return ReadyForSaveState::NotReadyForSaveData;
    }
  } else {
    return TransectStyleComplexItem::readyForSaveState();
  }
}

374
double RouteComplexItem::additionalTimeDelay() const { return 0; }
375

376
QString RouteComplexItem::patternName() const { return name; }
377

378 379
bool RouteComplexItem::registerGenerator(const QString &name,
                                         routing::GeneratorBase *g) {
380
  if (name.isEmpty()) {
381
    qCDebug(RouteComplexItemLog) << "registerGenerator(): empty name string.";
382 383 384 385
    return false;
  }

  if (!g) {
386
    qCDebug(RouteComplexItemLog) << "registerGenerator(): empty generator.";
387 388 389 390
    return false;
  }

  if (this->_generatorNameList.contains(name)) {
391 392
    qCDebug(RouteComplexItemLog) << "registerGenerator(): generator "
                                    "already registered.";
393 394 395 396 397
    return false;
  } else {
    this->_generatorNameList.push_back(name);
    this->_generatorList.push_back(g);
    if (this->_generatorList.size() == 1) {
398
      _setGenerator(g);
399 400 401 402 403 404 405
    }

    emit generatorNameListChanged();
    return true;
  }
}

406
bool RouteComplexItem::unregisterGenerator(const QString &name) {
407 408 409 410 411 412
  auto index = this->_generatorNameList.indexOf(name);
  if (index >= 0) {
    // Is this the current generator?
    const auto &g = this->_generatorList.at(index);
    if (g == this->_pGenerator) {
      if (index > 0) {
413
        _setGenerator(this->_generatorList.at(index - 1));
414
      } else {
415 416
        _setGenerator(nullptr);
        qCDebug(RouteComplexItemLog)
417 418 419 420 421
            << "unregisterGenerator(): last generator unregistered.";
      }
    }

    this->_generatorNameList.removeAt(index);
422 423
    auto gen = this->_generatorList.takeAt(index);
    gen->deleteLater();
424 425 426 427

    emit generatorNameListChanged();
    return true;
  } else {
428
    qCDebug(RouteComplexItemLog)
429 430 431 432 433
        << "unregisterGenerator(): generator " << name << " not registered.";
    return false;
  }
}

434
bool RouteComplexItem::unregisterGenerator(int index) {
435 436 437
  if (index > 0 && index < this->_generatorNameList.size()) {
    return unregisterGenerator(this->_generatorNameList.at(index));
  } else {
438 439 440 441
    qCDebug(RouteComplexItemLog) << "unregisterGenerator(): index (" << index
                                 << ") out"
                                    "of bounds ( "
                                 << this->_generatorList.size() << " ).";
442 443 444 445
    return false;
  }
}

446
bool RouteComplexItem::switchToGenerator(const QString &name) {
447 448
  auto index = this->_generatorNameList.indexOf(name);
  if (index >= 0) {
449
    _setGenerator(this->_generatorList.at(index));
450 451
    return true;
  } else {
452
    qCDebug(RouteComplexItemLog)
453 454 455 456 457
        << "switchToGenerator(): generator " << name << " not registered.";
    return false;
  }
}

458
bool RouteComplexItem::switchToGenerator(int index) {
459
  if (index >= 0) {
460
    _setGenerator(this->_generatorList.at(index));
461 462
    return true;
  } else {
463 464 465 466
    qCDebug(RouteComplexItemLog) << "unregisterGenerator(): index (" << index
                                 << ") out"
                                    "of bounds ( "
                                 << this->_generatorNameList.size() << " ).";
467 468 469 470
    return false;
  }
}

471
QStringList RouteComplexItem::generatorNameList() {
472 473 474
  return this->_generatorNameList;
}

475
routing::GeneratorBase *RouteComplexItem::generator() { return _pGenerator; }
476

477
int RouteComplexItem::generatorIndex() {
478 479 480
  return this->_generatorList.indexOf(this->_pGenerator);
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
void RouteComplexItem::editingStart() {
  if (!_editing) {
    *_editorData = *_areaData;
    _setAreaData(_editorData);
    _setEditing(true);
  }
}

void RouteComplexItem::editingStop() {
  if (_editing) {
    if (_editorData->isValid()) {
      *_areaData = *_editorData;
    }
    _setAreaData(_areaData);
    _setEditing(false);
  }
}

void RouteComplexItem::_rebuildTransectsPhase1(void) {
500 501 502 503
  auto start = std::chrono::high_resolution_clock::now();

  switch (this->_state) {
  case STATE::SKIPP:
504
    qCDebug(RouteComplexItemLog) << "rebuildTransectsPhase1: skipp.";
505 506 507
    this->_setState(STATE::IDLE);
    break;
  case STATE::CHANGE_VARIANT:
508
    qCDebug(RouteComplexItemLog) << "rebuildTransectsPhase1: variant change.";
509 510 511 512
    this->_changeVariantWorker();
    this->_setState(STATE::IDLE);
    break;
  case STATE::REVERT_PATH:
513
    qCDebug(RouteComplexItemLog) << "rebuildTransectsPhase1: reverse.";
514 515 516 517 518 519
    this->_reverseWorker();
    this->_setState(STATE::IDLE);
    break;
  case STATE::IDLE:
  case STATE::ROUTING:
    this->_setState(STATE::ROUTING);
520
    qCDebug(RouteComplexItemLog) << "rebuildTransectsPhase1: update.";
521 522 523 524 525 526
    if (!this->_updateWorker()) {
      this->_setState(STATE::IDLE);
    }
    break;
  }

527
  qCDebug(RouteComplexItemLog)
528 529 530 531 532 533 534
      << "rebuildTransectsPhase1(): "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

535
void RouteComplexItem::_recalcCameraShots() { _cameraShots = 0; }
536

537
void RouteComplexItem::_setTransects(RouteComplexItem::PtrRoutingData pRoute) {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  // Store solutions.
  auto ori = this->_areaData->origin();
  ori.setAltitude(0);
  const auto &transectsENU = pRoute->transects;
  QVector<Variant> variantVector;
  const auto nSolutions = pRoute->solutionVector.size();

  for (std::size_t j = 0; j < nSolutions; ++j) {
    Variant var{QList<CoordInfo_t>()};
    const auto &solution = pRoute->solutionVector.at(j);
    if (solution.size() > 0) {
      const auto &route = solution.at(0);
      const auto &path = route.path;
      const auto &info = route.info;
      if (info.size() > 1) {
        // Find index of first waypoint.
        std::size_t idxFirst = 0;
        const auto &infoFirst = info.at(1);
        const auto &firstTransect = transectsENU[infoFirst.index];
        if (firstTransect.size() > 0) {
          const auto &firstWaypoint =
              infoFirst.reversed ? firstTransect.back() : firstTransect.front();
          double th = 0.01;
          for (std::size_t i = 0; i < path.size(); ++i) {
            auto dist = bg::distance(path[i], firstWaypoint);
            if (dist < th) {
              idxFirst = i;
              break;
            }
          }

          // Find index of last waypoint.
          std::size_t idxLast = path.size() - 1;
          const auto &infoLast = info.at(info.size() - 2);
          const auto &lastTransect = transectsENU[infoLast.index];
          if (lastTransect.size() > 0) {
            const auto &lastWaypoint =
                infoLast.reversed ? lastTransect.front() : lastTransect.back();
            for (long i = path.size() - 1; i >= 0; --i) {
              auto dist = bg::distance(path[i], lastWaypoint);
              if (dist < th) {
                idxLast = i;
                break;
              }
            }

            // Convert to geo coordinates.
            auto &list = var.front();
            for (std::size_t i = idxFirst; i <= idxLast; ++i) {
              auto &vertex = path[i];
              QGeoCoordinate c;
              snake::fromENU(ori, vertex, c);
              list.append(CoordInfo_t{c, CoordTypeInterior});
            }

          } else {
594
            qCDebug(RouteComplexItemLog)
595 596 597
                << "_setTransects(): lastTransect.size() == 0";
          }
        } else {
598
          qCDebug(RouteComplexItemLog)
599 600 601
              << "_setTransects(): firstTransect.size() == 0";
        }
      } else {
602
        qCDebug(RouteComplexItemLog)
603 604 605
            << "_setTransects(): transectsInfo.size() <= 1";
      }
    } else {
606
      qCDebug(RouteComplexItemLog) << "_setTransects(): solution.size() == 0";
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
    }

    if (var.size() > 0 && var.front().size() > 0) {
      variantVector.push_back(std::move(var));
    }
  }

  // Assign routes if no error occured.
  if (variantVector.size() > 0) {
    // Swap first route to _transects.
    this->_variantVector.swap(variantVector);

    // If the transects are getting rebuilt then any previously loaded
    // mission items are now invalid.
    if (_loadedMissionItemsParent) {
      _loadedMissionItems.clear();
      _loadedMissionItemsParent->deleteLater();
      _loadedMissionItemsParent = nullptr;
    }

    // Add route variant names.
    this->_variantNames.clear();
    for (std::size_t i = 1; i <= std::size_t(this->_variantVector.size());
         ++i) {
      this->_variantNames.append(QString::number(i));
    }
    emit variantNamesChanged();

    disconnect(&this->_variant, &Fact::rawValueChanged, this,
636
               &RouteComplexItem::_changeVariant);
637 638
    this->_variant.setCookedValue(QVariant(0));
    connect(&this->_variant, &Fact::rawValueChanged, this,
639
            &RouteComplexItem::_changeVariant);
640 641 642 643 644
    this->_changeVariantWorker();

    this->_setState(STATE::SKIPP);
    this->_rebuildTransects();
  } else {
645
    qCDebug(RouteComplexItemLog)
646 647 648 649 650
        << "_setTransects(): failed, variantVector empty.";
    this->_setState(STATE::IDLE);
  }
}

651
Fact *RouteComplexItem::variant() { return &_variant; }
652

653
bool RouteComplexItem::calculating() const {
654 655 656
  return this->_calculating(this->_state);
}

657
bool RouteComplexItem::editing() const { return this->_editing; }