AreaData.cc 14.4 KB
Newer Older
1
#include "AreaData.h"
2

3 4
#include "geometry/MeasurementArea.h"
#include "geometry/SafeArea.h"
5
#include "geometry/snake.h"
6

7
#include "JsonHelper.h"
8
#include "QGCApplication.h"
9 10
#include "QGCLoggingCategory.h"
#include "QGCQGeoCoordinate.h"
11

12
QGC_LOGGING_CATEGORY(AreaDataLog, "AreaDataLog")
13

14
const char *originKey = "Origin";
15 16
const char *areaListKey = "AreaList";
const char *initializedKey = "Initialized";
17

18
AreaData::AreaData(QObject *parent) : QObject(parent) {}
19

20
AreaData::~AreaData() {}
21

22 23 24
AreaData::AreaData(const AreaData &other, QObject *parent)
    : QObject(parent), _initialized(false), _showErrorMessages(true) {
  *this = other;
25 26
}

27
AreaData &AreaData::operator=(const AreaData &other) {
28 29 30 31 32 33 34
  this->clear();

  // Clone elements.
  for (int i = 0; i < other._areaList.count(); ++i) {
    auto obj = other._areaList[i];
    auto area = qobject_cast<const GeoArea *>(obj);
    this->insert(area->clone(this));
35
  }
36 37 38 39

  _origin = other._origin;
  _initialized = other._initialized;

40
  return *this;
41 42
}

43
bool AreaData::insert(GeoArea *areaData) {
44 45 46
  if (areaData != nullptr) {
    if (Q_LIKELY(!this->_areaList.contains(areaData))) {
      _areaList.append(areaData);
47
      emit areaListChanged();
48 49 50 51 52 53 54

      auto *measurementArea = qobject_cast<MeasurementArea *>(areaData);
      if (measurementArea != nullptr) {
        connect(measurementArea, &MeasurementArea::centerChanged, this,
                &AreaData::_updateOrigin);
        _setOrigin(measurementArea->center());
      }
55
      return true;
56
    }
57 58
  }

59
  return false;
60 61
}

62 63 64 65
void AreaData::remove(GeoArea *areaData) {
  int index = _areaList.indexOf(areaData);
  if (index >= 0) {
    QObject *obj = _areaList.removeAt(index);
66

67 68 69 70 71 72
    auto *measurementArea = qobject_cast<MeasurementArea *>(areaData);
    if (measurementArea != nullptr) {
      disconnect(measurementArea, &MeasurementArea::centerChanged, this,
                 &AreaData::_updateOrigin);
      _setOrigin(QGeoCoordinate());
    }
73

74
    if (obj->parent() == nullptr || obj->parent() == this) {
75
      obj->deleteLater();
76 77
    }

78 79
    emit areaListChanged();
  }
80 81
}

82 83
void AreaData::clear() {
  if (_areaList.count() > 0) {
84 85
    while (_areaList.count() > 0) {
      remove(_areaList.value<GeoArea *>(0));
86 87 88
    }
    emit areaListChanged();
  }
89
  _errorString.clear();
90 91
}

92
QmlObjectListModel *AreaData::areaList() { return &_areaList; }
93

94
const QmlObjectListModel *AreaData::areaList() const { return &_areaList; }
95

96
QGeoCoordinate AreaData::origin() const { return _origin; }
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
bool AreaData::isCorrect() {
  if (!initialized()) {
    qCWarning(AreaDataLog) << "isCorrect(): not initialized";
    return false;
  }

  // Check if areas are correct
  if (!_areasCorrect()) {
    return false;
  }

  // Check if areas where added.
  MeasurementArea *measurementArea = nullptr;
  SafeArea *safeArea = nullptr;
  if (!_getAreas(&measurementArea, &safeArea)) {
    return false;
  }
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  // Check if measurement area is covered by safe area.
  if (!_origin.isValid()) {
    qCWarning(AreaDataLog) << "isCorrect(): origin invalid";
    return false;
  }
  const auto &origin = this->origin();
  snake::FPolygon safeAreaENU;
  snake::areaToEnu(origin, safeArea->pathModel(), safeAreaENU);
  snake::FPolygon measurementAreaENU;
  snake::areaToEnu(origin, measurementArea->pathModel(), measurementAreaENU);
  //  qDebug() << "origin" << origin;
  //  std::stringstream ss;
  //  ss << "measurementAreaENU: " << bg::wkt(measurementAreaENU) << std::endl;
  //  ss << "safeAreaENU: " << bg::wkt(safeAreaENU) << std::endl;
  //  qDebug() << ss.str().c_str();
  if (!bg::covered_by(measurementAreaENU, safeAreaENU)) {
    _processError(tr("Measurement Area not inside Safe Area. Please adjust "
                     "the Measurement Area."));
    return false;
  }
136 137

  _initialized = true;
138 139 140 141 142 143 144 145 146 147 148
  return true;
}

bool AreaData::initialize(const QGeoCoordinate &bottomLeft,
                          const QGeoCoordinate &topRight) {
  // bottomLeft and topRight define the bounding box.
  if (bottomLeft.isValid() && topRight.isValid() && bottomLeft != topRight) {
    auto *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
    auto *safeArea = getGeoArea<SafeArea *>(_areaList);

    if (safeArea == nullptr) {
149 150 151
      safeArea = new SafeArea(this);
      if (!insert(safeArea)) {
        safeArea->deleteLater();
152 153 154 155 156
        qCCritical(AreaDataLog)
            << "initialize(): safeArea == nullptr, but insert() failed.";
        return false;
      }
    }
157

158
    if (measurementArea == nullptr) {
159 160 161
      measurementArea = new MeasurementArea(this);
      if (!insert(measurementArea)) {
        measurementArea->deleteLater();
162 163 164 165 166
        qCCritical(AreaDataLog) << "initialize(): measurementArea == nullptr, "
                                   "but insert() failed.";
        return false;
      }
    }
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    // Fit safe area to bounding box.
    safeArea->clear();
    safeArea->appendVertex(bottomLeft);
    safeArea->appendVertex(
        QGeoCoordinate(topRight.latitude(), bottomLeft.longitude()));
    safeArea->appendVertex(topRight);
    safeArea->appendVertex(
        QGeoCoordinate(bottomLeft.latitude(), topRight.longitude()));

    // Put measurement area inside safeArea;
    measurementArea->clear();
    measurementArea->appendVertex(QGeoCoordinate(
        0.8 * bottomLeft.latitude() + 0.2 * topRight.latitude(),
        0.8 * bottomLeft.longitude() + 0.2 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.2 * bottomLeft.latitude() + 0.8 * topRight.latitude(),
        0.8 * bottomLeft.longitude() + 0.2 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.2 * bottomLeft.latitude() + 0.8 * topRight.latitude(),
        0.2 * bottomLeft.longitude() + 0.8 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.8 * bottomLeft.latitude() + 0.2 * topRight.latitude(),
        0.2 * bottomLeft.longitude() + 0.8 * topRight.longitude()));
191 192 193 194 195 196 197 198 199

    // Set depot
    safeArea->setDepot(QGeoCoordinate(
        safeArea->vertexCoordinate(0).latitude() * 0.5 +
            measurementArea->vertexCoordinate(0).latitude() * 0.5,
        safeArea->vertexCoordinate(0).longitude() * 0.5 +
            measurementArea->vertexCoordinate(0).longitude() * 0.5));

    _initialized = true;
200 201 202 203 204 205 206 207
    return true;
  } else {
    qCWarning(AreaDataLog)
        << "initialize(): bounding box invaldid (bottomLeft, topRight) "
        << bottomLeft << "," << topRight;
    return false;
  }
}
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 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
bool AreaData::initialized() { return _initialized; }

void AreaData::intersection() {
  if (initialized() && _areasCorrect()) {
    MeasurementArea *measurementArea = nullptr;
    SafeArea *safeArea = nullptr;
    if (_getAreas(&measurementArea, &safeArea)) {

      // convert to ENU
      const auto origin = this->origin();
      snake::FPolygon safeAreaENU;
      snake::areaToEnu(origin, safeArea->pathModel(), safeAreaENU);
      snake::FPolygon measurementAreaENU;
      snake::areaToEnu(origin, measurementArea->pathModel(),
                       measurementAreaENU);

      // do intersection
      std::deque<snake::FPolygon> outputENU;
      boost::geometry::intersection(measurementAreaENU, safeAreaENU, outputENU);

      if (outputENU.size() < 1 || outputENU[0].outer().size() < 4) {
        _processError(
            "Intersection did't deliver any result. Measurement Area and "
            "Safe Area must touch each other.");
        return;
      }

      if (outputENU[0].inners().size() > 0 || outputENU.size() > 1) {
        _processError(
            "Hint: Only simple polygons can be displayed. If Intersection"
            "produces polygons with holes or multi polygons, only "
            "partial information can be displayed.");
      }

      // Shrink the result if safeAreaENU doesn't cover it.
      auto large = std::move(outputENU[0]);
      snake::FPolygon small;
      while (!bg::covered_by(large, safeAreaENU)) {
        snake::offsetPolygon(large, small, -0.1);
        large = std::move(small);
        qDebug() << "intersection(): shrink";
      }

      // Convert.
      measurementArea->clear();
      for (auto it = large.outer().begin(); it != large.outer().end() - 1;
           ++it) {
        QGeoCoordinate c;
        snake::fromENU(origin, *it, c);
        measurementArea->appendVertex(c);
      }
    }
  }
262 263 264
}

bool AreaData::operator==(const AreaData &other) const {
265 266 267 268 269 270 271 272 273 274
  if (_areaList.count() == other._areaList.count()) {
    for (int i = 0; i < _areaList.count(); ++i) {
      if (_areaList[i] != other._areaList[i]) {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
275 276 277 278 279
}
bool AreaData::operator!=(const AreaData &other) const {
  return !(*this == other);
}

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
bool AreaData::load(const QJsonObject &obj, QString &errorString) {
  bool returnValue = true;

  // load initialized.
  {
    QString e;
    QList<JsonHelper::KeyValidateInfo> keyInfo = {
        {initializedKey, QJsonValue::Bool, true},
    };
    if (JsonHelper::validateKeys(obj, keyInfo, e)) {
      _initialized = obj[initializedKey].toBool();
    } else {
      returnValue = false;
      errorString.append(e);
      errorString.append("\n");
    }
  }

  // load areaList.
  {
    QString e;
    QList<JsonHelper::KeyValidateInfo> keyInfo = {
        {areaListKey, QJsonValue::Array, true},
    };
    if (JsonHelper::validateKeys(obj, keyInfo, e)) {
      this->clear();
      // iterate over json array
307
      for (const auto &jsonArea : obj[areaListKey].toArray()) {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        // check if area type key is present
        QList<JsonHelper::KeyValidateInfo> areaInfo = {
            {GeoArea::areaTypeKey, QJsonValue::String, true},
        };
        if (!JsonHelper::validateKeys(jsonArea, areaInfo, e)) {
          // load MeasurementArea
          if (jsonArea[GeoArea::areaTypeKey] == MeasurementArea::name) {
            auto area = getGeoArea<MeasurementArea *>(_areaList);
            if (area == nullptr) {
              auto area = new MeasurementArea(this);
              if (area->loadFromJson(jsonArea, e)) {
                this->insert(area);
              } else {
                returnValue = false;
                errorString.append(e);
                errorString.append("\n");
                area->deleteLater();
              }
            } else {
              returnValue = false;
              errorString.append(
                  tr("Multiple Measurement Areas detected. Area was ignored."));
            }
          }
          // load SafeArea
          else if (jsonArea[GeoArea::areaTypeKey] == SafeArea::name) {
            auto area = getGeoArea<SafeArea *>(_areaList);
            if (area == nullptr) {
              auto area = new SafeArea(this);
              if (area->loadFromJson(jsonArea, e)) {
                this->insert(area);
              } else {
                returnValue = false;
                errorString.append(e);
                errorString.append("\n");
                area->deleteLater();
              }
            } else {
              returnValue = false;
              errorString.append(
                  tr("Multiple Safe Areas detected. Area was ignored."));
            }
          }
          // unknown area
          else {
            returnValue = false;
            errorString.append(tr("Unknown area type: ") +
                               jsonArea[GeoArea::areaTypeKey]);
          }
        }
        // GeoArea::areaTypeKey missing
        else {
          returnValue = false;
          errorString.append(e);
          errorString.append("\n");
        }
      }
    }
    // AreaList missing
    else {
      returnValue = false;
      errorString.append(e);
      errorString.append("\n");
    }
  }

  // load origin
  {
    QString e;
    QList<JsonHelper::KeyValidateInfo> keyInfo = {
        {originKey, QJsonValue::Object, true},
    };
    if (JsonHelper::validateKeys(obj, keyInfo, e)) {
      QGeoCoordinate origin;
      if (JsonHelper::loadGeoCoordinate(obj[originKey], false, origin, e)) {
        _origin = origin;
      }
    }
  }

  // check if this is correct.
  if (!this->isCorrect()) {
    returnValue = false;
  }

  return returnValue;
394 395
}

396 397 398 399 400
bool AreaData::save(QJsonObject &obj) {
  QJsonObject temp;

  QJsonValue jsonOrigin;
  JsonHelper::saveGeoCoordinate(_origin, true, jsonOrigin);
401
  temp[originKey] = jsonOrigin;
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  temp[initializedKey] = _initialized;

  QJsonArray jsonAreaList;
  for (int i = 0; i < _areaList.count(); ++i) {
    auto qobj = _areaList[i];
    auto area = qobject_cast<GeoArea *>(qobj);
    QJsonObject jsonArea;
    if (area->saveToJson(jsonArea)) {
      jsonAreaList.append(jsonArea);
    } else {
      qDebug(AreaDataLog) << "save(): not able to save area: "
                          << area->objectName();
      _processError(tr("Not able to save area: ") + area->objectName());
      return false;
    }
  }
  temp[areaListKey] = jsonAreaList;

  obj = std::move(temp);
421 422 423
  return true;
}

424
void AreaData::_setOrigin(const QGeoCoordinate &origin) {
425 426 427 428 429
  if (this->_origin != origin) {
    this->_origin = origin;
    emit originChanged();
  }
}
430

431 432 433 434 435 436
void AreaData::_processError(const QString &str) {
  this->_errorString = str;
  emit error();
  if (_showErrorMessages) {
    qgcApp()->informationMessageBoxOnMainThread(tr("Area Editor"),
                                                this->errorString());
437
  }
438
}
439

440 441 442 443 444 445 446
bool AreaData::_areasCorrect() {
  // Check if areas are correct.
  for (int i = 0; i < _areaList.count(); ++i) {
    auto *area = _areaList.value<GeoArea *>(0);
    if (!area->isCorrect()) {
      _processError(area->errorString());
      return false;
447 448 449
    }
  }

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
  return true;
}

bool AreaData::_getAreas(MeasurementArea **measurementArea,
                         SafeArea **safeArea) {
  *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
  if (*measurementArea == nullptr) {
    _processError(
        tr("Measurement Area missing. Please define a measurement area."));
    return false;
  }
  *safeArea = getGeoArea<SafeArea *>(_areaList);
  if (*safeArea == nullptr) {
    _processError(tr("Safe Area missing. Please define a safe area."));
    return false;
  }

  return true;
468
}
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

void AreaData::setShowErrorMessages(bool showErrorMessages) {
  if (showErrorMessages != _showErrorMessages) {
    _showErrorMessages = showErrorMessages;
    emit showErrorMessagesChanged();
  }
}

void AreaData::_updateOrigin() {
  auto *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
  if (measurementArea != nullptr) {
    _setOrigin(measurementArea->center());
  }
}

bool AreaData::showErrorMessages() const { return _showErrorMessages; }

QString AreaData::errorString() const { return _errorString; }