MeasurementArea.cc 22.3 KB
Newer Older
1
#include "MeasurementArea.h"
2
#include "HashFunctions.h"
3
#include "geometry.h"
4 5
#include "nemo_interface/MeasurementTile.h"

6
#include <ctime>
7

8 9 10 11
#include "QtConcurrentRun"
#include <QJsonArray>
#include <QQmlEngine>

12 13
#include <boost/units/systems/si.hpp>

14
#include "JsonHelper.h"
15
#include "QGCLoggingCategory.h"
16
#include "QmlObjectListHelper.h"
17

18 19
#include "MeasurementComplexItem/nemo_interface/MeasurementTile.h"

20 21
#ifndef MAX_TILES
#define MAX_TILES 1000
22 23
#endif

24 25
QString randomId();

26 27 28 29 30 31 32 33
using namespace geometry;
namespace trans = bg::strategy::transform;

// Aux function
bool getTiles(const FPolygon &area, Length tileHeight, Length tileWidth,
              Area minTileArea, std::vector<FPolygon> &tiles,
              BoundingBox &bbox);

34
QGC_LOGGING_CATEGORY(MeasurementAreaLog, "MeasurementAreaLog")
35

36 37 38 39
namespace {
const char *tileArrayKey = "TileArray";
} // namespace

40
const char *MeasurementArea::settingsGroup = "MeasurementArea";
41 42 43 44
const char *tileHeightKey = "TileHeight";
const char *tileWidthName = "TileWidth";
const char *minTileAreaKey = "MinTileAreaPercent";
const char *showTilesKey = "ShowTiles";
45
const char *tileKey = "Tiles";
46
const char *toManyTilesKey = "ToManyTiles";
47
const char *MeasurementArea::nameString = "Measurement Area";
48

49 50
MeasurementArea::MeasurementArea(QObject *parent)
    : GeoArea(parent),
51
      _metaDataMap(FactMetaData::createMapFromJsonFile(
52
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
53
          this /* QObject parent */)),
54
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
55 56 57 58
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
59
                                       _metaDataMap[minTileAreaKey],
60
                                       this /* QObject parent */)),
61
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
62
                              this /* QObject parent */)),
63 64
      _toManyTiles(false), _tiles(new QmlObjectListModel()),
      _state(STATE::IDLE) {
65 66 67
  init();
}

68 69
MeasurementArea::MeasurementArea(const MeasurementArea &other, QObject *parent)
    : GeoArea(other, parent),
70
      _metaDataMap(FactMetaData::createMapFromJsonFile(
71
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
72
          this /* QObject parent */)),
73
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
74 75 76 77
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
78
                                       _metaDataMap[minTileAreaKey],
79
                                       this /* QObject parent */)),
80
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
81
                              this /* QObject parent */)),
82 83
      _toManyTiles(other._toManyTiles), _tiles(new QmlObjectListModel()),
      _state(STATE::IDLE) {
84 85 86
  init();
  disableUpdate();

87 88 89 90 91
  _tileHeight = other._tileHeight;
  _tileWidth = other._tileWidth;
  _minTileAreaPercent = other._minTileAreaPercent;
  _showTiles = other._showTiles;

92
  if (other.ready()) {
93 94 95 96 97
    for (int i = 0; i < other._tiles->count(); ++i) {
      _tiles->append(
          qobject_cast<const MeasurementTile *>(other._tiles->operator[](i))
              ->clone(_tiles.get()));
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
98
    _indexMap = other._indexMap;
99 100 101 102 103
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
104 105
}

106 107
MeasurementArea &MeasurementArea::operator=(const MeasurementArea &other) {
  GeoArea::operator=(other);
108 109 110 111 112 113 114 115

  disableUpdate();
  _tileHeight = other._tileHeight;
  _tileWidth = other._tileWidth;
  _minTileAreaPercent = other._minTileAreaPercent;
  _showTiles = other._showTiles;

  if (other.ready()) {
116 117 118 119 120 121
    _tiles->clearAndDeleteContents();
    for (int i = 0; i < other._tiles->count(); ++i) {
      _tiles->append(
          qobject_cast<const MeasurementTile *>(other._tiles->operator[](i))
              ->clone(_tiles.get()));
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
122
    _indexMap = other._indexMap;
123
    _toManyTiles = other._toManyTiles;
124 125 126 127 128
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
129 130 131
  return *this;
}

132
MeasurementArea::~MeasurementArea() { _tiles->clearAndDeleteContents(); }
133

134 135
QString MeasurementArea::mapVisualQML() const {
  return QStringLiteral("MeasurementAreaMapVisual.qml");
136
  // return QStringLiteral("");
137 138
}

139 140
QString MeasurementArea::editorQML() const {
  return QStringLiteral("MeasurementAreaEditor.qml");
141 142
}

143 144 145
MeasurementArea *MeasurementArea::clone(QObject *parent) const {
  return new MeasurementArea(*this, parent);
}
146

147
Fact *MeasurementArea::tileHeight() { return &_tileHeight; }
148

149
Fact *MeasurementArea::tileWidth() { return &_tileWidth; }
150

151
Fact *MeasurementArea::minTileArea() { return &_minTileAreaPercent; }
152

153
Fact *MeasurementArea::showTiles() { return &_showTiles; }
154

155
QmlObjectListModel *MeasurementArea::tiles() { return _tiles.get(); }
156 157

const QmlObjectListModel *MeasurementArea::tiles() const {
158
  return _tiles.get();
159 160
}

161
int MeasurementArea::maxTiles() const { return MAX_TILES; }
162

163
bool MeasurementArea::ready() const { return this->_state == STATE::IDLE; }
164

165 166
bool MeasurementArea::measurementCompleted() const {
  if (ready()) {
167 168 169
    for (int i = 0; i < _tiles->count(); ++i) {
      const auto tile = qobject_cast<const MeasurementTile *>(_tiles->get(i));
      if (!qFuzzyCompare(tile->progress(), 100)) {
170 171 172 173 174 175 176 177 178
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}

179
bool MeasurementArea::saveToJson(QJsonObject &json) {
180
  if (ready()) {
181 182 183 184 185
    if (this->GeoArea::saveToJson(json)) {
      json[tileHeightKey] = _tileHeight.rawValue().toDouble();
      json[tileWidthName] = _tileWidth.rawValue().toDouble();
      json[minTileAreaKey] = _minTileAreaPercent.rawValue().toDouble();
      json[showTilesKey] = _showTiles.rawValue().toBool();
186
      json[areaTypeKey] = nameString;
187
      json[toManyTilesKey] = _toManyTiles;
188 189

      // save tiles
190 191 192 193 194 195 196 197
      QJsonArray jsonTileArray;
      for (int i = 0; i < _tiles->count(); ++i) {
        auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
        QJsonObject jsonTile;
        tile->saveToJson(jsonTile);
        jsonTileArray.append(jsonTile);
      }
      json[tileArrayKey] = std::move(jsonTileArray);
198

199 200 201 202 203
      return true;
    } else {
      qCDebug(MeasurementAreaLog)
          << "saveToJson(): error inside GeoArea::saveToJson().";
    }
204
  } else {
205
    qCDebug(MeasurementAreaLog) << "saveToJson(): not ready().";
206
  }
207
  return false;
208 209
}

210 211 212
bool MeasurementArea::loadFromJson(const QJsonObject &json,
                                   QString &errorString) {
  if (this->GeoArea::loadFromJson(json, errorString)) {
213 214 215
    disableUpdate();
    bool retVal = true;

216
    // load parameters necessary for tile calculation.
217
    if (!json.contains(tileHeightKey) || !json[tileHeightKey].isDouble()) {
218 219 220
      errorString.append(tr("Could not load tile height!\n"));
      retVal = false;
    } else {
221
      _tileHeight.setRawValue(json[tileHeightKey].toDouble());
222 223 224 225 226 227 228 229 230
    }

    if (!json.contains(tileWidthName) || !json[tileWidthName].isDouble()) {
      errorString.append(tr("Could not load tile width!\n"));
      retVal = false;
    } else {
      _tileWidth.setRawValue(json[tileWidthName].toDouble());
    }

231
    if (!json.contains(minTileAreaKey) || !json[minTileAreaKey].isDouble()) {
232 233 234
      errorString.append(tr("Could not load minimal tile area!\n"));
      retVal = false;
    } else {
235
      _minTileAreaPercent.setRawValue(json[minTileAreaKey].toDouble());
236 237
    }

238 239
    // load less important parameters
    if (json.contains(showTilesKey) || !json[showTilesKey].isBool()) {
240
      _showTiles.setRawValue(json[showTilesKey].toBool());
241 242
    }

243
    // load tiles
244
    bool tileError = false;
245 246
    if (json.contains(tileArrayKey) && json[tileArrayKey].isArray()) {

247
      QString e;
248 249 250
      _tiles->clearAndDeleteContents();

      for (auto &&jsonTile : json[tileArrayKey].toArray()) {
251

252 253 254 255
        auto tile = new MeasurementTile(this);

        if (tile->loadFromJson(jsonTile.toObject(), e)) {
          _tiles->append(tile);
256
        } else {
257 258 259
          tile->deleteLater();
          qCWarning(MeasurementAreaLog) << e;
          tileError = true;
260 261 262
          break;
        }
      }
263
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
264

265 266 267 268 269 270 271 272 273
    if (json.contains(toManyTilesKey) && json[toManyTilesKey].isBool()) {
      _toManyTiles = json[toManyTilesKey].toBool();
    } else {
      tileError = true;
    }

    if (!tileError) {
      this->_indexMap.clear();
      for (int i = 0; i < _tiles->count(); ++i) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
274

275 276 277 278 279 280 281 282 283 284 285 286
        auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
        auto it = _indexMap.find(tile->id());

        // find unique id
        if (it != _indexMap.end()) {
          auto newId = MeasurementTile::randomId();
          constexpr long counterMax = 1e6;
          unsigned long counter = 0;
          for (; counter <= counterMax; ++counter) {
            it = _indexMap.find(newId);
            if (it == _indexMap.end()) {
              break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
287
            } else {
288
              newId = MeasurementTile::randomId();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
289 290 291
            }
          }

292 293 294 295 296 297 298 299
          if (counter != counterMax) {
            tile->setId(newId);
            tile->setProgress(0.0);
          } else {
            qCritical() << "MeasurementArea::storeTiles(): not able to find "
                           "unique id!";
            continue;
          }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
300
        }
301 302

        _indexMap.insert(std::make_pair(tile->id(), i));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
303
      }
304
    } else {
305 306 307 308 309 310 311
      qCWarning(MeasurementAreaLog)
          << "Not able to load tiles. tileArrayKey missing or wrong type.";
      if (json.contains(tileArrayKey)) {
        qCWarning(MeasurementAreaLog)
            << "tile array type: " << json[tileArrayKey].type();
      }
      tileError = true;
312 313 314
    }

    // do update if error occurred.
315
    enableUpdate();
316
    if (tileError) {
317 318
      doUpdate();
    }
319 320 321 322 323 324 325

    return retVal;
  } else {
    return false;
  }
}

326 327 328
bool MeasurementArea::isCorrect() {
  if (GeoArea::isCorrect()) {
    if (ready()) {
329 330 331 332 333 334 335
      if (_tiles->count() > 0) {
        return true;
      } else {
        setErrorString(tr("Not able to create tiles. This indicates that the "
                          "tile parameters must be adjusted. Reducing the Min. "
                          "Area parameter might deliver the desired result."));
      }
336 337 338 339 340
    } else if (_toManyTiles) {
      setErrorString(
          tr("Calculation would yield to many tiles, please adjust the tile "
             "parameters to reduce the number of tiles."));
    } else
341 342 343
      setErrorString(
          tr("Measurement Area tile calculation in progess. Please wait."));
  }
344

345 346 347
  return false;
}

348
void MeasurementArea::updateProgress(const ProgressArray &array) {
349
  if (ready() && array.size() > 0) {
350
    bool anyChanges = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
351 352 353 354 355 356 357
    for (const auto &lp : array) {
      auto it = _indexMap.find(lp.id());
      if (it != _indexMap.end()) {
        int tileIndex = it->second;
        auto *tile = _tiles->value<MeasurementTile *>(tileIndex);
        if (!qFuzzyCompare(lp.progress(), tile->progress())) {
          tile->setProgress(lp.progress());
358 359 360 361 362 363
          anyChanges = true;
        }
      }
    }

    if (anyChanges) {
364 365 366 367
      emit progressChanged();
    }
  }
}
368 369 370

void MeasurementArea::randomProgress() {
  if (ready()) {
371

372
    std::srand(std::time(nullptr));
373

Valentin Platzgummer's avatar
Valentin Platzgummer committed
374 375
    ProgressArray progressArray;

376 377 378 379 380 381
    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = _tiles->value<MeasurementTile *>(i);
      Q_ASSERT(tile != nullptr);

      auto p = tile->progress();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
382
      p += std::rand() % 125;
383 384 385
      if (p > 100) {
        p = 100;
      }
386

Valentin Platzgummer's avatar
Valentin Platzgummer committed
387
      progressArray.append(LabeledProgress(p, tile->id()));
388 389
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
390
    updateProgress(progressArray);
391 392 393 394 395
  }
}

void MeasurementArea::resetProgress() {
  if (ready()) {
396 397 398 399 400 401 402 403 404 405 406
    bool anyChanges = false;

    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = _tiles->value<MeasurementTile *>(i);
      Q_ASSERT(tile != nullptr);

      if (!qFuzzyCompare(tile->progress(), 0)) {
        tile->setProgress(0);
        anyChanges = true;
      }
407 408
    }

409 410 411
    if (anyChanges) {
      emit progressChanged();
    }
412 413
  }
}
414

415
//!
416 417
//! \brief MeasurementArea::doUpdate
//! \pre MeasurementArea::deferUpdate must be called first, don't call
418
//! this function directly!
419
void MeasurementArea::doUpdate() {
420
  using namespace geometry;
421 422 423 424 425 426 427 428 429 430 431
  using namespace boost::units;

  auto start = std::chrono::high_resolution_clock::now();

  if (this->_state != STATE::UPDATEING && this->_state != STATE::STOP) {
    const auto height = this->_tileHeight.rawValue().toDouble() * si::meter;
    const auto width = this->_tileWidth.rawValue().toDouble() * si::meter;
    const auto tileArea = width * height;
    const auto totalArea = this->area() * si::meter * si::meter;
    const auto estNumTiles = totalArea / tileArea;
    // Check some conditions.
432 433 434 435
    if (long(std::ceil(estNumTiles.value())) >= MAX_TILES) {
      _toManyTiles = true;
    } else if (this->GeoArea::isCorrect()) {
      _toManyTiles = false;
436 437 438 439 440 441 442 443 444
      setState(STATE::UPDATEING);

      auto polygon = this->coordinateList();
      for (auto &v : polygon) {
        v.setAltitude(0);
      }
      const auto minArea =
          this->_minTileAreaPercent.rawValue().toDouble() / 100 * tileArea;
      auto *th = this->thread();
445

446 447 448
      auto future = QtConcurrent::run([polygon, th, height, width, minArea] {
        auto start = std::chrono::high_resolution_clock::now();

449
        TilePtr pData(new QmlObjectListModel());
450 451 452 453 454 455 456
        // Convert to ENU system.
        QGeoCoordinate origin = polygon.first();
        FPolygon polygonENU;
        areaToEnu(origin, polygon, polygonENU);
        std::vector<FPolygon> tilesENU;
        BoundingBox bbox;
        // Generate tiles.
457
        if (getTiles(polygonENU, height, width, minArea, tilesENU, bbox)) {
458 459
          // Convert to geo system.
          for (const auto &t : tilesENU) {
460
            auto geoTile = new MeasurementTile(pData.get());
461 462 463 464 465
            for (const auto &v : t.outer()) {
              QGeoCoordinate geoVertex;
              fromENU(origin, v, geoVertex);
              geoTile->push_back(geoVertex);
            }
466
            pData->append(geoTile);
467 468 469 470
          }
        }
        pData->moveToThread(th);

471
        qCDebug(MeasurementAreaLog)
472 473 474 475 476 477 478 479 480 481 482 483
            << "doUpdate(): update time: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(
                   std::chrono::high_resolution_clock::now() - start)
                   .count()
            << " ms";

        return pData;
      }); // QtConcurrent::run()

      this->_watcher.setFuture(future);
    }
  }
484
  qCDebug(MeasurementAreaLog)
485 486 487 488 489 490 491
      << "doUpdate(): execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

492
void MeasurementArea::deferUpdate() {
493
  if (this->_state == STATE::IDLE || this->_state == STATE::DEFERED) {
494
    qCDebug(MeasurementAreaLog) << "defereUpdate(): defer update.";
495
    if (this->_state == STATE::IDLE) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
496
      this->_indexMap.clear();
497 498 499
      this->_tiles->clearAndDeleteContents();
      emit tilesChanged();
      emit progressChanged();
500 501 502 503
    }
    this->setState(STATE::DEFERED);
    this->_timer.start(100);
  } else if (this->_state == STATE::UPDATEING) {
504
    qCDebug(MeasurementAreaLog) << "defereUpdate(): restart.";
505 506 507 508
    setState(STATE::RESTARTING);
  }
}

509
void MeasurementArea::storeTiles() {
510 511 512
  auto start = std::chrono::high_resolution_clock::now();

  if (this->_state == STATE::UPDATEING) {
513
    qCDebug(MeasurementAreaLog) << "storeTiles(): update.";
514

515 516 517 518 519 520 521
    _tiles->clearAndDeleteContents();
    this->_tiles = this->_watcher.result();
    this->_watcher.result().reset();
    QQmlEngine::setObjectOwnership(this->_tiles.get(),
                                   QQmlEngine::CppOwnership);

    // update tileMap
Valentin Platzgummer's avatar
Valentin Platzgummer committed
522
    this->_indexMap.clear();
523 524 525
    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
526
      auto it = _indexMap.find(tile->id());
527 528

      // find unique id
Valentin Platzgummer's avatar
Valentin Platzgummer committed
529
      if (it != _indexMap.end()) {
530
        auto newId = MeasurementTile::randomId();
531 532 533
        constexpr long counterMax = 1e6;
        unsigned long counter = 0;
        for (; counter <= counterMax; ++counter) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
534 535
          it = _indexMap.find(newId);
          if (it == _indexMap.end()) {
536 537
            break;
          } else {
538
            newId = MeasurementTile::randomId();
539 540 541 542 543 544 545 546 547 548 549 550 551
          }
        }

        if (counter != counterMax) {
          tile->setId(newId);
          tile->setProgress(0.0);
        } else {
          qCritical()
              << "MeasurementArea::storeTiles(): not able to find unique id!";
          continue;
        }
      }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
552
      _indexMap.insert(std::make_pair(tile->id(), i));
553 554
    }

555 556
    // This is expensive. Drawing tiles is expensive too.
    emit this->tilesChanged();
557
    emit progressChanged();
558 559
    setState(STATE::IDLE);
  } else if (this->_state == STATE::RESTARTING) {
560
    qCDebug(MeasurementAreaLog) << "storeTiles(): restart.";
561 562
    doUpdate();
  } else if (this->_state == STATE::STOP) {
563
    qCDebug(MeasurementAreaLog) << "storeTiles(): stop.";
564
  }
565
  qCDebug(MeasurementAreaLog)
566 567 568 569 570 571 572
      << "storeTiles() execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

573
void MeasurementArea::disableUpdate() {
574
  setState(STATE::STOP);
575 576 577
  this->_timer.stop();
}

578
void MeasurementArea::enableUpdate() {
579 580 581 582 583
  if (this->_state == STATE::STOP) {
    setState(STATE::IDLE);
  }
}

584
void MeasurementArea::init() {
585
  this->setObjectName(nameString);
586 587 588

  QQmlEngine::setObjectOwnership(this->_tiles.get(), QQmlEngine::CppOwnership);

589
  connect(&this->_tileHeight, &Fact::rawValueChanged, this,
590
          &MeasurementArea::deferUpdate);
591
  connect(&this->_tileWidth, &Fact::rawValueChanged, this,
592
          &MeasurementArea::deferUpdate);
593
  connect(&this->_minTileAreaPercent, &Fact::rawValueChanged, this,
594 595
          &MeasurementArea::deferUpdate);
  connect(this, &GeoArea::pathChanged, this, &MeasurementArea::deferUpdate);
596
  this->_timer.setSingleShot(true);
597
  connect(&this->_timer, &QTimer::timeout, this, &MeasurementArea::doUpdate);
598 599
  connect(&this->_watcher,
          &QFutureWatcher<std::unique_ptr<QmlObjectListModel>>::finished, this,
600
          &MeasurementArea::storeTiles);
601 602
}

603
void MeasurementArea::setState(MeasurementArea::STATE s) {
604 605 606 607 608 609 610 611
  if (this->_state != s) {
    auto oldState = this->_state;
    this->_state = s;
    if (s == STATE::IDLE || oldState == STATE::IDLE) {
      emit readyChanged();
    }
  }
}
612

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
bool getTiles(const FPolygon &area, Length tileHeight, Length tileWidth,
              Area minTileArea, std::vector<FPolygon> &tiles,
              BoundingBox &bbox) {
  if (area.outer().empty() || area.outer().size() < 4) {
    qCDebug(MeasurementAreaLog) << "Area has to few vertices.";
    return false;
  }

  if (tileWidth <= 0 * bu::si::meter || tileHeight <= 0 * bu::si::meter ||
      minTileArea < 0 * bu::si::meter * bu::si::meter) {
    std::stringstream ss;
    ss << "Parameters tileWidth (" << tileWidth << "), tileHeight ("
       << tileHeight << "), minTileArea (" << minTileArea
       << ") must be positive.";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  if (bbox.corners.outer().size() != 5) {
    bbox.corners.clear();
    minimalBoundingBox(area, bbox);
  }

636
  if (bbox.corners.outer().size() < 5) {
637
    return false;
638 639
  }

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  double bboxWidth = bbox.width;
  double bboxHeight = bbox.height;
  FPoint origin = bbox.corners.outer()[0];

  // cout << "Origin: " << origin[0] << " " << origin[1] << endl;
  // Transform _mArea polygon to bounding box coordinate system.
  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate(
      bbox.angle * 180 / M_PI);
  trans::translate_transformer<double, 2, 2> translate(-origin.get<0>(),
                                                       -origin.get<1>());
  FPolygon translated_polygon;
  FPolygon rotated_polygon;
  boost::geometry::transform(area, translated_polygon, translate);
  boost::geometry::transform(translated_polygon, rotated_polygon, rotate);
  bg::correct(rotated_polygon);
  // cout << bg::wkt<BoostPolygon2D>(rotated_polygon) << endl;

  size_t iMax = ceil(bboxWidth / tileWidth.value());
  size_t jMax = ceil(bboxHeight / tileHeight.value());

  if (iMax < 1 || jMax < 1) {
    std::stringstream ss;
    ss << "Tile width (" << tileWidth << ") or tile height (" << tileHeight
       << ") to large for measurement area.";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate_back(
      -bbox.angle * 180 / M_PI);
  trans::translate_transformer<double, 2, 2> translate_back(origin.get<0>(),
                                                            origin.get<1>());
  for (size_t i = 0; i < iMax; ++i) {
    double x_min = tileWidth.value() * i;
    double x_max = x_min + tileWidth.value();
    for (size_t j = 0; j < jMax; ++j) {
      double y_min = tileHeight.value() * j;
      double y_max = y_min + tileHeight.value();

      FPolygon tile_unclipped;
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});

      std::deque<FPolygon> boost_tiles;
      if (!boost::geometry::intersection(tile_unclipped, rotated_polygon,
                                         boost_tiles))
        continue;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
691
      for (FPolygon &t : boost_tiles) {
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
        if (bg::area(t) > minTileArea.value()) {
          // Transform boost_tile to world coordinate system.
          FPolygon rotated_tile;
          FPolygon translated_tile;
          boost::geometry::transform(t, rotated_tile, rotate_back);
          boost::geometry::transform(rotated_tile, translated_tile,
                                     translate_back);

          // Store tile and calculate center point.
          tiles.push_back(translated_tile);
        }
      }
    }
  }

  if (tiles.size() < 1) {
    std::stringstream ss;
    ss << "No tiles calculated. Is the minTileArea (" << minTileArea
       << ") parameter large enough?";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  return true;
}
717 718 719 720 721 722 723 724 725 726 727

QString randomId() {
  std::srand(std::time(nullptr));
  std::int64_t r = 0;

  for (int i = 0; i < 10; ++i) {
    r ^= std::rand();
  }

  return QString::number(r);
}