geometry.cpp 17.3 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 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 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 269 270 271 272 273 274 275 276 277 278 279 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 307 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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
#include <algorithm>
#include <iostream>

#include "geometry.h"

#include <mapbox/geometry.hpp>
#include <mapbox/polylabel.hpp>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/adapted/boost_tuple.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/polygon.hpp>

#include "clipper/clipper.hpp"
#define CLIPPER_SCALE 1000000

#ifndef NDEBUG
//#define SNAKE_SHOW_TIME
#endif

namespace bg = boost::geometry;
namespace trans = bg::strategy::transform;

BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(bg::cs::cartesian)

namespace geometry {
static const IntType stdScale = 1000000;
//=========================================================================
// Geometry stuff.
//=========================================================================

void polygonCenter(const FPolygon &polygon, FPoint &center) {
  using namespace mapbox;
  if (polygon.outer().empty())
    return;
  mapbox::geometry::polygon<double> p;
  mapbox::geometry::linear_ring<double> lr1;
  for (size_t i = 0; i < polygon.outer().size(); ++i) {
    mapbox::geometry::point<double> vertex(polygon.outer()[i].get<0>(),
                                           polygon.outer()[i].get<1>());
    lr1.push_back(vertex);
  }
  p.push_back(lr1);
  mapbox::geometry::point<double> c = polylabel(p);

  center.set<0>(c.x);
  center.set<1>(c.y);
}

bool minimalBoundingBox(const FPolygon &polygon, BoundingBox &minBBox) {
  /*
  Find the minimum-area bounding box of a set of 2D points

  The input is a 2D convex hull, in an Nx2 numpy array of x-y co-ordinates.
  The first and last points points must be the same, making a closed polygon.
  This program finds the rotation angles of each edge of the convex polygon,
  then tests the area of a bounding box aligned with the unique angles in
  90 degrees of the 1st Quadrant.
  Returns the

  Tested with Python 2.6.5 on Ubuntu 10.04.4 (original version)
  Results verified using Matlab

  Copyright (c) 2013, David Butterworth, University of Queensland
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of the Willow Garage, Inc. nor the names of its
        contributors may be used to endorse or promote products derived from
        this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
  */

  if (polygon.outer().empty() || polygon.outer().size() < 3)
    return false;
  FPolygon convex_hull;
  bg::convex_hull(polygon, convex_hull);

  // cout << "Convex hull: " << bg::wkt<BoostPolygon2D>(convex_hull) << endl;

  //# Compute edges (x2-x1,y2-y1)
  std::vector<FPoint> edges;
  const auto &convex_hull_outer = convex_hull.outer();
  for (long i = 0; i < long(convex_hull_outer.size()) - 1; ++i) {
    FPoint p1 = convex_hull_outer.at(i);
    FPoint p2 = convex_hull_outer.at(i + 1);
    double edge_x = p2.get<0>() - p1.get<0>();
    double edge_y = p2.get<1>() - p1.get<1>();
    edges.push_back(FPoint{edge_x, edge_y});
  }

  //    cout << "Edges: ";
  //    for (auto e : edges)
  //        cout << e.get<0>() << " " << e.get<1>() << ",";
  //    cout << endl;

  // Calculate unique edge angles  atan2(y/x)
  double angle_scale = 1e3;
  std::set<long> angles_long;
  for (auto vertex : edges) {
    double angle = std::fmod(atan2(vertex.get<1>(), vertex.get<0>()), M_PI / 2);
    angle =
        angle < 0 ? angle + M_PI / 2 : angle; // want strictly positive answers
    angles_long.insert(long(round(angle * angle_scale)));
  }
  std::vector<double> edge_angles;
  for (auto a : angles_long)
    edge_angles.push_back(double(a) / angle_scale);

  //    cout << "Unique angles: ";
  //    for (auto e : edge_angles)
  //        cout << e*180/M_PI << ",";
  //    cout << endl;

  double min_area = std::numeric_limits<double>::infinity();
  // Test each angle to find bounding box with smallest area
  // print "Testing", len(edge_angles), "possible rotations for bounding box...
  // \n"
  for (double angle : edge_angles) {

    trans::rotate_transformer<bg::degree, double, 2, 2> rotate(angle * 180 /
                                                               M_PI);
    FPolygon hull_rotated;
    bg::transform(convex_hull, hull_rotated, rotate);
    // cout << "Convex hull rotated: " << bg::wkt<BoostPolygon2D>(hull_rotated)
    // << endl;

    bg::model::box<FPoint> box;
    bg::envelope(hull_rotated, box);
    //        cout << "Bounding box: " <<
    //        bg::wkt<bg::model::box<BoostPoint2D>>(box) << endl;

    //# print "Rotated hull points are \n", rot_points
    FPoint min_corner = box.min_corner();
    FPoint max_corner = box.max_corner();
    double min_x = min_corner.get<0>();
    double max_x = max_corner.get<0>();
    double min_y = min_corner.get<1>();
    double max_y = max_corner.get<1>();
    //        cout << "min_x: " << min_x << endl;
    //        cout << "max_x: " << max_x << endl;
    //        cout << "min_y: " << min_y << endl;
    //        cout << "max_y: " << max_y << endl;

    // Calculate height/width/area of this bounding rectangle
    double width = max_x - min_x;
    double height = max_y - min_y;
    double area = width * height;
    //        cout << "Width: " << width << endl;
    //        cout << "Height: " << height << endl;
    //        cout << "area: " << area << endl;
    //        cout << "angle: " << angle*180/M_PI << endl;

    // Store the smallest rect found first (a simple convex hull might have 2
    // answers with same area)
    if (area < min_area) {
      min_area = area;
      minBBox.angle = angle;
      minBBox.width = width;
      minBBox.height = height;

      minBBox.corners.clear();
      minBBox.corners.outer().push_back(FPoint{min_x, min_y});
      minBBox.corners.outer().push_back(FPoint{min_x, max_y});
      minBBox.corners.outer().push_back(FPoint{max_x, max_y});
      minBBox.corners.outer().push_back(FPoint{max_x, min_y});
      minBBox.corners.outer().push_back(FPoint{min_x, min_y});
    }
    // cout << endl << endl;
  }

  // Transform corners of minimal bounding box.
  trans::rotate_transformer<bg::degree, double, 2, 2> rotate(-minBBox.angle *
                                                             180 / M_PI);
  FPolygon rotated_polygon;
  bg::transform(minBBox.corners, rotated_polygon, rotate);
  minBBox.corners = rotated_polygon;

  return true;
}

void offsetPolygon(const FPolygon &polygon, FPolygon &polygonOffset,
                   double offset) {
  bg::strategy::buffer::distance_symmetric<double> distance_strategy(offset);
  bg::strategy::buffer::join_miter join_strategy(3);
  bg::strategy::buffer::end_flat end_strategy;
  bg::strategy::buffer::point_square point_strategy;
  bg::strategy::buffer::side_straight side_strategy;

  bg::model::multi_polygon<FPolygon> result;

  bg::buffer(polygon, result, distance_strategy, side_strategy, join_strategy,
             end_strategy, point_strategy);

  if (result.size() > 0)
    polygonOffset = result[0];
}

void graphFromPolygon(const FPolygon &polygon, const FLineString &vertices,
                      Matrix<double> &graph) {
  size_t n = graph.n();

  for (size_t i = 0; i < n; ++i) {
    FPoint v1 = vertices[i];
    for (size_t j = i + 1; j < n; ++j) {
      FPoint v2 = vertices[j];
      FLineString path{v1, v2};

      double distance = 0;
      if (!bg::within(path, polygon))
        distance = std::numeric_limits<double>::infinity();
      else
        distance = bg::length(path);
      graph(i, j) = distance;
      graph(j, i) = distance;
    }
  }
}

bool toDistanceMatrix(Matrix<double> &graph) {
  size_t n = graph.n();

  auto distance = [&graph](size_t i, size_t j) -> double {
    return graph(i, j);
  };

  for (size_t i = 0; i < n; ++i) {
    for (size_t j = i + 1; j < n; ++j) {
      double d = graph(i, j);
      if (!std::isinf(d))
        continue;
      std::vector<size_t> path;
      if (!dijkstraAlgorithm(n, i, j, path, d, distance)) {
        return false;
      }
      //            cout << "(" << i << "," << j << ") d: " << d << endl;
      //            cout << "Path size: " << path.size() << endl;
      //            for (auto idx : path)
      //                cout << idx << " ";
      //            cout << endl;
      graph(i, j) = d;
      graph(j, i) = d;
    }
  }
  return true;
}

bool joinedArea(const FPolygon &mArea, const FPolygon &sArea,
                const FPolygon &corridor, FPolygon &jArea,
                std::string &errorString) {
  // Measurement area and service area overlapping?
  bool overlapingSerMeas = bg::intersects(mArea, sArea) ? true : false;
  bool corridorValid = corridor.outer().size() > 0 ? true : false;

  // Check if corridor is connecting measurement area and service area.
  bool corridor_is_connection = false;
  if (corridorValid) {
    // Corridor overlaping with measurement area?
    if (bg::intersects(corridor, mArea)) {
      // Corridor overlaping with service area?
      if (bg::intersects(corridor, sArea)) {
        corridor_is_connection = true;
      }
    }
  }

  // Are areas joinable?
  std::deque<FPolygon> sol;
  FPolygon partialArea = mArea;
  if (overlapingSerMeas) {
    if (corridor_is_connection) {
      bg::union_(partialArea, corridor, sol);
    }
  } else if (corridor_is_connection) {
    bg::union_(partialArea, corridor, sol);
  } else {
    std::stringstream ss;
    auto printPoint = [&ss](const FPoint &p) {
      ss << " (" << p.get<0>() << ", " << p.get<1>() << ")";
    };
    ss << "Areas are not overlapping." << std::endl;
    ss << "Measurement area:";
    bg::for_each_point(mArea, printPoint);
    ss << std::endl;
    ss << "Service area:";
    bg::for_each_point(sArea, printPoint);
    ss << std::endl;
    ss << "Corridor:";
    bg::for_each_point(corridor, printPoint);
    ss << std::endl;
    errorString = ss.str();
    return false;
  }

  if (sol.size() > 0) {
    partialArea = sol[0];
    sol.clear();
  }

  // Join areas.
  bg::union_(partialArea, sArea, sol);

  if (sol.size() > 0) {
    jArea = sol[0];
  } else {
    std::stringstream ss;
    auto printPoint = [&ss](const FPoint &p) {
      ss << " (" << p.get<0>() << ", " << p.get<1>() << ")";
    };
    ss << "Areas not joinable." << std::endl;
    ss << "Measurement area:";
    bg::for_each_point(mArea, printPoint);
    ss << std::endl;
    ss << "Service area:";
    bg::for_each_point(sArea, printPoint);
    ss << std::endl;
    ss << "Corridor:";
    bg::for_each_point(corridor, printPoint);
    ss << std::endl;
    errorString = ss.str();
    return false;
  }

  return true;
}

bool joinedArea(const std::vector<FPolygon *> &areas, FPolygon &joinedArea) {
  if (areas.size() < 1)
    return false;
  joinedArea = *areas[0];
  std::deque<std::size_t> idxList;
  for (size_t i = 1; i < areas.size(); ++i)
    idxList.push_back(i);

  std::deque<FPolygon> sol;
  while (idxList.size() > 0) {
    bool success = false;
    for (auto it = idxList.begin(); it != idxList.end(); ++it) {
      bg::union_(joinedArea, *areas[*it], sol);
      if (sol.size() > 0) {
        joinedArea = sol[0];
        sol.clear();
        idxList.erase(it);
        success = true;
        break;
      }
    }
    if (!success)
      return false;
  }

  return true;
}

BoundingBox::BoundingBox() : width(0), height(0), angle(0) {}

void BoundingBox::clear() {
  width = 0;
  height = 0;
  angle = 0;
  corners.clear();
}

FPoint int2Float(const IPoint &ip) { return int2Float(ip, stdScale); }

FPoint int2Float(const IPoint &ip, IntType scale) {
  return FPoint{FloatType(ip.get<0>()) / scale, FloatType(ip.get<1>()) / scale};
}

IPoint float2Int(const FPoint &ip) { return float2Int(ip, stdScale); }

IPoint float2Int(const FPoint &ip, IntType scale) {
  return IPoint{IntType(std::llround(ip.get<0>() * scale)),
                IntType(std::llround(ip.get<1>() * scale))};
}

bool dijkstraAlgorithm(size_t numElements, size_t startIndex, size_t endIndex,
                       std::vector<size_t> &elementPath, double &length,
                       std::function<double(size_t, size_t)> distanceDij) {
  if (startIndex >= numElements || endIndex >= numElements) {
    length = std::numeric_limits<double>::infinity();
    return false;
  } else if (endIndex == startIndex) {
    length = 0;
    elementPath.push_back(startIndex);
    return true;
  }

  // Node struct
  // predecessorIndex is the index of the predecessor node
  // (nodeList[predecessorIndex]) distance is the distance between the node and
  // the start node node number is stored by the position in nodeList
  struct Node {
    std::size_t predecessorIndex = std::numeric_limits<std::size_t>::max();
    double distance = std::numeric_limits<double>::infinity();
  };

  // The list with all Nodes (elements)
  std::vector<Node> nodeList(numElements);
  // This list will be initalized with indices referring to the elements of
  // nodeList. Elements will be successively remove during the execution of the
  // Dijkstra Algorithm.
  std::vector<size_t> workingSet(numElements);

  // append elements to node list
  for (size_t i = 0; i < numElements; ++i)
    workingSet[i] = i;

  nodeList[startIndex].distance = 0;

  // Dijkstra Algorithm
  // https://de.wikipedia.org/wiki/Dijkstra-Algorithmus
  while (workingSet.size() > 0) {
    // serach Node with minimal distance
    auto minDist = std::numeric_limits<double>::infinity();
    std::size_t minDistIndex_WS =
        std::numeric_limits<std::size_t>::max(); // WS = workinSet
    for (size_t i = 0; i < workingSet.size(); ++i) {
      const auto nodeIndex = workingSet.at(i);
      const auto dist = nodeList.at(nodeIndex).distance;
      if (dist < minDist) {
        minDist = dist;
        minDistIndex_WS = i;
      }
    }
    if (minDistIndex_WS == std::numeric_limits<std::size_t>::max())
      return false;

    size_t indexU_NL = workingSet.at(minDistIndex_WS); // NL = nodeList
    workingSet.erase(workingSet.begin() + minDistIndex_WS);
    if (indexU_NL == endIndex) // shortest path found
      break;

    const auto distanceU = nodeList.at(indexU_NL).distance;
    // update distance
    for (size_t i = 0; i < workingSet.size(); ++i) {
      auto indexV_NL = workingSet[i]; // NL = nodeList
      Node *v = &nodeList[indexV_NL];
      auto dist = distanceDij(indexU_NL, indexV_NL);
      // is ther an alternative path which is shorter?
      auto alternative = distanceU + dist;
      if (alternative < v->distance) {
        v->distance = alternative;
        v->predecessorIndex = indexU_NL;
      }
    }
  }
  // end Djikstra Algorithm

  // reverse assemble path
  auto e = endIndex;
  length = nodeList[e].distance;
  while (true) {
    if (e == std::numeric_limits<std::size_t>::max()) {
      if (elementPath.size() > 0 &&
          elementPath[0] == startIndex) { // check if starting point was reached
        break;
      } else { // some error
        length = std::numeric_limits<double>::infinity();
        elementPath.clear();
        return false;
      }
    } else {
      elementPath.insert(elementPath.begin(), e);
      // Update Node
      e = nodeList[e].predecessorIndex;
    }
  }
  return true;
}

bool shortestPathFromGraph(const Matrix<double> &graph, const size_t startIndex,
                           const size_t endIndex,
                           std::vector<size_t> &pathIdx) {
  if (!std::isinf(graph(startIndex, endIndex))) {
    pathIdx.push_back(startIndex);
    pathIdx.push_back(endIndex);
  } else {
    auto distance = [&graph](size_t i, size_t j) -> double {
      return graph(i, j);
    };
    double d = 0;
    if (!dijkstraAlgorithm(graph.n(), startIndex, endIndex, pathIdx, d,
                           distance)) {
      return false;
    }
  }
  return true;
}

} // namespace geometry

bool boost::geometry::model::operator==(::geometry::FPoint &p1,
                                        ::geometry::FPoint &p2) {
  return (p1.get<0>() == p2.get<0>()) && (p1.get<1>() == p2.get<1>());
}

bool boost::geometry::model::operator!=(::geometry::FPoint &p1,
                                        ::geometry::FPoint &p2) {
  return !(p1 == p2);
}

bool boost::geometry::model::operator==(::geometry::IPoint &p1,
                                        ::geometry::IPoint &p2) {
  return (p1.get<0>() == p2.get<0>()) && (p1.get<1>() == p2.get<1>());
}
bool boost::geometry::model::operator!=(::geometry::IPoint &p1,
                                        ::geometry::IPoint &p2) {
  return !(p1 == p2);
}