[pprepair] 01/02: Imported Upstream version 0.0~20140611-c70373b
Bas Couwenberg
sebastic at xs4all.nl
Sat Nov 22 22:40:30 UTC 2014
This is an automated email from the git hooks/post-receive script.
sebastic-guest pushed a commit to branch master
in repository pprepair.
commit ead8c4370cb1c9619741c49437ecdf7e99bfff53
Author: Bas Couwenberg <sebastic at xs4all.nl>
Date: Sat Nov 22 22:57:13 2014 +0100
Imported Upstream version 0.0~20140611-c70373b
---
.gitignore | 21 +
CMakeLists.txt | 75 ++
FaceInfo.cpp | 94 ++
FaceInfo.h | 53 ++
IOWorker.cpp | 2076 +++++++++++++++++++++++++++++++++++++++++
IOWorker.h | 146 +++
LICENSE.txt | 674 +++++++++++++
PlanarPartition.cpp | 383 ++++++++
PlanarPartition.h | 80 ++
PolygonHandle.cpp | 255 +++++
PolygonHandle.h | 144 +++
README.md | 52 ++
definitions/CGALDefinitions.h | 165 ++++
definitions/definitions.h | 38 +
icon.png | Bin 0 -> 27740 bytes
pprepair.cpp | 399 ++++++++
16 files changed, 4655 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ae4ce49
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,21 @@
+# Metadata
+.DS_Store
+
+# Subversion
+.svn
+
+# OS specific Makefile
+Makefile
+
+# Compiled sources
+*.o
+pprepair
+
+# xcode project
+*.xcodeproj
+
+build
+
+CMakeFiles
+CMakeCache.txt
+cmake_install.cmake
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..d3d348b
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,75 @@
+# Copyright (c) 2009-2013,
+# Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+# Hugo Ledoux h.ledoux at tudelft.nl
+# Martijn Meijers b.m.meijers at tudelft.nl
+# All rights reserved.
+#
+# This file is part of pprepair: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Licensees holding a valid commercial license may use this file in
+# accordance with the commercial license agreement provided with
+# the software.
+#
+# This file is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#
+
+project( pprepair )
+
+cmake_minimum_required(VERSION 2.6.2)
+if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" VERSION_GREATER 2.6)
+ if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION}" VERSION_GREATER 2.8.3)
+ cmake_policy(VERSION 2.8.4)
+ else()
+ cmake_policy(VERSION 2.6)
+ endif()
+endif()
+
+set( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true )
+
+if ( COMMAND cmake_policy )
+ cmake_policy( SET CMP0003 NEW )
+endif()
+
+# CGAL
+find_package( CGAL QUIET COMPONENTS )
+
+if ( NOT CGAL_FOUND )
+ message(SEND_ERROR "pprepair requires the CGAL library")
+ return()
+endif()
+
+# include helper file
+include( ${CGAL_USE_FILE} )
+
+# Boost
+find_package( Boost REQUIRED )
+
+if ( NOT Boost_FOUND )
+ message(SEND_ERROR "pprepair requires the Boost library")
+ return()
+endif()
+
+# GDAL
+find_package( GDAL )
+
+if ( NOT GDAL_FOUND )
+ message(SEND_ERROR "pprepair requires the GDAL library")
+endif()
+
+include_directories( ${GDAL_INCLUDE_DIR} )
+
+# Creating entries for target: pprepair
+# ############################
+
+add_executable( pprepair FaceInfo.cpp IOWorker.cpp PlanarPartition.cpp PolygonHandle.cpp pprepair.cpp )
+
+add_to_cached_list( CGAL_EXECUTABLE_TARGETS pprepair )
+
+# Link the executable to CGAL and third-party libraries
+target_link_libraries(pprepair ${CGAL_LIBRARIES} ${CGAL_3RD_PARTY_LIBRARIES} ${GDAL_LIBRARY})
+
diff --git a/FaceInfo.cpp b/FaceInfo.cpp
new file mode 100644
index 0000000..5d00963
--- /dev/null
+++ b/FaceInfo.cpp
@@ -0,0 +1,94 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#include "FaceInfo.h"
+
+FaceInfo::FaceInfo() {
+ tag = NULL;
+}
+
+FaceInfo::~FaceInfo() {
+ if (tag != NULL) {
+ if (tag->isMultiPolygonHandle()) {
+ delete tag;
+ }
+ }
+}
+
+bool FaceInfo::hasTag(PolygonHandle *handle) {
+ if (tag == NULL) return false;
+ if (tag->isMultiPolygonHandle()) return static_cast<MultiPolygonHandle *>(tag)->hasHandle(handle);
+ if (tag == handle) return true;
+ return false;
+}
+
+bool FaceInfo::hasNoTags() const {
+ if (tag == NULL) return true;
+ return false;
+}
+
+bool FaceInfo::hasOneTag() const {
+ if (tag == NULL) return false;
+ if (tag->isMultiPolygonHandle()) return false;
+ return true;
+}
+
+unsigned int FaceInfo::numberOfTags() const {
+ if (tag == NULL) return 0;
+ if (tag->isMultiPolygonHandle()) return static_cast<MultiPolygonHandle *>(tag)->numberOfHandles();
+ return 1;
+}
+
+void FaceInfo::addTag(PolygonHandle *handle) {
+ if (tag == NULL) tag = handle;
+ else if (tag->isMultiPolygonHandle()) static_cast<MultiPolygonHandle *>(tag)->addHandle(handle);
+ else if (tag != handle) {
+ MultiPolygonHandle *multiTag = new MultiPolygonHandle(tag);
+ multiTag->addHandle(handle);
+ tag = multiTag;
+ }
+}
+
+void FaceInfo::removeAllTags() {
+ if (tag == NULL) return;
+ if (tag->isMultiPolygonHandle()) delete tag;
+ tag = NULL;
+}
+
+void FaceInfo::substituteTagsWith(PolygonHandle *handle) {
+ removeAllTags();
+ addTag(handle);
+}
+
+PolygonHandle * FaceInfo::getOneTag() const {
+ if (tag == NULL) return NULL;
+ if (tag->isMultiPolygonHandle()) {
+ return *static_cast<MultiPolygonHandle *>(tag)->getHandles()->begin();
+ } return tag;
+}
+
+PolygonHandle * FaceInfo::getTags() const {
+ return tag;
+}
+
+void FaceInfo::setTags(PolygonHandle *handle) {
+ tag = handle;
+}
\ No newline at end of file
diff --git a/FaceInfo.h b/FaceInfo.h
new file mode 100644
index 0000000..61fab6b
--- /dev/null
+++ b/FaceInfo.h
@@ -0,0 +1,53 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef FACEINFO_H
+#define FACEINFO_H
+
+#include "PolygonHandle.h"
+
+class FaceInfo {
+public:
+ // Constructors and destructors
+ FaceInfo();
+ ~FaceInfo();
+
+ // Clean (and expensive) access operations
+ bool hasTag(PolygonHandle *handle);
+ bool hasNoTags() const;
+ bool hasOneTag() const;
+ unsigned int numberOfTags() const;
+ void addTag(PolygonHandle *handle);
+ void removeAllTags();
+ void substituteTagsWith(PolygonHandle *handle);
+ PolygonHandle * getOneTag() const;
+
+ // Dirty (and cheap) access operations
+ PolygonHandle * getTags() const;
+ void setTags(PolygonHandle *handle);
+
+private:
+ // Tags to the polygons it belongs to.
+ // If more than one, it points to a MultiPolygonHandle with a set of pointers to PolygonHandles.
+ PolygonHandle *tag;
+};
+
+#endif
\ No newline at end of file
diff --git a/IOWorker.cpp b/IOWorker.cpp
new file mode 100644
index 0000000..e551328
--- /dev/null
+++ b/IOWorker.cpp
@@ -0,0 +1,2076 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#include "IOWorker.h"
+
+IOWorker::IOWorker() {
+ startingSearchFace = Triangulation::Face_handle();
+}
+
+bool IOWorker::addToTriangulation(Triangulation &triangulation, TaggingVector &edgesToTag, const char *file, unsigned int schemaIndex) {
+ // Open file
+ OGRDataSource *dataSource = OGRSFDriverRegistrar::Open(file, false);
+ if (dataSource == NULL) {
+ std::cerr << "Error: Could not open file." << std::endl;
+ return false;
+ }
+
+ char *name = new char[strlen(dataSource->GetName())+1];
+ strcpy(name, dataSource->GetName());
+ fileNames.push_back(name);
+ std::cout << "\tPath: " << name << std::endl;
+ std::cout << "\tType: " << dataSource->GetDriver()->GetName() << std::endl;
+ int numberOfLayers = dataSource->GetLayerCount();
+ std::cout << "\tLayers: " << numberOfLayers << std::endl;
+
+ // Read layer by layer
+ for (int currentLayer = 0; currentLayer < numberOfLayers; currentLayer++) {
+ OGRLayer *dataLayer = dataSource->GetLayer(currentLayer);
+ dataLayer->ResetReading();
+ OGRSpatialReference* tmp = dataLayer->GetSpatialRef();
+ if ( (tmp != NULL) && (spatialReference != NULL) )
+ spatialReference = tmp->CloneGeogCS();
+
+ unsigned int numberOfPolygons = dataLayer->GetFeatureCount(true);
+ std::cout << "\tReading layer #" << currentLayer+1 << " (" << numberOfPolygons << " polygons)...";
+ polygons.reserve(polygons.size()+numberOfPolygons);
+
+ // Check fields and the schema type
+ OGRFeatureDefn *layerDefinition = dataLayer->GetLayerDefn();
+ insertToStream(std::cout, layerDefinition, 1, schemaIndex);
+
+ // If it's the first input file, assign the schema type of it
+ if (triangulation.number_of_faces() == 0) {
+ schemaFieldType = layerDefinition->GetFieldDefn(schemaIndex)->GetType();
+ } // Otherwise, check if it matches the previous one
+ else {
+ if (layerDefinition->GetFieldDefn(schemaIndex)->GetType() != schemaFieldType) {
+ std::cerr << "\tError: The schema field type in this layer is incompatible with the previous one. Skipped." << std::endl;
+ continue;
+ }
+ }
+
+ // Save the field names and types
+ for (int currentField = 0; currentField < layerDefinition->GetFieldCount(); currentField++) {
+ OGRFieldDefn *fieldDefinition = layerDefinition->GetFieldDefn(currentField);
+ FieldDefinition *newField = new FieldDefinition(fieldDefinition->GetNameRef(), fieldDefinition->GetType(), fieldDefinition->GetJustify(), fieldDefinition->GetWidth(), fieldDefinition->GetPrecision());
+ unsigned int currentCheck;
+ for (currentCheck = 0; currentCheck < fields.size(); currentCheck++) {
+ if (newField->matches(fields[currentCheck])) break;
+ } if (currentCheck == (unsigned int)fields.size()) {
+ // It's a new field
+ fields.push_back(newField);
+ fieldEquivalencies[FieldDescriptor(name, currentLayer, currentField)] = ((unsigned int)fields.size())-1;
+ } else {
+ // The field matches an older one, don't add
+ delete newField;
+ fieldEquivalencies[FieldDescriptor(name, currentLayer, currentField)] = currentCheck;
+ }
+ }
+
+ // Reads all features in this layer
+ OGRFeature *feature;
+ while ((feature = dataLayer->GetNextFeature()) != NULL) {
+
+ // STEP 1: Get polygons from input
+ std::vector<std::list<Point> > outerRingsList;
+ std::vector<std::list<Point> > innerRingsList;
+ switch(feature->GetGeometryRef()->getGeometryType()) {
+
+ // Most typical case, receiving polygons
+ case wkbPolygon:
+ case wkbPolygon25D: {
+ OGRPolygon *geometry = static_cast<OGRPolygon *>(feature->GetGeometryRef());
+ outerRingsList.push_back(std::list<Point>());
+
+ // Get outer ring
+ for (int currentPoint = 0; currentPoint < geometry->getExteriorRing()->getNumPoints(); currentPoint++)
+ outerRingsList.back().push_back(Point(geometry->getExteriorRing()->getX(currentPoint),
+ geometry->getExteriorRing()->getY(currentPoint)));
+
+ // Get inner rings
+ innerRingsList.reserve(geometry->getNumInteriorRings());
+ for (int currentRing = 0; currentRing < geometry->getNumInteriorRings(); currentRing++) {
+ innerRingsList.push_back(std::list<Point>());
+ for (int currentPoint = 0; currentPoint < geometry->getInteriorRing(currentRing)->getNumPoints(); currentPoint++) {
+ innerRingsList.back().push_back(Point(geometry->getInteriorRing(currentRing)->getX(currentPoint),
+ geometry->getInteriorRing(currentRing)->getY(currentPoint)));
+ }
+ } break;
+ }
+
+ // Receiving multi polygons
+ case wkbMultiPolygon: {
+ OGRMultiPolygon *geometry = static_cast<OGRMultiPolygon *>(feature->GetGeometryRef());
+
+ // Check each polygon
+ for (int currentPolygon = 0; currentPolygon < geometry->getNumGeometries(); currentPolygon++) {
+ OGRPolygon *thisGeometry = static_cast<OGRPolygon *>(geometry->getGeometryRef(currentPolygon));
+ outerRingsList.push_back(std::list<Point>());
+
+ // Get outer ring
+ for (int currentPoint = 0; currentPoint < thisGeometry->getExteriorRing()->getNumPoints(); currentPoint++)
+ outerRingsList.back().push_back(Point(thisGeometry->getExteriorRing()->getX(currentPoint),
+ thisGeometry->getExteriorRing()->getY(currentPoint)));
+
+ // Get inner rings
+ innerRingsList.reserve(innerRingsList.size()+thisGeometry->getNumInteriorRings());
+ for (int currentRing = 0; currentRing < thisGeometry->getNumInteriorRings(); currentRing++) {
+ innerRingsList.push_back(std::list<Point>());
+ for (int currentPoint = 0; currentPoint < thisGeometry->getInteriorRing(currentRing)->getNumPoints(); currentPoint++) {
+ innerRingsList.back().push_back(Point(thisGeometry->getInteriorRing(currentRing)->getX(currentPoint),
+ thisGeometry->getInteriorRing(currentRing)->getY(currentPoint)));
+ }
+ }
+ } break;
+ }
+
+ default:
+ std::cerr << "\tFeature #" << feature->GetFID() << ": unsupported type (";
+ insertToStream(std::cout, feature->GetGeometryRef()->getGeometryType());
+ std::cerr << "). Skipped." << std::endl;
+ continue;
+ break;
+
+ // TODO: Implement other cases: points, lines, containers with multiple features, etc.
+ }
+
+ // STEP 2: Check validity of individual polygons
+ // it's more efficient doing this during creation, but this is more readable and maintainable (check SVN v59).
+ // After all, this is not the main focus here.
+
+ std::vector<Polygon> polygonsVector;
+ // CHECKS ON VERTICES
+
+ // Remove repeated vertices. One per ring is considered normal, since some specifications allow or require it (first == last).
+ for (unsigned int currentRing = 0; currentRing < outerRingsList.size(); ++currentRing) {
+ if (removeDuplicateVertices(outerRingsList[currentRing]) > 1)
+ std::cout << "\tFeature #" << feature->GetFID() << ": duplicate vertices in outer boundary #" << currentRing << ". Removed duplicates." << std::endl;
+ } for (unsigned int currentRing = 0; currentRing < innerRingsList.size(); ++currentRing) {
+ if (removeDuplicateVertices(innerRingsList[currentRing]) > 1)
+ std::cout << "\tFeature #" << feature->GetFID() << ": duplicate vertices in inner boundary #" << currentRing << ". Removed duplicates." << std::endl;
+ }
+
+ // Trivial check for rings with less than 3 vertices. The ones with 3 or more vertices will be done in the triangulation
+ for (int currentRing = 0; currentRing < (int)outerRingsList.size(); ++currentRing) {
+ if (outerRingsList[currentRing].size() < 3) {
+ std::cout << "\tFeature #" << feature->GetFID() << ": less than 3 vertices in outer boundary #" << currentRing << ". Removed." << std::endl;
+ outerRingsList.erase(outerRingsList.begin()+currentRing);
+ --currentRing;
+ }
+ } for (int currentRing = 0; currentRing < (int)innerRingsList.size(); ++currentRing) {
+ if (innerRingsList[currentRing].size() < 3) {
+ std::cout << "\tFeature #" << feature->GetFID() << ": less than 3 vertices in inner boundary #" << currentRing << ". Removed." << std::endl;
+ innerRingsList.erase(innerRingsList.begin()+currentRing);
+ --currentRing;
+ }
+ }
+
+ // CHECKS ON RINGS
+
+ // Let's move on to the CGAL data structures for Rings
+ std::vector<Ring> outerRings;
+ std::vector<Ring> innerRings;
+ outerRings.reserve(outerRingsList.size());
+ innerRings.reserve(innerRingsList.size());
+ for (unsigned int currentRing = 0; currentRing < outerRingsList.size(); currentRing++) {
+ outerRings.push_back(Ring(outerRingsList[currentRing].begin(), outerRingsList[currentRing].end()));
+ outerRingsList[currentRing].clear();
+ } for (unsigned int currentRing = 0; currentRing < innerRingsList.size(); currentRing++) {
+ innerRings.push_back(Ring(innerRingsList[currentRing].begin(), innerRingsList[currentRing].end()));
+ innerRingsList[currentRing].clear();
+ }
+
+ // Split self touching rings and correct winding
+ std::vector<Ring *> outerRingsToBuild;
+ std::vector<Ring *> innerRingsToClassify;
+ std::vector<std::vector<Ring> > innerRingsToBuild;
+
+ // Get outer rings
+ for (unsigned int currentRings = 0; currentRings < outerRings.size(); currentRings++) {
+ if (!outerRings[currentRings].is_simple()) {
+ std::cout << "\tFeature #" << feature->GetFID() << " (" << outerRings[currentRings].size() << " vertices): self intersecting outer boundary #" << currentRings << ". Split." << std::endl;
+ std::vector<Ring *> receivedRings = splitRing(outerRings[currentRings]);
+ for (std::vector<Ring *>::iterator currentRing = receivedRings.begin(); currentRing != receivedRings.end(); ++currentRing) {
+ if ((*currentRing)->is_clockwise_oriented()) {
+ outerRingsToBuild.push_back(*currentRing);
+ } else {
+ innerRingsToClassify.push_back(*currentRing);
+ }
+ }
+ } else {
+ if (outerRings[currentRings].is_counterclockwise_oriented()) {
+ std::cout << "\tFeature #" << feature->GetFID() << ": incorrect winding in outer boundary #" << currentRings << ". Reversed." << std::endl;
+ outerRings[currentRings].reverse_orientation();
+ } outerRingsToBuild.push_back(new Ring(outerRings[currentRings]));
+ outerRings[currentRings].clear();
+ }
+ }
+
+ // Get inner rings
+ for (unsigned int currentRings = 0; currentRings < innerRings.size(); currentRings++) {
+ if (!innerRings[currentRings].is_simple()) {
+ std::cout << "\tFeature #" << feature->GetFID() << " (" << innerRings[currentRings].size() << " vertices): self intersecting inner boundary #" << currentRings << ". Split." << std::endl;
+ std::vector<Ring *> receivedRings = splitRing(innerRings[currentRings]);
+ for (std::vector<Ring *>::iterator currentRing = receivedRings.begin(); currentRing != receivedRings.end(); ++currentRing) {
+ if ((*currentRing)->is_clockwise_oriented()) {
+ innerRingsToClassify.push_back(*currentRing);
+ } else {
+ outerRingsToBuild.push_back(*currentRing);
+ }
+ }
+ } else {
+ if (innerRings[currentRings].is_clockwise_oriented()) {
+ std::cout << "\tFeature #" << feature->GetFID() << ": incorrect winding in inner boundary #" << currentRings << ". Reversed." << std::endl;
+ innerRings[currentRings].reverse_orientation();
+ } innerRingsToClassify.push_back(new Ring(innerRings[currentRings]));
+ innerRings[currentRings].clear();
+ }
+ }
+
+ // Make space for inner rings
+ for (std::vector<Ring *>::iterator currentRing = outerRingsToBuild.begin(); currentRing != outerRingsToBuild.end(); ++currentRing) {
+ innerRingsToBuild.push_back(std::vector<Ring>());
+ }
+
+ // Put inner rings into the correct outer ring (and likely other ones). Incorrectly nested rings are found here.
+ if (outerRingsToBuild.size() == 0) {
+ // Outer ring had no area or there wasn't any. Delete all inner rings
+ std::cout << "\tFeature #" << feature->GetFID() << ": zero area outer boundary. Inner boundaries removed." << std::endl;
+ for (std::vector<Ring *>::iterator currentRing = innerRingsToClassify.begin(); currentRing != innerRingsToClassify.end(); ++currentRing) {
+ delete *currentRing;
+ }
+ }
+
+ // Now check them and put them in place
+ else if (innerRingsToClassify.size() > 0) {
+ testRings(outerRingsToBuild, innerRingsToClassify, innerRingsToBuild, feature->GetFID());
+ }
+
+ // Let's move on to CGAL data structures for Polygons
+ for (unsigned int currentPolygon = 0; currentPolygon < outerRingsToBuild.size(); ++currentPolygon) {
+ polygonsVector.push_back(Polygon(*outerRingsToBuild[currentPolygon], innerRingsToBuild[currentPolygon].begin(), innerRingsToBuild[currentPolygon].end()));
+ } outerRingsToBuild.clear();
+ innerRingsToBuild.clear();
+
+ // STEP 3: Introduce edges as constraints in the triangulation
+ for (std::vector<Polygon>::iterator currentPolygon = polygonsVector.begin(); currentPolygon != polygonsVector.end(); ++currentPolygon) {
+
+ // Create and save polygon handle
+ PolygonHandle *handle = new PolygonHandle(schemaIndex, fileNames.back(), currentLayer, feature->GetFID());
+ polygons.push_back(handle);
+
+ // Save other attributes to put back later
+ copyFields(feature, handle);
+
+ // Create edges vector for this handle
+ edgesToTag.push_back(std::pair<std::vector<Triangulation::Vertex_handle>, std::vector<std::vector<Triangulation::Vertex_handle> > >());
+
+ // Insert edges into the triangulation and edges vector
+ for (Ring::Edge_const_iterator currentEdge = currentPolygon->outer_boundary().edges_begin();
+ currentEdge != currentPolygon->outer_boundary().edges_end();
+ ++currentEdge) {
+ Triangulation::Vertex_handle sourceVertex = triangulation.insert(currentEdge->source(), startingSearchFace);
+ startingSearchFace = triangulation.incident_faces(sourceVertex);
+ Triangulation::Vertex_handle targetVertex = triangulation.insert(currentEdge->target(), startingSearchFace);
+ triangulation.insert_constraint(sourceVertex, targetVertex);
+ startingSearchFace = triangulation.incident_faces(targetVertex);
+ edgesToTag.back().first.push_back(sourceVertex);
+ } for (Polygon::Hole_const_iterator currentRing = currentPolygon->holes_begin(); currentRing != currentPolygon->holes_end(); ++currentRing) {
+ edgesToTag.back().second.push_back(std::vector<Triangulation::Vertex_handle>());
+ for (Ring::Edge_const_iterator currentEdge = currentRing->edges_begin(); currentEdge != currentRing->edges_end(); ++currentEdge) {
+ Triangulation::Vertex_handle sourceVertex = triangulation.insert(currentEdge->source(), startingSearchFace);
+ startingSearchFace = triangulation.incident_faces(sourceVertex);
+ Triangulation::Vertex_handle targetVertex = triangulation.insert(currentEdge->target(), startingSearchFace);
+ triangulation.insert_constraint(sourceVertex, targetVertex);
+ startingSearchFace = triangulation.incident_faces(targetVertex);
+ edgesToTag.back().second.back().push_back(sourceVertex);
+ }
+ }
+ }
+
+ // Free memory
+ polygonsVector.clear();
+
+ // Free OGR feature
+ OGRFeature::DestroyFeature(feature);
+ }
+ }
+
+ // Free OGR data source
+ OGRDataSource::DestroyDataSource(dataSource);
+
+ return true;
+}
+
+bool IOWorker::tagTriangulation(Triangulation &triangulation, TaggingVector &edgesToTag) {
+
+ std::stack<Triangulation::Face_handle> stack;
+ Triangulation::Vertices_in_constraint_iterator previousVertex, currentVertex;
+ Triangulation::Face_handle currentFace;
+ int incident;
+ bool sameOrder;
+
+ // Add all edges of a polygon
+ for (unsigned int currentPolygon = 0; currentPolygon < edgesToTag.size(); ++currentPolygon) {
+
+ // Outer boundary
+ for (unsigned int currentEdge = 0; currentEdge < edgesToTag[currentPolygon].first.size(); ++currentEdge) {
+ previousVertex = triangulation.vertices_in_constraint_begin(edgesToTag[currentPolygon].first[currentEdge],
+ edgesToTag[currentPolygon].first[(currentEdge+1)%edgesToTag[currentPolygon].first.size()]);
+ // Check if the returned order is the same
+ if ((*previousVertex)->point() == edgesToTag[currentPolygon].first[currentEdge]->point()) sameOrder = true;
+ else sameOrder = false;
+ currentVertex = previousVertex;
+ ++currentVertex;
+ while (currentVertex != triangulation.vertices_in_constraint_end(edgesToTag[currentPolygon].first[currentEdge],
+ edgesToTag[currentPolygon].first[(currentEdge+1)%edgesToTag[currentPolygon].first.size()])) {
+ if (sameOrder) {
+ if (!triangulation.is_edge(*previousVertex, *currentVertex, currentFace, incident)) {
+ std::cout << "\tError: Cannot find adjoining face to an edge from the edge list!" << std::endl;
+ return false;
+ }
+ } else {
+ if (!triangulation.is_edge(*currentVertex, *previousVertex, currentFace, incident)) {
+ std::cout << "\tError: Cannot find adjoining face to an edge from the edge list!" << std::endl;
+ return false;
+ }
+ } previousVertex = currentVertex;
+ ++currentVertex;
+ stack.push(currentFace);
+ }
+ }
+
+ // Free memory for boundaries
+ edgesToTag[currentPolygon].first.clear();
+ edgesToTag[currentPolygon].second.clear();
+
+ // Expand the tags
+ tagStack(stack, polygons[currentPolygon]);
+ }
+
+ // Free remaining memory
+ edgesToTag.clear();
+
+ // Tag the universe
+ currentFace = triangulation.infinite_face();
+ stack.push(currentFace);
+ tagStack(stack, &universe);
+
+ return true;
+}
+
+bool IOWorker::makeAllHolesValid(Triangulation &triangulation) {
+
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (currentFace->info().hasNoTags()) {
+ currentFace->info().addTag(&universe);
+ }
+ }
+
+ return true;
+}
+
+bool IOWorker::splitRegions(Triangulation &triangulation, double ratio) {
+
+ double shortSide, longSide, thisSide;
+ unsigned int whichSide, splits = 0;
+
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+
+ // Check for the longest and shortest sides
+ shortSide = longSide = sqrt(CGAL::to_double(triangulation.segment(currentFace, 0).squared_length()));
+ whichSide = 0;
+ thisSide = sqrt(CGAL::to_double(triangulation.segment(currentFace, 1).squared_length()));
+ if (thisSide > longSide) longSide = thisSide;
+ else if (thisSide < shortSide) {
+ shortSide = thisSide;
+ whichSide = 1;
+ } thisSide = sqrt(CGAL::to_double(triangulation.segment(currentFace, 2).squared_length()));
+ if (thisSide > longSide) longSide = thisSide;
+ else if (thisSide < shortSide) {
+ shortSide = thisSide;
+ whichSide = 2;
+ }
+
+ // Add constrained edge if they exceed the long/short ratio
+ if (longSide/shortSide >= ratio) {
+ currentFace->set_constraint(whichSide, true);
+ ++splits;
+ }
+ }
+
+ std::cout << "\t" << splits << " constrained edges added." << std::endl;
+
+ return true;
+}
+
+bool IOWorker::repairTrianglesByNumberOfNeighbours(Triangulation &triangulation, bool alsoUniverse) {
+
+ bool repaired = true;
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ std::map<PolygonHandle *, unsigned int> tagCount;
+ if (!currentFace->info().hasOneTag()) {
+
+ // Count the number of times each tag appears
+ addtoCount(tagCount, currentFace->neighbor(0)->info().getTags());
+ addtoCount(tagCount, currentFace->neighbor(1)->info().getTags());
+ addtoCount(tagCount, currentFace->neighbor(2)->info().getTags());
+
+ // Find the tag with highest count
+ unsigned int maxCount = 0;
+ std::map<PolygonHandle *, unsigned int>::iterator mostTimesAppeared = tagCount.end();
+ for (std::map<PolygonHandle *, unsigned int>::iterator currentCount = tagCount.begin(); currentCount != tagCount.end(); ++currentCount) {
+ if (currentCount->first != NULL && (alsoUniverse || currentCount->first != &universe)) {
+ if (currentCount->second > maxCount && (currentFace->info().hasTag(currentCount->first) || currentFace->info().hasNoTags())) {
+ currentCount->second = maxCount;
+ mostTimesAppeared = currentCount;
+ } else if (currentCount->second == maxCount) {
+ mostTimesAppeared = tagCount.end();
+ }
+ }
+ }
+
+ // Assign the triangle to the tag with the highest count (if there is one)
+ if (mostTimesAppeared == tagCount.end()) repaired = false;
+ else facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(currentFace, mostTimesAppeared->first));
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return repaired;
+}
+
+bool IOWorker::repairTrianglesByAbsoluteMajority(Triangulation &triangulation, bool alsoUniverse) {
+
+ bool repaired = true;
+
+ // Put faces to repair in the vector
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, Triangulation::Face_handle> > facesToRepair;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (!currentFace->info().hasOneTag()) {
+ if (currentFace->neighbor(0)->info().hasOneTag() && currentFace->neighbor(1)->info().hasOneTag() &&
+ currentFace->neighbor(0)->info().getTags() == currentFace->neighbor(1)->info().getTags() &&
+ (currentFace->info().hasTag(currentFace->neighbor(0)->info().getTags()) || currentFace->info().hasNoTags())) {
+ if ((currentFace->neighbor(0)->info().getTags() != &universe &&
+ currentFace->neighbor(0)->info().getTags() != NULL) ||
+ alsoUniverse) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, Triangulation::Face_handle>(currentFace, currentFace->neighbor(0)));
+ }
+ } else if (currentFace->neighbor(0)->info().hasOneTag() && currentFace->neighbor(2)->info().hasOneTag() &&
+ currentFace->neighbor(0)->info().getTags() == currentFace->neighbor(2)->info().getTags() &&
+ (currentFace->info().hasTag(currentFace->neighbor(2)->info().getTags()) || currentFace->info().hasNoTags())) {
+ if ((currentFace->neighbor(2)->info().getTags() != &universe &&
+ currentFace->neighbor(2)->info().getTags() != NULL) ||
+ alsoUniverse) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, Triangulation::Face_handle>(currentFace, currentFace->neighbor(2)));
+ }
+ } else if (currentFace->neighbor(1)->info().hasOneTag() && currentFace->neighbor(2)->info().hasOneTag() &&
+ currentFace->neighbor(1)->info().getTags() == currentFace->neighbor(2)->info().getTags() &&
+ (currentFace->info().hasTag(currentFace->neighbor(1)->info().getTags()) || currentFace->info().hasNoTags())) {
+ if ((currentFace->neighbor(1)->info().getTags() != &universe &&
+ currentFace->neighbor(1)->info().getTags() != NULL) ||
+ alsoUniverse) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, Triangulation::Face_handle>(currentFace, currentFace->neighbor(1)));
+ }
+ } else {
+ repaired = false;
+ }
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, Triangulation::Face_handle> >::iterator currentFace = facesToRepair.begin();
+ currentFace != facesToRepair.end();
+ ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second->info().getTags());
+ }
+
+ return repaired;
+}
+
+bool IOWorker::repairTrianglesByLongestBoundary(Triangulation &triangulation, bool alsoUniverse) {
+
+ bool repaired = true;
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ std::map<PolygonHandle *, double> tagBoundaryLength;
+ if (!currentFace->info().hasOneTag()) {
+
+ // Add up the boundary for each tag
+ addToLength(tagBoundaryLength, currentFace->neighbor(0)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(currentFace, 0).squared_length())));
+ addToLength(tagBoundaryLength, currentFace->neighbor(1)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(currentFace, 1).squared_length())));
+ addToLength(tagBoundaryLength, currentFace->neighbor(2)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(currentFace, 2).squared_length())));
+
+ // Find the tag with longest boundary
+ double maxLength = 0.0;
+ std::map<PolygonHandle *, double>::iterator longest = tagBoundaryLength.end();
+ for (std::map<PolygonHandle *, double>::iterator currentLength = tagBoundaryLength.begin(); currentLength != tagBoundaryLength.end(); ++currentLength) {
+ if (currentLength->first != NULL && (alsoUniverse || currentLength->first != &universe)) {
+ if (currentLength->second > maxLength && (currentFace->info().hasTag(currentLength->first) || currentFace->info().hasNoTags())) {
+ maxLength = currentLength->second;
+ longest = currentLength;
+ } else if (currentLength->second == maxLength) {
+ longest = tagBoundaryLength.end();
+ }
+ }
+ }
+
+ // Assign the triangle to the tag with the longest boundary (if there is one)
+ if (longest == tagBoundaryLength.end()) repaired = false;
+ else facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(currentFace, longest->first));
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return repaired;
+}
+
+bool IOWorker::repairRegionsByLongestBoundary(Triangulation &triangulation, bool alsoUniverse) {
+
+ bool repaired = true;
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ std::set<Triangulation::Face_handle> processedFaces;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ std::map<PolygonHandle *, double> tagBoundaryLength;
+ if (!currentFace->info().hasOneTag() && !processedFaces.count(currentFace)) {
+
+ // Expand this triangle into a complete region
+ std::set<Triangulation::Face_handle> facesInRegion;
+ facesInRegion.insert(currentFace);
+ std::stack<Triangulation::Face_handle> facesToProcess;
+ facesToProcess.push(currentFace);
+ while (facesToProcess.size() > 0) {
+ Triangulation::Face_handle currentFaceInStack = facesToProcess.top();
+ facesToProcess.pop();
+ processedFaces.insert(currentFaceInStack);
+ if (!currentFaceInStack->neighbor(0)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(0)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 0))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(0));
+ facesToProcess.push(currentFaceInStack->neighbor(0));
+ } if (!currentFaceInStack->neighbor(1)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(1)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 1))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(1));
+ facesToProcess.push(currentFaceInStack->neighbor(1));
+ } if (!currentFaceInStack->neighbor(2)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(2)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 2))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(2));
+ facesToProcess.push(currentFaceInStack->neighbor(2));
+ }
+ }
+
+ // Add up the boundary for each triangle and tag
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ if (!facesInRegion.count((*currentFaceInRegion)->neighbor(0))) {
+ addToLength(tagBoundaryLength, (*currentFaceInRegion)->neighbor(0)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(*currentFaceInRegion, 0).squared_length())));
+ } if (!facesInRegion.count((*currentFaceInRegion)->neighbor(1))) {
+ addToLength(tagBoundaryLength, (*currentFaceInRegion)->neighbor(1)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(*currentFaceInRegion, 1).squared_length())));
+ } if (!facesInRegion.count((*currentFaceInRegion)->neighbor(2))) {
+ addToLength(tagBoundaryLength, (*currentFaceInRegion)->neighbor(2)->info().getTags(), sqrt(CGAL::to_double(triangulation.segment(*currentFaceInRegion, 2).squared_length())));
+ }
+ }
+
+ // Find the tag with longest boundary
+ double maxLength = 0.0;
+ std::map<PolygonHandle *, double>::iterator longest = tagBoundaryLength.end();
+ for (std::map<PolygonHandle *, double>::iterator currentLength = tagBoundaryLength.begin(); currentLength != tagBoundaryLength.end(); ++currentLength) {
+ if (currentLength->first != NULL && (alsoUniverse || currentLength->first != &universe)) {
+ if (currentLength->second > maxLength && (currentFace->info().hasTag(currentLength->first) || currentFace->info().hasNoTags())) {
+ maxLength = currentLength->second;
+ longest = currentLength;
+ } else if (currentLength->second == maxLength) {
+ longest = tagBoundaryLength.end();
+ }
+ }
+ }
+
+ // Assign the region to the tag with the longest boundary (if there is one)
+ if (longest == tagBoundaryLength.end()) repaired = false;
+ else {
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(*currentFaceInRegion, longest->first));
+ }
+ }
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return repaired;
+}
+
+bool IOWorker::repairRegionsByRandomNeighbour(Triangulation &triangulation, bool alsoUniverse) {
+
+ bool repaired = true;
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ std::set<Triangulation::Face_handle> processedFaces;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (!currentFace->info().hasOneTag() && !processedFaces.count(currentFace)) {
+
+ // Expand this triangle into a complete region
+ std::set<Triangulation::Face_handle> facesInRegion;
+ facesInRegion.insert(currentFace);
+ std::stack<Triangulation::Face_handle> facesToProcess;
+ facesToProcess.push(currentFace);
+ while (facesToProcess.size() > 0) {
+ Triangulation::Face_handle currentFaceInStack = facesToProcess.top();
+ facesToProcess.pop();
+ processedFaces.insert(currentFaceInStack);
+ if (!currentFaceInStack->neighbor(0)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(0)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 0))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(0));
+ facesToProcess.push(currentFaceInStack->neighbor(0));
+ } if (!currentFaceInStack->neighbor(1)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(1)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 1))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(1));
+ facesToProcess.push(currentFaceInStack->neighbor(1));
+ } if (!currentFaceInStack->neighbor(2)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(2)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 2))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(2));
+ facesToProcess.push(currentFaceInStack->neighbor(2));
+ }
+ }
+
+ // Find a random tag
+ PolygonHandle *tagToAssign;
+ while (true) {
+ std::set<Triangulation::Face_handle>::iterator randomFace = facesInRegion.begin();
+ std::advance(randomFace, rand()%facesInRegion.size());
+ int neighbourIndex = rand()%3;
+ unsigned int numberOfTags = (*randomFace)->neighbor(neighbourIndex)->info().numberOfTags();
+ if (numberOfTags == 0) continue;
+ if (numberOfTags == 1) {
+ tagToAssign = (*randomFace)->neighbor(neighbourIndex)->info().getTags();
+ if (alsoUniverse || tagToAssign != &universe) break;
+ } else {
+ std::list<PolygonHandle *>::const_iterator randomTag = static_cast<MultiPolygonHandle *>((*randomFace)->neighbor(neighbourIndex)->info().getTags())->getHandles()->begin();
+ std::advance(randomTag, rand()%numberOfTags);
+ tagToAssign = *randomTag;
+ if (alsoUniverse || tagToAssign != &universe) break;
+ }
+ }
+
+ // Assign the region to the random tag
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(*currentFaceInRegion, tagToAssign));
+ }
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return repaired;
+}
+
+bool IOWorker::repairByPriorityList(Triangulation &triangulation, const char *file) {
+
+ // Process priority file
+ std::ifstream priorityFile;
+ priorityFile.open(file, std::ios::in);
+ if (!priorityFile.is_open()) {
+ std::cout << "Priority file could not be opened." << std::endl;
+ return false;
+ } std::map<Field *, unsigned int, FieldComparator> priorityMap;
+ unsigned int currentPriority = 0;
+ while (!priorityFile.eof()) {
+ switch (schemaFieldType) {
+ case OFTString: {
+ std::string fieldAsString;
+ std::getline(priorityFile, fieldAsString); // If we deal with strings take a whole line (since spaces could be valid)
+ StringField *newField = new StringField(fieldAsString.c_str());
+ priorityMap[newField] = currentPriority;
+ break;
+ } case OFTReal: {
+ double fieldAsDouble;
+ priorityFile >> fieldAsDouble;
+ DoubleField *newField = new DoubleField(fieldAsDouble);
+ priorityMap[newField] = currentPriority;
+ } case OFTInteger: {
+ int fieldAsInt;
+ priorityFile >> fieldAsInt;
+ IntField *newField = new IntField(fieldAsInt);
+ priorityMap[newField] = currentPriority;
+ } default: {
+ std::cout << "Field type not supported." << std::endl;
+ std::string fieldAsString;
+ std::getline(priorityFile, fieldAsString);
+ break;
+ }
+ } ++currentPriority;
+ } priorityFile.close();
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ std::set<Triangulation::Face_handle> processedFaces;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (!currentFace->info().hasOneTag() && !processedFaces.count(currentFace)) {
+
+ // Expand this triangle into a complete region
+ std::set<Triangulation::Face_handle> facesInRegion;
+ facesInRegion.insert(currentFace);
+ std::stack<Triangulation::Face_handle> facesToProcess;
+ facesToProcess.push(currentFace);
+ while (facesToProcess.size() > 0) {
+ Triangulation::Face_handle currentFaceInStack = facesToProcess.top();
+ facesToProcess.pop();
+ processedFaces.insert(currentFaceInStack);
+ if (!currentFaceInStack->neighbor(0)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(0)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 0))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(0));
+ facesToProcess.push(currentFaceInStack->neighbor(0));
+ } if (!currentFaceInStack->neighbor(1)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(1)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 1))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(1));
+ facesToProcess.push(currentFaceInStack->neighbor(1));
+ } if (!currentFaceInStack->neighbor(2)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(2)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 2))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(2));
+ facesToProcess.push(currentFaceInStack->neighbor(2));
+ }
+ }
+
+ // Find the tag with the highest priority
+ PolygonHandle *tagToAssign = NULL;
+ unsigned int priorityOfTag = UINT_MAX;
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ // Gap, check neighbours
+ if ((*currentFaceInRegion)->info().hasNoTags()) {
+ if (!(*currentFaceInRegion)->neighbor(0)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(0)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(0)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(0)->info().getTags()->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentFaceInRegion)->neighbor(0)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(0)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(0)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ } if (!(*currentFaceInRegion)->neighbor(1)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(1)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(1)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(1)->info().getTags()->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentFaceInRegion)->neighbor(1)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(1)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(1)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ } if (!(*currentFaceInRegion)->neighbor(2)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(2)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(2)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(2)->info().getTags()->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentFaceInRegion)->neighbor(2)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(2)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(2)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ }
+ }
+
+ // Overlap, check this one
+ else {
+ if ((*currentFaceInRegion)->info().hasOneTag() && (*currentFaceInRegion)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->info().getTags()->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentFaceInRegion)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTag) {
+ priorityOfTag = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ }
+ }
+
+ // Assign the tag to the triangles in the region
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(*currentFaceInRegion, tagToAssign));
+ }
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return true;
+}
+
+bool IOWorker::repairEdgeMatching(Triangulation &triangulation, const char *file) {
+
+ // Process priority file
+ std::ifstream priorityFile;
+ priorityFile.open(file, std::ios::in);
+ if (!priorityFile.is_open()) {
+ std::cout << "Priority file could not be opened." << std::endl;
+ return false;
+ } std::map<Field *, unsigned int, FieldComparator> priorityMap;
+ unsigned int currentPriority = 0;
+ while (!priorityFile.eof()) {
+ switch (schemaFieldType) {
+ case OFTString: {
+ std::string fieldAsString;
+ std::getline(priorityFile, fieldAsString); // If we deal with strings take a whole line (since spaces could be valid)
+ StringField *newField = new StringField(fieldAsString.c_str());
+ priorityMap[newField] = currentPriority;
+ break;
+ } case OFTReal: {
+ double fieldAsDouble;
+ priorityFile >> fieldAsDouble;
+ DoubleField *newField = new DoubleField(fieldAsDouble);
+ priorityMap[newField] = currentPriority;
+ } case OFTInteger: {
+ int fieldAsInt;
+ priorityFile >> fieldAsInt;
+ IntField *newField = new IntField(fieldAsInt);
+ priorityMap[newField] = currentPriority;
+ } default: {
+ std::cout << "Field type not supported." << std::endl;
+ std::string fieldAsString;
+ std::getline(priorityFile, fieldAsString);
+ break;
+ }
+ } ++currentPriority;
+ } priorityFile.close();
+
+ // Use a temporary vector to make it deterministic and order independent
+ std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> > facesToRepair;
+ std::set<Triangulation::Face_handle> processedFaces;
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (!currentFace->info().hasOneTag() && !processedFaces.count(currentFace)) {
+
+ // Expand this triangle into a complete region
+ std::set<Triangulation::Face_handle> facesInRegion;
+ facesInRegion.insert(currentFace);
+ std::stack<Triangulation::Face_handle> facesToProcess;
+ facesToProcess.push(currentFace);
+ while (facesToProcess.size() > 0) {
+ Triangulation::Face_handle currentFaceInStack = facesToProcess.top();
+ facesToProcess.pop();
+ processedFaces.insert(currentFaceInStack);
+ if (!currentFaceInStack->neighbor(0)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(0)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 0))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(0));
+ facesToProcess.push(currentFaceInStack->neighbor(0));
+ } if (!currentFaceInStack->neighbor(1)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(1)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 1))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(1));
+ facesToProcess.push(currentFaceInStack->neighbor(1));
+ } if (!currentFaceInStack->neighbor(2)->info().hasOneTag() && !facesInRegion.count(currentFaceInStack->neighbor(2)) &&
+ !triangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(currentFaceInStack, 2))) {
+ facesInRegion.insert(currentFaceInStack->neighbor(2));
+ facesToProcess.push(currentFaceInStack->neighbor(2));
+ }
+ }
+
+ // Find the tag with the highest priority
+ PolygonHandle *tagToAssign = NULL;
+ unsigned int priorityOfTagh = UINT_MAX;
+ unsigned int priorityOfTagg = 0;
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ // Gap, check neighbours
+ if ((*currentFaceInRegion)->info().hasNoTags()) {
+ if (!(*currentFaceInRegion)->neighbor(0)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(0)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(0)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(0)->info().getTags()->getSchemaField()] >= priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentFaceInRegion)->neighbor(0)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(0)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(0)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ } if (!(*currentFaceInRegion)->neighbor(1)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(1)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(1)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(1)->info().getTags()->getSchemaField()] >= priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentFaceInRegion)->neighbor(1)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(1)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(1)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ } if (!(*currentFaceInRegion)->neighbor(2)->info().hasNoTags()) {
+ if ((*currentFaceInRegion)->neighbor(2)->info().hasOneTag() && (*currentFaceInRegion)->neighbor(2)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->neighbor(2)->info().getTags()->getSchemaField()] < priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentFaceInRegion)->neighbor(2)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->neighbor(2)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->neighbor(2)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTagg) {
+ priorityOfTagg = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ }
+ }
+
+ // Overlap, check this one
+ else {
+ if ((*currentFaceInRegion)->info().hasOneTag() && (*currentFaceInRegion)->info().getTags() != &universe) {
+ if (priorityMap[(*currentFaceInRegion)->info().getTags()->getSchemaField()] < priorityOfTagh) {
+ priorityOfTagh = priorityMap[(*currentFaceInRegion)->info().getTags()->getSchemaField()];
+ tagToAssign = (*currentFaceInRegion)->info().getTags();
+ }
+ } else {
+ MultiPolygonHandle *handle = static_cast<MultiPolygonHandle *>((*currentFaceInRegion)->info().getTags());
+ for (std::list<PolygonHandle *>::const_iterator currentTag = handle->getHandles()->begin(); currentTag != handle->getHandles()->end(); ++currentTag) {
+ if (*currentTag == &universe) continue;
+ if (priorityMap[(*currentTag)->getSchemaField()] < priorityOfTagh) {
+ priorityOfTagh = priorityMap[(*currentTag)->getSchemaField()];
+ tagToAssign = *currentTag;
+ }
+ }
+ }
+ }
+ }
+
+ // Assign the tag to the triangles in the region
+ for (std::set<Triangulation::Face_handle>::iterator currentFaceInRegion = facesInRegion.begin(); currentFaceInRegion != facesInRegion.end(); ++currentFaceInRegion) {
+ facesToRepair.push_back(std::pair<Triangulation::Face_handle, PolygonHandle *>(*currentFaceInRegion, tagToAssign));
+ }
+ }
+ }
+
+ // Re-tag faces in the vector
+ for (std::vector<std::pair<Triangulation::Face_handle, PolygonHandle *> >::iterator currentFace = facesToRepair.begin(); currentFace != facesToRepair.end(); ++currentFace) {
+ currentFace->first->info().removeAllTags();
+ currentFace->first->info().addTag(currentFace->second);
+ }
+
+ return true;
+}
+
+bool IOWorker::matchSchemata(Triangulation &triangulation) {
+
+ std::map<Field *, PolygonHandle *, FieldComparator> fieldMatch;
+ std::map<PolygonHandle *, PolygonHandle *> equivalencies;
+
+ // Find equivalencies
+ for (std::vector<PolygonHandle *>::iterator currentPolygon = polygons.begin(); currentPolygon != polygons.end(); ++currentPolygon) {
+ if (fieldMatch.count((*currentPolygon)->getSchemaField()) == 0) {
+ fieldMatch[(*currentPolygon)->getSchemaField()] = *currentPolygon;
+ equivalencies[*currentPolygon] = *currentPolygon;
+ } else equivalencies[*currentPolygon] = fieldMatch[(*currentPolygon)->getSchemaField()];
+ } std::cout << fieldMatch.size() << " classes found." << std::endl;
+
+ // Re-tag
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ currentFace->info().substituteTagsWith(equivalencies[currentFace->info().getTags()]);
+ }
+
+ return true;
+}
+
+void IOWorker::removeConstraints(Triangulation &triangulation) {
+ // Remove constrained edges that have the same polygon on both sides
+ unsigned long long int constrainedEdgesRemoved = 0;
+ for (Triangulation::All_edges_iterator currentEdge = triangulation.all_edges_begin(); currentEdge != triangulation.all_edges_end(); ++currentEdge) {
+ if (!triangulation.is_constrained(*currentEdge)) continue;
+ if (currentEdge->first->info().getOneTag() == currentEdge->first->neighbor(currentEdge->second)->info().getOneTag()) {
+ triangulation.remove_constrained_edge(currentEdge->first, currentEdge->second);
+ ++constrainedEdgesRemoved;
+ }
+ } std::cout << "\tRemoved " << constrainedEdgesRemoved << " constrained edges" << std::endl;
+}
+
+void IOWorker::removeVertices(Triangulation &triangulation) {
+ // Remove unnecessary vertices completely surrounded by the same polygon
+ // TODO: This can be optimised
+
+ std::cout << "\tBefore: " << triangulation.number_of_faces() << " triangles in the triangulation" << std::endl;
+
+ unsigned long long int surroundedVerticesRemoved = 0;
+ Triangulation::Finite_vertices_iterator currentVertex = triangulation.finite_vertices_begin();
+ while (currentVertex != triangulation.finite_vertices_end()) {
+ if (triangulation.are_there_incident_constraints(currentVertex)) {
+ ++currentVertex;
+ continue;
+ }
+
+ Triangulation::Face_circulator firstFace = triangulation.incident_faces(currentVertex), currentFace = firstFace;
+ ++currentFace;
+ bool allEqual = true;
+ while (currentFace != firstFace) {
+ if (currentFace->info().getOneTag() != firstFace->info().getOneTag()) {
+ allEqual = false;
+ break;
+ } ++currentFace;
+ }
+
+ if (allEqual) {
+ Triangulation::Finite_vertices_iterator vertexToRemove = currentVertex;
+ ++currentVertex;
+
+ Point location = vertexToRemove->point();
+ //Triangulation::Face_handle approximateLocation;
+ PolygonHandle *tag = triangulation.incident_faces(vertexToRemove)->info().getOneTag();
+ triangulation.remove(vertexToRemove);
+ std::stack<Triangulation::Face_handle> stack;
+ Triangulation::Face_handle emptyFace = triangulation.locate(location);
+ stack.push(emptyFace);
+ tagStack(stack, tag);
+
+ ++surroundedVerticesRemoved;
+ } else {
+ ++currentVertex;
+ }
+ } std::cout << "\tRemoved " << surroundedVerticesRemoved << " surrounded vertices" << std::endl;
+
+ std::cout << "\tAfter: " << triangulation.number_of_faces() << " triangles in the triangulation" << std::endl;
+}
+
+bool IOWorker::reconstructPolygons(Triangulation &triangulation, std::vector<std::pair<PolygonHandle *, Polygon> > &outputPolygons) {
+ for (Triangulation::Finite_faces_iterator seedingFace = triangulation.finite_faces_begin(); seedingFace != triangulation.finite_faces_end(); ++seedingFace) {
+ PolygonHandle *currentTag = seedingFace->info().getOneTag();
+ if (currentTag == NULL) continue;
+
+ // STEP 1: Find a suitable seeding triangle (connected to the outer boundary)
+ if (currentTag == &universe) {
+ seedingFace->info().removeAllTags();
+ continue;
+ } if (seedingFace->neighbor(0)->info().getOneTag() == currentTag &&
+ seedingFace->neighbor(1)->info().getOneTag() == currentTag &&
+ seedingFace->neighbor(2)->info().getOneTag() == currentTag) continue;
+
+ // STEP 2: Get boundary
+ seedingFace->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> vertices;
+ if (seedingFace->neighbor(2)->info().hasTag(currentTag)) {
+ seedingFace->neighbor(2)->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> *l2 = getBoundary(seedingFace->neighbor(2), seedingFace->neighbor(2)->index(seedingFace), currentTag);
+ vertices.splice(vertices.end(), *l2);
+ delete l2;
+ } vertices.push_back(seedingFace->vertex(0));
+ if (seedingFace->neighbor(1)->info().hasTag(currentTag)) {
+ seedingFace->neighbor(1)->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> *l1 = getBoundary(seedingFace->neighbor(1), seedingFace->neighbor(1)->index(seedingFace), currentTag);
+ vertices.splice(vertices.end(), *l1);
+ delete l1;
+ } vertices.push_back(seedingFace->vertex(2));
+ if (seedingFace->neighbor(0)->info().hasTag(currentTag)) {
+ seedingFace->neighbor(0)->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> *l0 = getBoundary(seedingFace->neighbor(0), seedingFace->neighbor(0)->index(seedingFace), currentTag);
+ vertices.splice(vertices.end(), *l0);
+ delete l0;
+ } vertices.push_back(seedingFace->vertex(1));
+
+ // STEP 3: Find cutting vertices
+ std::set<Triangulation::Vertex_handle> visitedVertices;
+ std::set<Triangulation::Vertex_handle> repeatedVertices;
+ for (std::list<Triangulation::Vertex_handle>::iterator currentVertex = vertices.begin(); currentVertex != vertices.end(); ++currentVertex) {
+ if (!visitedVertices.insert(*currentVertex).second) repeatedVertices.insert(*currentVertex);
+ } visitedVertices.clear();
+
+ // STEP 4: Cut and join rings in the correct order
+ std::list<std::list<Triangulation::Vertex_handle> *> rings;
+ std::stack<std::list<Triangulation::Vertex_handle> *> chainsStack;
+ std::map<Triangulation::Vertex_handle, std::list<Triangulation::Vertex_handle> *> vertexChainMap;
+ std::list<Triangulation::Vertex_handle> *newChain = new std::list<Triangulation::Vertex_handle>();
+
+ // New vertex
+ for (std::list<Triangulation::Vertex_handle>::iterator currentVertex = vertices.begin(); currentVertex != vertices.end(); ++currentVertex) {
+ // New chain
+ if (repeatedVertices.count(*currentVertex) > 0) {
+ // Closed by itself
+ if (newChain->front() == *currentVertex) {
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) delete newChain;
+ else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+ }
+ // Open by itself
+ else {
+ // Closed with others in stack
+ if (vertexChainMap.count(*currentVertex)) {
+ while (chainsStack.top() != vertexChainMap[*currentVertex]) {
+ newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ } newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ vertexChainMap.erase(*currentVertex);
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) delete newChain;
+ else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+ }
+ // Open
+ else {
+ // Not first chain
+ if (repeatedVertices.count(newChain->front()) > 0) vertexChainMap[newChain->front()] = newChain;
+ chainsStack.push(newChain);
+ }
+ } newChain = new std::list<Triangulation::Vertex_handle>();
+ } newChain->push_back(*currentVertex);
+ }
+
+ // Final ring
+ while (chainsStack.size() > 0) {
+ newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ }
+
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) {
+ delete newChain;
+ } else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+
+ if (chainsStack.size() > 0) std::cout << "Error: Stack has " << chainsStack.size() << " elements. Should be empty." << std::endl;
+
+ // STEP 5: Make a polygon from this list and save it
+ std::vector<Ring> innerRings;
+ Ring outerRing;
+ for (std::list<std::list<Triangulation::Vertex_handle> *>::iterator currentRing = rings.begin(); currentRing != rings.end(); ++currentRing) {
+ Ring newRing;
+ for (std::list<Triangulation::Vertex_handle>::iterator currentPoint = (*currentRing)->begin(); currentPoint != (*currentRing)->end(); ++currentPoint) {
+ newRing.push_back((*currentPoint)->point());
+ } if (newRing.is_clockwise_oriented()) outerRing = newRing;
+ else innerRings.push_back(newRing);
+ } outputPolygons.push_back(std::pair<PolygonHandle *, Polygon>(currentTag, Polygon(outerRing, innerRings.begin(), innerRings.end())));
+ // Free memory from the chains
+ for (std::list<std::list<Triangulation::Vertex_handle> *>::iterator currentRing = rings.begin(); currentRing != rings.end(); ++currentRing) {
+ delete *currentRing;
+ }
+ }
+
+ return true;
+}
+
+bool IOWorker::exportPolygons(std::vector<std::pair<PolygonHandle *, Polygon> > &outputPolygons, const char *file, bool withProvenance) {
+
+ // Prepare file
+ const char *driverName = "ESRI Shapefile";
+ OGRSFDriver *driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driverName);
+ if (driver == NULL) {
+ std::cout << "\tError: OGR Shapefile driver not found." << std::endl;
+ return false;
+ }
+
+ OGRDataSource *dataSource = driver->Open(file, false);
+ if (dataSource != NULL) {
+ std::cout << "\tOverwriting file..." << std::endl;
+ if (driver->DeleteDataSource(dataSource->GetName())!= OGRERR_NONE) {
+ std::cout << "\tError: Couldn't erase file with same name." << std::endl;
+ return false;
+ } OGRDataSource::DestroyDataSource(dataSource);
+ }
+
+ std::cout << "\tWriting file... " << std::endl;
+ dataSource = driver->CreateDataSource(file, NULL);
+ if (dataSource == NULL) {
+ std::cout << "\tError: Could not create file." << std::endl;
+ return false;
+ }
+
+ OGRLayer *layer = dataSource->CreateLayer("polygons", spatialReference, wkbPolygon, NULL);
+ if (layer == NULL) {
+ std::cout << "\tError: Could not create layer." << std::endl;
+ return false;
+ }
+
+ // Set up the fields that there will be
+ if (withProvenance) {
+ unsigned int longest = 0;
+ for (std::vector<char *>::iterator currentFileName = fileNames.begin(); currentFileName != fileNames.end(); ++currentFileName) {
+ if (strlen(*currentFileName) > longest) longest = strlen(*currentFileName);
+ } OGRFieldDefn filenameField("File", OFTString);
+ filenameField.SetWidth(longest);
+ if (layer->CreateField(&filenameField) != OGRERR_NONE) {
+ std::cout << "\tError: Could not create field File." << std::endl;
+ return false;
+ } OGRFieldDefn layerField("Layer", OFTInteger);
+ if (layer->CreateField(&layerField) != OGRERR_NONE) {
+ std::cout << "\tError: Could not create field Layer." << std::endl;
+ return false;
+ }
+ }
+
+ for (std::vector<FieldDefinition *>::iterator currentField = fields.begin(); currentField != fields.end(); ++currentField) {
+ OGRFieldDefn newField((*currentField)->name, (*currentField)->type);
+ newField.SetJustify((*currentField)->justification);
+ newField.SetWidth((*currentField)->width);
+ newField.SetPrecision((*currentField)->precision);
+ if (layer->CreateField(&newField) != OGRERR_NONE) {
+ std::cout << "\tError: Could not create field " << (*currentField)->name << "." << std::endl;
+ return false;
+ }
+ }
+
+ // Put fields in
+ for (std::vector<std::pair<PolygonHandle *, Polygon> >::iterator currentPolygon = outputPolygons.begin(); currentPolygon != outputPolygons.end(); ++currentPolygon) {
+ OGRPolygon polygon;
+ OGRLinearRing outerRing;
+ if (currentPolygon->second.outer_boundary().size() < 1) continue;
+ for (Ring::Vertex_iterator currentVertex = currentPolygon->second.outer_boundary().vertices_begin();
+ currentVertex != currentPolygon->second.outer_boundary().vertices_end();
+ ++currentVertex) {
+ outerRing.addPoint(CGAL::to_double(currentVertex->x()), CGAL::to_double(currentVertex->y()));
+ } outerRing.addPoint(CGAL::to_double(currentPolygon->second.outer_boundary().vertex(0).x()), CGAL::to_double(currentPolygon->second.outer_boundary().vertex(0).y()));
+ polygon.addRing(&outerRing);
+ for (Polygon::Hole_const_iterator currentRing = currentPolygon->second.holes_begin(); currentRing != currentPolygon->second.holes_end(); ++currentRing) {
+ OGRLinearRing innerRing;
+ for (Ring::Vertex_iterator currentVertex = currentRing->vertices_begin(); currentVertex != currentRing->vertices_end(); ++currentVertex) {
+ innerRing.addPoint(CGAL::to_double(currentVertex->x()), CGAL::to_double(currentVertex->y()));
+ } innerRing.addPoint(CGAL::to_double(currentRing->vertex(0).x()), CGAL::to_double(currentRing->vertex(0).y()));
+ polygon.addRing(&innerRing);
+ } OGRFeature *feature = OGRFeature::CreateFeature(layer->GetLayerDefn());
+ if (withProvenance) {
+ feature->SetField("File", currentPolygon->first->getOriginalFile());
+ feature->SetField("Layer", (int)currentPolygon->first->getLayer());
+ } for (unsigned int currentField = 0; currentField < currentPolygon->first->getNumberOfFields(); currentField++) {
+ switch (currentPolygon->first->getField(currentField)->getType()) {
+ case OFTString:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor(currentPolygon->first->getOriginalFile(), currentPolygon->first->getLayer(), currentField)]]->name,
+ currentPolygon->first->getField(currentField)->getValueAsString());
+ break;
+ case OFTReal:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor(currentPolygon->first->getOriginalFile(), currentPolygon->first->getLayer(), currentField)]]->name,
+ currentPolygon->first->getField(currentField)->getValueAsDouble());
+ break;
+ case OFTInteger:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor(currentPolygon->first->getOriginalFile(), currentPolygon->first->getLayer(), currentField)]]->name,
+ currentPolygon->first->getField(currentField)->getValueAsInt());
+ break;
+ default:
+ std::cout << "\tError: Type not implemented." << std::endl;
+ break;
+ }
+ }
+
+ // Put geometry in
+ feature->SetGeometry(&polygon);
+
+ // Create OGR feature
+ if (layer->CreateFeature(feature) != OGRERR_NONE) std::cout << "\tError: Could not create feature." << std::endl;
+
+ // Free OGR feature
+ OGRFeature::DestroyFeature(feature);
+ }
+
+ // Free OGR data source
+ OGRDataSource::DestroyDataSource(dataSource);
+
+ return true;
+}
+
+bool IOWorker::exportTriangulation(Triangulation &t, const char *file, bool withNumberOfTags, bool withFields, bool withProvenance) {
+
+ // Prepare file
+ const char *driverName = "ESRI Shapefile";
+ OGRSFDriver *driver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driverName);
+ if (driver == NULL) {
+ std::cout << "Driver not found." << std::endl;
+ return false;
+ }
+
+ OGRDataSource *dataSource = driver->Open(file, false);
+ if (dataSource != NULL) {
+ std::cout << "Erasing current file..." << std::endl;
+ if (driver->DeleteDataSource(dataSource->GetName())!= OGRERR_NONE) {
+ std::cout << "Couldn't erase current file." << std::endl;
+ return false;
+ } OGRDataSource::DestroyDataSource(dataSource);
+ }
+
+ std::cout << "Writing file... " << std::endl;
+ dataSource = driver->CreateDataSource(file, NULL);
+ if (dataSource == NULL) {
+ std::cout << "Could not create file." << std::endl;
+ return false;
+ }
+
+ OGRLayer *layer = dataSource->CreateLayer("triangles", spatialReference, wkbPolygon, NULL);
+ if (layer == NULL) {
+ std::cout << "Could not create layer." << std::endl;
+ return false;
+ }
+
+ // Set up the fields that there will be
+ if (withNumberOfTags) {
+ OGRFieldDefn numberOfTagsField("Tags", OFTInteger);
+ if (layer->CreateField(&numberOfTagsField) != OGRERR_NONE) {
+ std::cout << "Could not create field Tags." << std::endl;
+ return false;
+ }
+ }
+
+ if (withProvenance) {
+ unsigned int longest = 0;
+ for (std::vector<char *>::iterator currentFileName = fileNames.begin(); currentFileName != fileNames.end(); ++currentFileName) {
+ if (strlen(*currentFileName) > longest) longest = strlen(*currentFileName);
+ } OGRFieldDefn filenameField("File", OFTString);
+ filenameField.SetWidth(longest);
+ if (layer->CreateField(&filenameField) != OGRERR_NONE) {
+ std::cout << "Could not create field Filename." << std::endl;
+ return false;
+ } OGRFieldDefn layerField("Layer", OFTInteger);
+ if (layer->CreateField(&layerField) != OGRERR_NONE) {
+ std::cout << "Could not create field Layer." << std::endl;
+ return false;
+ }
+ }
+
+ if (withFields) {
+ for (std::vector<FieldDefinition *>::iterator currentField = fields.begin(); currentField != fields.end(); ++currentField) {
+ OGRFieldDefn newField((*currentField)->name, (*currentField)->type);
+ newField.SetJustify((*currentField)->justification);
+ newField.SetWidth((*currentField)->width);
+ newField.SetPrecision((*currentField)->precision);
+ if (layer->CreateField(&newField) != OGRERR_NONE) {
+ std::cout << "Could not create field " << (*currentField)->name << "." << std::endl;
+ return false;
+ }
+ }
+ }
+
+ // Put fields in
+ for (CDT::Finite_faces_iterator currentFace = t.finite_faces_begin(); currentFace != t.finite_faces_end(); ++currentFace) {
+ OGRLinearRing ring;
+ ring.addPoint(CGAL::to_double((*(*currentFace).vertex(0)).point().x()), CGAL::to_double((*(*currentFace).vertex(0)).point().y()), 0.0);
+ ring.addPoint(CGAL::to_double((*(*currentFace).vertex(1)).point().x()), CGAL::to_double((*(*currentFace).vertex(1)).point().y()), 0.0);
+ ring.addPoint(CGAL::to_double((*(*currentFace).vertex(2)).point().x()), CGAL::to_double((*(*currentFace).vertex(2)).point().y()), 0.0);
+ ring.addPoint(CGAL::to_double((*(*currentFace).vertex(0)).point().x()), CGAL::to_double((*(*currentFace).vertex(0)).point().y()), 0.0);
+ OGRPolygon polygon;
+ polygon.addRing(&ring);
+ OGRFeature *feature = OGRFeature::CreateFeature(layer->GetLayerDefn());
+ if (withNumberOfTags) {
+
+ // Put number of tags
+ if ((*currentFace).info().getTags() == NULL) {
+ feature->SetField("Tags", 0);
+ } else {
+ feature->SetField("Tags", (int)(*currentFace).info().numberOfTags());
+ }
+
+ // Put number of tags, the universe doesn't count
+ if ((*currentFace).info().getTags() == NULL) {
+ feature->SetField("Tags", 0);
+ } else if ((*currentFace).info().getTags() != &universe) {
+ feature->SetField("Tags", (int)(*currentFace).info().numberOfTags());
+ } else {
+ feature->SetField("Tags", 0);
+ }
+ } if (withProvenance) {
+ if ((*currentFace).info().getTags() == NULL) {
+ feature->SetField("File", "");
+ feature->SetField("Layer", -1);
+ } else {
+ feature->SetField("File", (*currentFace).info().getTags()->getOriginalFile());
+ feature->SetField("Layer", (int)(*currentFace).info().getTags()->getLayer());
+ }
+ } if (withFields && (*currentFace).info().getTags() != NULL) for (unsigned int currentField = 0; currentField < (*currentFace).info().getTags()->getNumberOfFields(); currentField++) {
+ switch ((*currentFace).info().getTags()->getField(currentField)->getType()) {
+ case OFTString:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor((*currentFace).info().getTags()->getOriginalFile(), (*currentFace).info().getTags()->getLayer(), currentField)]]->name,
+ (*currentFace).info().getTags()->getField(currentField)->getValueAsString());
+ case OFTReal:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor((*currentFace).info().getTags()->getOriginalFile(), (*currentFace).info().getTags()->getLayer(), currentField)]]->name,
+ (*currentFace).info().getTags()->getField(currentField)->getValueAsDouble());
+ case OFTInteger:
+ feature->SetField(fields[fieldEquivalencies[FieldDescriptor((*currentFace).info().getTags()->getOriginalFile(), (*currentFace).info().getTags()->getLayer(), currentField)]]->name,
+ (*currentFace).info().getTags()->getField(currentField)->getValueAsInt());
+ break;
+ default:
+ std::cout << "Error: Type not implemented." << std::endl;
+ break;
+ }
+
+ }
+
+ // Put geometry in
+ feature->SetGeometry(&polygon);
+
+ // Create OGR feature
+ if (layer->CreateFeature(feature) != OGRERR_NONE) std::cout << "Could not create feature." << std::endl;
+
+ // Free OGR feature
+ OGRFeature::DestroyFeature(feature);
+ }
+
+ // Free OGR data source
+ OGRDataSource::DestroyDataSource(dataSource);
+
+ return true;
+}
+
+unsigned int IOWorker::removeDuplicateVertices(std::list<Point> &ring) {
+ unsigned int removed = 0;
+ ring.push_back(ring.front());
+ std::list<Point>::iterator previousVertex = ring.begin();
+ std::list<Point>::iterator nextVertex = previousVertex;
+ ++nextVertex;
+ while (nextVertex != ring.end()) {
+ if (*previousVertex == *nextVertex) {
+ nextVertex = ring.erase(nextVertex);
+ ++removed;
+ } else {
+ ++previousVertex;
+ ++nextVertex;
+ }
+ } ring.pop_back();
+ return removed;
+}
+
+std::vector<Ring *> IOWorker::splitRing(Ring &ring) {
+ std::vector<Ring *> outputRings;
+
+ // STEP 1: Put the edges in a triangulation
+ Triangulation ringTriangulation;
+ startingSearchFaceInRing = Triangulation::Face_handle();
+ for (Ring::Edge_const_iterator currentEdge = ring.edges_begin(); currentEdge != ring.edges_end(); ++currentEdge) {
+ Triangulation::Vertex_handle source = ringTriangulation.insert(currentEdge->source(), startingSearchFaceInRing);
+ startingSearchFaceInRing = ringTriangulation.incident_faces(source);
+ Triangulation::Vertex_handle target = ringTriangulation.insert(currentEdge->target(), startingSearchFaceInRing);
+ Triangulation::Face_handle correspondingFace;
+ int correspondingVertex;
+ // Remove identical degenerate edges
+ if (ringTriangulation.is_edge(source, target, correspondingFace, correspondingVertex)) {
+ if (ringTriangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(correspondingFace, correspondingVertex))) {
+ //std::cout << "Removing duplicate constraint <" << *source << ", " << *target << ">" << std::endl;
+ ringTriangulation.remove_constraint(source, target);
+ continue;
+ }
+ } //std::cout << "Inserting constraint <" << *source << ", " << *target << ">" << std::endl;
+ ringTriangulation.insert_constraint(source, target);
+ startingSearchFaceInRing = ringTriangulation.incident_faces(target);
+ }
+
+ // Free space of the old ring
+ ring.clear();
+
+ // STEP 2: Remove degenerate edges (not identical, so not caught during creation)
+ for (Triangulation::Subconstraint_iterator currentEdge = ringTriangulation.subconstraints_begin();
+ currentEdge != ringTriangulation.subconstraints_end();
+ ++currentEdge) {
+ //std::cout << "Checking subconstraint: <" << *(currentEdge->first.first) << ", " << *(currentEdge->first.second) << ">: " << ringTriangulation.number_of_enclosing_constraints(currentEdge->first.first, currentEdge->first.second) << " enclosing constraints." << std::endl;
+ // Subconstraint_iterator has a weird return value...
+ if (ringTriangulation.number_of_enclosing_constraints(currentEdge->first.first, currentEdge->first.second) % 2 == 0) {
+ Triangulation::Face_handle f;
+ int i;
+ ringTriangulation.is_edge(currentEdge->first.first, currentEdge->first.second, f, i);
+ if (ringTriangulation.is_constrained(std::pair<Triangulation::Face_handle, int>(f, i))) {
+ //std::cout << "Removing constraint..." << std::endl;
+ ringTriangulation.remove_constraint(currentEdge->first.first, currentEdge->first.second);
+ } else {
+ //std::cout << "Adding constraint..." << std::endl;
+ ringTriangulation.insert_constraint(currentEdge->first.first, currentEdge->first.second);
+ }
+ }
+ }
+
+ // STEP 3: Tag triangles
+ PolygonHandle interior, exterior;
+ std::stack<Triangulation::Face_handle> interiorStack, exteriorStack;
+ exteriorStack.push(ringTriangulation.infinite_face());
+ tagStack(interiorStack, exteriorStack, &interior, &exterior);
+
+ // STEP 4: Get chains representing boundaries
+ Triangulation::Face_handle seedingFace;
+ std::vector<std::list<Triangulation::Vertex_handle> *> verticesList;
+ for (Triangulation::Finite_faces_iterator seedingFace = ringTriangulation.finite_faces_begin(); seedingFace != ringTriangulation.finite_faces_end(); ++seedingFace) {
+
+ if (seedingFace->info().getTags() != &interior) continue;
+
+ std::list<Triangulation::Vertex_handle> *vertices = new std::list<Triangulation::Vertex_handle>();
+ seedingFace->info().setTags(NULL);
+
+ if (seedingFace->neighbor(2)->info().getTags() == &interior) {
+ seedingFace->neighbor(2)->info().setTags(NULL);
+ std::list<Triangulation::Vertex_handle> *l2 = getBoundary(seedingFace->neighbor(2), seedingFace->neighbor(2)->index(seedingFace), &interior);
+ vertices->splice(vertices->end(), *l2);
+ delete l2;
+ } vertices->push_back(seedingFace->vertex(0));
+ if (seedingFace->neighbor(1)->info().getTags() == &interior) {
+ seedingFace->neighbor(1)->info().setTags(NULL);
+ std::list<Triangulation::Vertex_handle> *l1 = getBoundary(seedingFace->neighbor(1), seedingFace->neighbor(1)->index(seedingFace), &interior);
+ vertices->splice(vertices->end(), *l1);
+ delete l1;
+ } vertices->push_back(seedingFace->vertex(2));
+ if (seedingFace->neighbor(0)->info().getTags() == &interior) {
+ seedingFace->neighbor(0)->info().setTags(NULL);
+ std::list<Triangulation::Vertex_handle> *l0 = getBoundary(seedingFace->neighbor(0), seedingFace->neighbor(0)->index(seedingFace), &interior);
+ vertices->splice(vertices->end(), *l0);
+ delete l0;
+ } vertices->push_back(seedingFace->vertex(1));
+
+ verticesList.push_back(vertices);
+ }
+
+ // From now on, process each list...
+ for (std::vector<std::list<Triangulation::Vertex_handle> *>::iterator currentVerticesList = verticesList.begin(); currentVerticesList != verticesList.end(); ++currentVerticesList) {
+
+ // STEP 5: Find cutting vertices
+ std::set<Triangulation::Vertex_handle> visitedVertices;
+ std::set<Triangulation::Vertex_handle> repeatedVertices;
+ for (std::list<Triangulation::Vertex_handle>::iterator currentVertex = (*currentVerticesList)->begin(); currentVertex != (*currentVerticesList)->end(); ++currentVertex) {
+ if (!visitedVertices.insert(*currentVertex).second) repeatedVertices.insert(*currentVertex);
+ } visitedVertices.clear();
+
+ // STEP 6: Cut and join rings in the correct order
+ std::list<std::list<Triangulation::Vertex_handle> *> rings;
+ std::stack<std::list<Triangulation::Vertex_handle> *> chainsStack;
+ std::map<Triangulation::Vertex_handle, std::list<Triangulation::Vertex_handle> *> vertexChainMap;
+ std::list<Triangulation::Vertex_handle> *newChain = new std::list<Triangulation::Vertex_handle>();
+ for (std::list<Triangulation::Vertex_handle>::iterator currentVertex = (*currentVerticesList)->begin(); currentVertex != (*currentVerticesList)->end(); ++currentVertex) {
+ // New chain
+ if (repeatedVertices.count(*currentVertex) > 0) {
+ // Closed by itself
+ if (newChain->front() == *currentVertex) {
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) delete newChain;
+ else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+ }
+
+ // Open by itself
+ else {
+ // Closed with others in stack
+ if (vertexChainMap.count(*currentVertex)) {
+ while (chainsStack.top() != vertexChainMap[*currentVertex]) {
+ newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ } newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ vertexChainMap.erase(*currentVertex);
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) delete newChain;
+ else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+ }
+
+ // Open
+ else {
+ // Not first chain
+ if (repeatedVertices.count(newChain->front()) > 0) vertexChainMap[newChain->front()] = newChain;
+ chainsStack.push(newChain);
+ }
+ } newChain = new std::list<Triangulation::Vertex_handle>();
+ } newChain->push_back(*currentVertex);
+ }
+
+ // Final ring
+ while (chainsStack.size() > 0) {
+ newChain->splice(newChain->begin(), *chainsStack.top());
+ chainsStack.pop();
+ }
+
+ // Degenerate (insufficient vertices to be valid)
+ if (newChain->size() < 3) delete newChain;
+ else {
+ std::list<Triangulation::Vertex_handle>::iterator secondElement = newChain->begin();
+ ++secondElement;
+ // Degenerate (zero area)
+ if (newChain->back() == *secondElement) delete newChain;
+ // Valid
+ else rings.push_back(newChain);
+ }
+
+ // STEP 7: Make rings from these lists and save them
+ for (std::list<std::list<Triangulation::Vertex_handle> *>::iterator currentRing = rings.begin(); currentRing != rings.end(); ++currentRing) {
+ Ring *newRing = new Ring();
+ for (std::list<Triangulation::Vertex_handle>::iterator currentVertex = (*currentRing)->begin(); currentVertex != (*currentRing)->end(); ++currentVertex) {
+ newRing->push_back((*currentVertex)->point());
+ } outputRings.push_back(newRing);
+ }
+
+ // Free memory from the chains
+ for (std::list<std::list<Triangulation::Vertex_handle> *>::iterator currentRing = rings.begin(); currentRing != rings.end(); ++currentRing) delete *currentRing;
+
+ // Free memory from the vertices lists
+ delete *currentVerticesList;
+ }
+
+ // Free memory from the triangulation
+ ringTriangulation.clear();
+
+ std::cout << "\tCreated " << outputRings.size() << " rings." << std::endl;
+ return outputRings;
+}
+
+void IOWorker::testRings(std::vector<Ring *> &outerRings, std::vector<Ring *> &innerRings, std::vector<std::vector<Ring> > &classification, long fid) {
+ Triangulation ringsTriangulation;
+ startingSearchFaceInRing = Triangulation::Face_handle();
+ std::vector<std::vector<Triangulation::Vertex_handle> > ringsToTag;
+ std::vector<PolygonHandle *> tags;
+ tags.reserve(outerRings.size());
+ std::map<PolygonHandle *, unsigned int> tagsMap;
+
+ // STEP 1: Put the edges from the outer rings in the triangulation and save them for tagging
+ for (std::vector<Ring *>::iterator currentRing = outerRings.begin(); currentRing != outerRings.end(); ++currentRing) {
+ ringsToTag.push_back(std::vector<Triangulation::Vertex_handle>());
+ tags.push_back(new PolygonHandle());
+ tagsMap[tags.back()] = tags.size()-1;
+ for (Ring::Edge_const_iterator currentEdge = (*currentRing)->edges_begin(); currentEdge != (*currentRing)->edges_end(); ++currentEdge) {
+ Triangulation::Vertex_handle source = ringsTriangulation.insert(currentEdge->source(), startingSearchFaceInRing);
+ startingSearchFaceInRing = ringsTriangulation.incident_faces(source);
+ Triangulation::Vertex_handle target = ringsTriangulation.insert(currentEdge->target(), startingSearchFaceInRing);
+ ringsTriangulation.insert_constraint(source, target);
+ startingSearchFaceInRing = ringsTriangulation.incident_faces(target);
+ ringsToTag.back().push_back(source);
+ } ringsToTag.back().push_back(ringsToTag.back().front());
+ }
+
+ // STEP 2: Tag triangles
+ Triangulation::Face_handle currentFace;
+ int incident;
+ std::stack<Triangulation::Face_handle> stack;
+ for (unsigned int currentRing = 0; currentRing < ringsToTag.size(); ++currentRing) {
+ for (unsigned int currentVertex = 1; currentVertex < ringsToTag[currentRing].size(); ++currentVertex) {
+ if (!ringsTriangulation.is_edge(ringsToTag[currentRing].at(currentVertex-1), ringsToTag[currentRing].at(currentVertex), currentFace, incident)) {
+ std::cout << "\tError: Cannot find adjoining face to an edge from the edge list!" << std::endl;
+ } stack.push(currentFace);
+ } tagStack(stack, tags[currentRing]);
+ }
+
+ // Tag the universe
+ stack.push(ringsTriangulation.infinite_face());
+ tagStack(stack, &universe);
+
+ // Free memory
+ ringsToTag.clear();
+
+ // STEP 3: Check where inner rings belong
+ for (std::vector<Ring *>::iterator currentRing = innerRings.begin(); currentRing != innerRings.end(); ++currentRing) {
+ std::set<unsigned int> addedTo;
+ for (Ring::Edge_const_iterator currentEdge = (*currentRing)->edges_begin(); currentEdge != (*currentRing)->edges_end(); ++currentEdge) {
+ Triangulation::Locate_type locateType;
+ int locateIndex;
+ Triangulation::Face_handle location = ringsTriangulation.locate(currentEdge->source(), locateType, locateIndex, startingSearchFaceInRing);
+ startingSearchFaceInRing = location;
+ if (locateType == Triangulation::FACE) {
+ PolygonHandle *tag = location->info().getTags();
+ if (tagsMap.count(tag) > 0) {
+ unsigned int tagIndex = tagsMap[tag];
+ if (addedTo.count(tagIndex) == 0) {
+ addedTo.insert(tagIndex);
+ classification[tagIndex].push_back(**currentRing);
+ }
+ } else {
+ std::cout << "\tFeature #" << fid << ": inner boundary vertex outside outer boundary. Using other vertices..." << std::endl;
+ }
+ }
+ } if (addedTo.size() < 1) std::cout << "\tFeature #" << fid << ": inner boundary cannot fit in any outer boundary. Skipped." << std::endl;
+ else if (addedTo.size() > 1) std::cout << "\tFeature #" << fid << ": inner boundary fits in more than one OB. Added to all." << std::endl;
+ }
+}
+
+void IOWorker::copyFields(OGRFeature *ogrfeature, PolygonHandle *handle) {
+ Field *newField;
+ for (int i = 0; i < ogrfeature->GetFieldCount(); i++) {
+ switch (ogrfeature->GetFieldDefnRef(i)->GetType()) {
+ case OFTString:
+ newField = new StringField(ogrfeature->GetFieldAsString(i));
+ break;
+ case OFTReal:
+ newField = new DoubleField(ogrfeature->GetFieldAsDouble(i));
+ break;
+ case OFTInteger:
+ newField = new IntField(ogrfeature->GetFieldAsInteger(i));
+ break;
+ default:
+ std::cout << "\tError: Field type not supported. Skipped." << std::endl;
+ continue;
+ break;
+ } handle->addField(newField);
+ }
+}
+
+void IOWorker::tagStack(std::stack<Triangulation::Face_handle> &positiveStack, std::stack<Triangulation::Face_handle> &negativeStack, PolygonHandle *positiveHandle, PolygonHandle *negativeHandle) {
+ //std::cout << "tagStack() Infinite vertex at: " << std::endl;
+ while (!positiveStack.empty() || !negativeStack.empty()) {
+ //std::cout << "positiveStack: " << positiveStack.size() << " negativeStack: " << negativeStack.size() << std::endl;
+ if (positiveStack.empty()) {
+ Triangulation::Face_handle currentFace = negativeStack.top();
+ //std::cout << "Triangle: <" << *(currentFace->vertex(0)) << ", " << *(currentFace->vertex(1)) << ", " << *(currentFace->vertex(2)) << ">" << std::endl;
+ negativeStack.pop();
+ currentFace->info().setTags(negativeHandle);
+ if (currentFace->is_constrained(0)) {
+ if (currentFace->neighbor(0)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(0)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(0));
+ }
+ } else {
+ if (currentFace->neighbor(0)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(0)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(0));
+ }
+ } if (currentFace->is_constrained(1)) {
+ if (currentFace->neighbor(1)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(1)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(1));
+ }
+ } else {
+ if (currentFace->neighbor(1)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(1)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(1));
+ }
+ } if (currentFace->is_constrained(2)) {
+ if (currentFace->neighbor(2)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(2)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(2));
+ }
+ } else {
+ if (currentFace->neighbor(2)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(2)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(2));
+ }
+ }
+ } else {
+ Triangulation::Face_handle currentFace = positiveStack.top();
+ //std::cout << "Triangle: <" << *(currentFace->vertex(0)) << ", " << *(currentFace->vertex(1)) << ", " << *(currentFace->vertex(2)) << ">" << std::endl;
+ positiveStack.pop();
+ currentFace->info().setTags(positiveHandle);
+ if (currentFace->is_constrained(0)) {
+ if (currentFace->neighbor(0)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(0)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(0));
+ }
+ } else {
+ if (currentFace->neighbor(0)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(0)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(0));
+ }
+ } if (currentFace->is_constrained(1)) {
+ if (currentFace->neighbor(1)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(1)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(1));
+ }
+ } else {
+ if (currentFace->neighbor(1)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(1)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(1));
+ }
+ } if (currentFace->is_constrained(2)) {
+ if (currentFace->neighbor(2)->info().getTags() != negativeHandle) {
+ currentFace->neighbor(2)->info().setTags(negativeHandle);
+ negativeStack.push(currentFace->neighbor(2));
+ }
+ } else {
+ if (currentFace->neighbor(2)->info().getTags() != positiveHandle) {
+ currentFace->neighbor(2)->info().setTags(positiveHandle);
+ positiveStack.push(currentFace->neighbor(2));
+ }
+ }
+ }
+ }
+}
+
+void IOWorker::tagStack(std::stack<Triangulation::Face_handle> &stack, PolygonHandle *handle) {
+ while (!stack.empty()) {
+ Triangulation::Face_handle currentFace = stack.top();
+ stack.pop();
+ currentFace->info().addTag(handle);
+ if (!currentFace->neighbor(0)->info().hasTag(handle) && !currentFace->is_constrained(0)) {
+ currentFace->neighbor(0)->info().addTag(handle);
+ stack.push(currentFace->neighbor(0));
+ } if (!currentFace->neighbor(1)->info().hasTag(handle) && !currentFace->is_constrained(1)) {
+ currentFace->neighbor(1)->info().addTag(handle);
+ stack.push(currentFace->neighbor(1));
+ } if (!currentFace->neighbor(2)->info().hasTag(handle) && !currentFace->is_constrained(2)) {
+ currentFace->neighbor(2)->info().addTag(handle);
+ stack.push(currentFace->neighbor(2));
+ }
+ }
+}
+
+std::list<Triangulation::Vertex_handle> * IOWorker::getBoundary(Triangulation::Face_handle face, int edge, PolygonHandle *polygon) {
+ std::list<Triangulation::Vertex_handle> *vertices = new std::list<Triangulation::Vertex_handle>();
+
+ // Check clockwise edge
+ if (!face->is_constrained(face->cw(edge)) && !face->neighbor(face->cw(edge))->info().hasNoTags()) {
+ face->neighbor(face->cw(edge))->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> *v1 = getBoundary(face->neighbor(face->cw(edge)), face->neighbor(face->cw(edge))->index(face), polygon);
+ vertices->splice(vertices->end(), *v1);
+ delete v1;
+ }
+
+ // Add central vertex
+ vertices->push_back(face->vertex(edge));
+
+ // Check counterclockwise edge
+ if (!face->is_constrained(face->ccw(edge)) && !face->neighbor(face->ccw(edge))->info().hasNoTags()) {
+ face->neighbor(face->ccw(edge))->info().removeAllTags();
+ std::list<Triangulation::Vertex_handle> *v2 = getBoundary(face->neighbor(face->ccw(edge)), face->neighbor(face->ccw(edge))->index(face), polygon);
+ vertices->splice(vertices->end(), *v2);
+ delete v2;
+ }
+
+ return vertices;
+}
+
+void IOWorker::addtoCount(std::map<PolygonHandle *, unsigned int> &count, PolygonHandle *ph) {
+ if (ph == NULL) return;
+ if (ph->isMultiPolygonHandle()) {
+ MultiPolygonHandle *mph = static_cast<MultiPolygonHandle *>(ph);
+ for (std::list<PolygonHandle *>::const_iterator currentPolygonHandle = mph->getHandles()->begin(); currentPolygonHandle != mph->getHandles()->end(); ++currentPolygonHandle) {
+ if (count.count(*currentPolygonHandle)) count[*currentPolygonHandle]++;
+ else count[*currentPolygonHandle] = 1;
+ }
+ } else {
+ if (count.count(ph)) count[ph]++;
+ else count[ph] = 1;
+ }
+}
+
+void IOWorker::addToLength(std::map<PolygonHandle *, double> &lengths, PolygonHandle *ph, double length) {
+ if (ph == NULL) return;
+ if (ph->isMultiPolygonHandle()) {
+ MultiPolygonHandle *mph = static_cast<MultiPolygonHandle *>(ph);
+ for (std::list<PolygonHandle *>::const_iterator currentPolygonHandle = mph->getHandles()->begin(); currentPolygonHandle != mph->getHandles()->end(); ++currentPolygonHandle) {
+ if (lengths.count(*currentPolygonHandle)) lengths[*currentPolygonHandle] += length;
+ else lengths[*currentPolygonHandle] = length;
+ }
+ } else {
+ if (lengths.count(ph)) lengths[ph] += length;
+ else lengths[ph] = length;
+ }
+}
+
+void IOWorker::insertToStream(std::ostream &ostr, OGRFeatureDefn *layerDefinition, unsigned int indentation, int schemaIndex) {
+ ostr << std::endl;
+ for (int currentField = 0; currentField < layerDefinition->GetFieldCount(); currentField++) {
+ OGRFieldDefn *fieldDefinition = layerDefinition->GetFieldDefn(currentField);
+ if (currentField == schemaIndex) ostr << ">";
+ for (unsigned int i = 0; i <= indentation; i++) ostr << "\t";
+ insertToStream(ostr, fieldDefinition->GetType());
+ ostr << "\t" << fieldDefinition->GetNameRef() << std::endl;
+ }
+}
+
+void IOWorker::insertToStream(std::ostream &ostr, const OGRFieldType &ft) {
+ switch (ft) {
+ case OFTInteger:
+ ostr << "int ";
+ break;
+ case OFTIntegerList:
+ ostr << "int[] ";
+ break;
+ case OFTReal:
+ ostr << "double ";
+ break;
+ case OFTRealList:
+ ostr << "double[] ";
+ break;
+ case OFTString:
+ ostr << "string ";
+ break;
+ case OFTStringList:
+ ostr << "string[] ";
+ break;
+ case OFTWideString:
+ ostr << "deprecated ";
+ break;
+ case OFTWideStringList:
+ ostr << "deprecated ";
+ break;
+ case OFTBinary:
+ ostr << "binary data";
+ break;
+ case OFTDate:
+ ostr << "date ";
+ break;
+ case OFTTime:
+ ostr << "time ";
+ break;
+ case OFTDateTime:
+ ostr << "date & time";
+ break;
+ default:
+ ostr << "unknown ";
+ break;
+ }
+}
+
+void IOWorker::insertToStream(std::ostream &ostr, const OGRwkbGeometryType >) {
+ switch (gt) {
+ case wkbUnknown:
+ ostr << "unknown";
+ break;
+ case wkbPoint:
+ ostr << "point";
+ break;
+ case wkbLineString:
+ ostr << "line string";
+ break;
+ case wkbPolygon:
+ ostr << "polygon";
+ break;
+ case wkbMultiPoint:
+ ostr << "multi point";
+ break;
+ case wkbMultiLineString:
+ ostr << "multi line string";
+ break;
+ case wkbMultiPolygon:
+ ostr << "multi polygon";
+ break;
+ case wkbGeometryCollection:
+ ostr << "geometry collection";
+ break;
+ case wkbNone:
+ ostr << "none";
+ break;
+ case wkbLinearRing:
+ ostr << "linear ring";
+ break;
+ case wkbPoint25D:
+ ostr << "2.5D point";
+ break;
+ case wkbLineString25D:
+ ostr << "2.5D line string";
+ break;
+ case wkbPolygon25D:
+ ostr << "2.5D polygon";
+ break;
+ case wkbMultiPoint25D:
+ ostr << "2.5D multi point";
+ break;
+ case wkbMultiLineString25D:
+ ostr << "2.5D multi line string";
+ break;
+ case wkbMultiPolygon25D:
+ ostr << "2.5D multi polygon";
+ break;
+ case wkbGeometryCollection25D:
+ ostr << "2.5D geometry collection";
+ break;
+ default:
+ ostr << "other";
+ break;
+ }
+}
+
+void IOWorker::insertTriangulationInfo(std::ostream &ostr, const Triangulation &t) {
+ // Number of tags
+ unsigned int untagged = 0, onetag = 0, multipletags = 0, total;
+ for (Triangulation::Finite_faces_iterator currentFace = t.finite_faces_begin(); currentFace != t.finite_faces_end(); ++currentFace) {
+ if ((*currentFace).info().hasNoTags()) untagged++;
+ else if ((*currentFace).info().hasOneTag()) onetag++;
+ else multipletags++;
+ } total = onetag + multipletags + untagged;
+ ostr << "\tHoles: " << untagged << " triangles (" << 100.0*untagged/total << " %)" << std::endl <<
+ "\tOk: " << onetag << " triangles (" << 100.0*onetag/total << " %)" << std::endl <<
+ "\tOverlaps: " << multipletags << " triangles (" << 100.0*multipletags/total << " %)" << std::endl;
+
+ // Other info?
+}
\ No newline at end of file
diff --git a/IOWorker.h b/IOWorker.h
new file mode 100644
index 0000000..600344c
--- /dev/null
+++ b/IOWorker.h
@@ -0,0 +1,146 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef IOWORKER_H
+#define IOWORKER_H
+
+#include "FaceInfo.h"
+#include "definitions/CGALDefinitions.h"
+
+class IOWorker {
+public:
+ // Construction
+ IOWorker();
+
+ // Main operations
+ bool addToTriangulation(Triangulation &triangulation, TaggingVector &edgesToTag, const char *file, unsigned int schemaIndex);
+ bool tagTriangulation(Triangulation &triangulation, TaggingVector &edgesToTag);
+ bool makeAllHolesValid(Triangulation &triangulation);
+ bool splitRegions(Triangulation &triangulation, double ratio);
+ bool repairTrianglesByNumberOfNeighbours(Triangulation &triangulation, bool alsoUniverse);
+ bool repairTrianglesByAbsoluteMajority(Triangulation &triangulation, bool alsoUniverse);
+ bool repairTrianglesByLongestBoundary(Triangulation &triangulation, bool alsoUniverse);
+ bool repairRegionsByLongestBoundary(Triangulation &triangulation, bool alsoUniverse);
+ bool repairRegionsByRandomNeighbour(Triangulation &triangulation, bool alsoUniverse);
+ bool repairByPriorityList(Triangulation &triangulation, const char *file);
+ bool repairEdgeMatching(Triangulation &triangulation, const char *file);
+ bool matchSchemata(Triangulation &triangulation);
+ void removeConstraints(Triangulation &triangulation);
+ void removeVertices(Triangulation &triangulation);
+ bool reconstructPolygons(Triangulation &triangulation, std::vector<std::pair<PolygonHandle *, Polygon> > &outputPolygons);
+ bool exportPolygons(std::vector<std::pair<PolygonHandle *, Polygon> > &outputPolygons, const char *file, bool withProvenance);
+ bool exportTriangulation(Triangulation &t, const char *file, bool withNumberOfTags, bool withFields, bool withProvenance);
+
+ // Printing functions
+ void insertToStream(std::ostream &ostr, OGRFeatureDefn *layerDefinition, unsigned int indentation = 0, int schemaIndex = -1);
+ void insertToStream(std::ostream &ostr, const OGRFieldType &ft);
+ void insertToStream(std::ostream &ostr, const OGRwkbGeometryType >);
+ void insertTriangulationInfo(std::ostream &ostr, const Triangulation &t);
+
+private:
+ // Data structures
+ struct FieldDescriptor {
+ char *file;
+ int layer;
+ int field;
+
+ FieldDescriptor(char *fl, int l, int fld) {
+ file = fl;
+ layer = l;
+ field = fld;
+ }
+
+ bool operator<(const FieldDescriptor &fe) const {
+ //std::cout << "COMP {" << std::endl << "\t" << file << "\t" << layer << "\t" << field << std::endl << "\t" << fe.file << "\t" << fe.layer << "\t" << fe.field << std::endl;
+ if (file < fe.file) return true;
+ if (file > fe.file) return false;
+ if (layer < fe.layer) return true;
+ if (layer > fe.layer) return false;
+ if (field < fe.field) return true;
+ return false;
+ }
+ };
+
+ struct FieldDefinition {
+ char *name;
+ OGRFieldType type;
+ OGRJustification justification;
+ int width;
+ int precision;
+
+ FieldDefinition(const char *n, OGRFieldType t, OGRJustification j, int w, int p) {
+ name = new char[strlen(n)+1];
+ strcpy(name, n);
+ type = t;
+ justification = j;
+ width = w;
+ precision = p;
+ }
+
+ ~FieldDefinition() {
+ delete name;
+ }
+
+ bool matches(FieldDefinition *f) {
+ // For the moment, only exact matches.
+ // if we had reference data, we could match them together (change values to the ones of the reference and return true)
+ if (strcmp(name, f->name) != 0) return false;
+ if (type != f->type) return false;
+ if (justification != f->justification) return false;
+ if (width != f->width) return false;
+ if (precision != f->precision) return false;
+ return true;
+ }
+ };
+
+ struct FieldComparator {
+ bool operator() (Field * const &f1, Field * const &f2) const {
+ return (*f1) < (*f2);
+ }
+ };
+
+ // What is kept from input
+ std::vector<char *> fileNames;
+ std::vector<PolygonHandle *> polygons;
+ OGRFieldType schemaFieldType;
+ std::vector<FieldDefinition *> fields;
+ std::map<FieldDescriptor, unsigned int> fieldEquivalencies;
+ OGRSpatialReference* spatialReference;
+
+ // Internal special tags
+ PolygonHandle universe;
+
+ // Cached values
+ Triangulation::Face_handle startingSearchFace, startingSearchFaceInRing; // faces that are expected to be close to the next point to be added
+
+ // Helper functions
+ unsigned int removeDuplicateVertices(std::list<Point> &ring);
+ std::vector<Ring *> splitRing(Ring &ring);
+ void testRings(std::vector<Ring *> &outerRings, std::vector<Ring *> &innerRings, std::vector<std::vector<Ring> > &classification, long fid);
+ void copyFields(OGRFeature *ogrfeature, PolygonHandle *handle);
+ void tagStack(std::stack<Triangulation::Face_handle> &positiveStack, std::stack<Triangulation::Face_handle> &negativeStack, PolygonHandle *positiveHandle, PolygonHandle *negativeHandle);
+ void tagStack(std::stack<Triangulation::Face_handle> &stack, PolygonHandle *handle);
+ std::list<Triangulation::Vertex_handle> *getBoundary(Triangulation::Face_handle face, int edge, PolygonHandle *polygon);
+ void addtoCount(std::map<PolygonHandle *, unsigned int> &count, PolygonHandle *ph);
+ void addToLength(std::map<PolygonHandle *, double> &lengths, PolygonHandle *ph, double length);
+};
+
+#endif
\ No newline at end of file
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/PlanarPartition.cpp b/PlanarPartition.cpp
new file mode 100644
index 0000000..b8e602b
--- /dev/null
+++ b/PlanarPartition.cpp
@@ -0,0 +1,383 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#include "PlanarPartition.h"
+
+PlanarPartition::PlanarPartition() {
+ // Registers drivers for all supported formats in OGR
+ OGRRegisterAll();
+
+ // Set internal states
+ state = CREATED;
+
+ // std::cout precision (for debugging)
+ std::cout.setf(std::ios::fixed,std::ios::floatfield);
+ std::cout.precision(6);
+}
+
+PlanarPartition::~PlanarPartition() {
+ triangulation.clear();
+}
+
+bool PlanarPartition::addToTriangulation(const char *file, unsigned int schemaIndex) {
+
+ // Check if we have already made changes to the triangulation
+ if (state > TRIANGULATED) {
+ std::cerr << "Error: The triangulation has already been tagged. It cannot be modified!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Adding a new set of polygons to the triangulation..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool returnValue = io.addToTriangulation(triangulation, edgesToTag, file, schemaIndex);
+ if (triangulation.number_of_faces() > 0) state = TRIANGULATED;
+
+ // Triangulation stats
+ std::cout << "Polygons added (" << time(NULL)-thisTime << " s). The triangulation has now:" << std::endl;
+ std::cout << "\tVertices: " << triangulation.number_of_vertices() << std::endl;
+ std::cout << "\tEdges: " << triangulation.tds().number_of_edges() << std::endl;
+ std::cout << "\tTriangles: " << triangulation.number_of_faces() << std::endl;
+
+ return returnValue;
+}
+
+bool PlanarPartition::tagTriangulation() {
+
+ if (state < TRIANGULATED) {
+ std::cout << "No triangulation to tag!" << std::endl;
+ return false;
+ } if (state > TRIANGULATED) {
+ std::cout << "Triangulation already tagged!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Tagging..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool returnValue = io.tagTriangulation(triangulation, edgesToTag);
+
+ // Mark as tagged (for export)
+ if (returnValue) state = TAGGED;
+
+ std::cout << "Tagging done (" << time(NULL)-thisTime << " s)." << std::endl;
+
+ return true;
+}
+
+bool PlanarPartition::makeAllHolesValid() {
+ return io.makeAllHolesValid(triangulation);
+}
+
+bool PlanarPartition::checkValidity() {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot check!" << std::endl;
+ return false;
+ } if (state >= REPAIRED) return true;
+
+ for (Triangulation::Finite_faces_iterator currentFace = triangulation.finite_faces_begin(); currentFace != triangulation.finite_faces_end(); ++currentFace) {
+ if (!(*currentFace).info().hasOneTag()) return true; // true means successful operation, not that everything is valid
+ }
+
+ state = REPAIRED;
+ return true;
+}
+
+bool PlanarPartition::splitRegions(double ratio) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot split!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Splitting regions..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ if (ratio <= 1.0) return false;
+
+ bool returnValue = io.splitRegions(triangulation, ratio);
+
+ std::cout << "\tRegions split (" << time(NULL)-thisTime << " s)." << std::endl;
+
+ return returnValue;
+}
+
+bool PlanarPartition::repairTrianglesByNumberOfNeighbours(bool alsoUniverse) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing triangles by number of neighbours..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairTrianglesByNumberOfNeighbours(triangulation, alsoUniverse);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairTrianglesByAbsoluteMajority(bool alsoUniverse) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing triangles by absolute majority..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairTrianglesByAbsoluteMajority(triangulation, alsoUniverse);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairTrianglesByLongestBoundary(bool alsoUniverse) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing triangles by longest boundary..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairTrianglesByLongestBoundary(triangulation, alsoUniverse);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairRegionsByLongestBoundary(bool alsoUniverse) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing regions by longest boundary..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairRegionsByLongestBoundary(triangulation, alsoUniverse);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairRegionsByRandomNeighbour(bool alsoUniverse) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing regions by random neighbour..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairRegionsByRandomNeighbour(triangulation, alsoUniverse);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairByPriorityList(const char *file) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing by priority list..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairByPriorityList(triangulation, file);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::repairEdgeMatching(const char *file) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not yet tagged. Cannot repair!" << std::endl;
+ return false;
+ } if (state > TAGGED) {
+ std::cout << "Triangulation already repaired!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Repairing by priority list..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool repaired = io.repairEdgeMatching(triangulation, file);
+
+ if (repaired) {
+ std::cout << "Repair successful (" << time(NULL)-thisTime << " s). All polygons are now valid." << std::endl;
+ } else {
+ std::cout << "Repair of all polygons not possible (" << time(NULL)-thisTime << " s)." << std::endl;
+ }
+
+ // Return whether the planar partition is now valid
+ if (repaired) state = REPAIRED;
+ return repaired;
+}
+
+bool PlanarPartition::matchSchemata() {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not tagged. Cannot match schemata!" << std::endl;
+ return false;
+ } if (state < REPAIRED) std::cout << "Warning: Triangulation not yet repaired. There could be errors..." << std::endl;
+ if (state > REPAIRED) {
+ std::cout << "Polygons already reconstructed. Cannot match schemata!" << std::endl;
+ return false;
+ }
+
+ bool returnValue = io.matchSchemata(triangulation);
+
+ std::cout << "Schemata matched." << std::endl;
+
+ return returnValue;
+}
+
+bool PlanarPartition::reconstructPolygons(bool removeVertices) {
+
+ if (state < TAGGED) {
+ std::cout << "Triangulation not tagged. Cannot reconstruct!" << std::endl;
+ return false;
+ } if (state < REPAIRED) std::cout << "Warning: Triangulation not yet repaired. There could be errors..." << std::endl;
+ if (state > REPAIRED) {
+ std::cout << "Polygons already reconstructed!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Reconstructing polygons (geometry)..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ io.removeConstraints(triangulation);
+ if (removeVertices) io.removeVertices(triangulation);
+ bool returnValue = io.reconstructPolygons(triangulation, outputPolygons);
+
+ // Mark as reconstructed
+ if (returnValue) state = RECONSTRUCTED;
+
+ std::cout << "Polygons reconstructed (" << time(NULL)-thisTime << " s)." << std::endl;
+ return returnValue;
+}
+
+bool PlanarPartition::exportPolygons(const char *file, bool withProvenance) {
+
+ if (state < RECONSTRUCTED) {
+ std::cout << "Polygons have not been reconstructed. Nothing to export!" << std::endl;
+ return false;
+ }
+
+ std::cout << "Exporting polygons..." << std::endl;
+ time_t thisTime = time(NULL);
+
+ bool returnValue = io.exportPolygons(outputPolygons, file, withProvenance);
+
+ std::cout << "Polygons exported (" << time(NULL)-thisTime << " s)." << std::endl;
+ return returnValue;
+}
+
+bool PlanarPartition::exportTriangulation(const char *file, bool withNumberOfTags, bool withFields, bool withProvenance) {
+
+ // To accept external triangulations for debugging, comment...
+ if (state < TRIANGULATED || state > REPAIRED) {
+ std::cout << "No triangulation to export!" << std::endl;
+ return false;
+ }
+
+ io.exportTriangulation(triangulation, file, withNumberOfTags, withFields, withProvenance);
+
+ return true;
+}
+
+void PlanarPartition::printInfo() {
+ io.insertTriangulationInfo(std::cout, triangulation);
+}
\ No newline at end of file
diff --git a/PlanarPartition.h b/PlanarPartition.h
new file mode 100644
index 0000000..8334ea7
--- /dev/null
+++ b/PlanarPartition.h
@@ -0,0 +1,80 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef PLANARPARTITION_H
+#define PLANARPARTITION_H
+
+#include "IOWorker.h"
+
+class PlanarPartition {
+public:
+ // Constructors and destructors, initialisation
+ PlanarPartition();
+ ~PlanarPartition();
+
+ // Operations
+ bool addToTriangulation(const char *file, unsigned int schemaIndex = 0);
+
+ bool tagTriangulation();
+ bool makeAllHolesValid();
+ bool addAllowedHole(Point p);
+ bool addAllowedHoles(const char *file);
+ bool splitRegions(double ratio);
+
+ bool checkValidity();
+ bool repairTrianglesByNumberOfNeighbours(bool alsoUniverse);
+ bool repairTrianglesByAbsoluteMajority(bool alsoUniverse);
+ bool repairTrianglesByLongestBoundary(bool alsoUniverse);
+ bool repairRegionsByLongestBoundary(bool alsoUniverse);
+ bool repairRegionsByRandomNeighbour(bool alsoUniverse);
+ bool repairByPriorityList(const char *file);
+ bool repairEdgeMatching(const char *file);
+
+ bool matchSchemata();
+
+ bool reconstructPolygons(bool removeVertices = false);
+
+ bool exportPolygons(const char *file, bool withProvenance);
+ bool exportTriangulation(const char *file, bool withNumberOfTags, bool withFields, bool withProvenance);
+
+ void printInfo();
+
+private: // Comment to have access to the triangulation and other data structures from outside
+ // Internal states
+ enum State {
+ CREATED,
+ TRIANGULATED,
+ TAGGED,
+ REPAIRED,
+ RECONSTRUCTED
+ };
+ State state;
+
+ // I/O handler
+ IOWorker io;
+
+ // Generated stuff
+ Triangulation triangulation;
+ TaggingVector edgesToTag;
+ std::vector<std::pair<PolygonHandle *, Polygon> > outputPolygons;
+};
+
+#endif
\ No newline at end of file
diff --git a/PolygonHandle.cpp b/PolygonHandle.cpp
new file mode 100644
index 0000000..d00f714
--- /dev/null
+++ b/PolygonHandle.cpp
@@ -0,0 +1,255 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#include "PolygonHandle.h"
+
+Field::~Field() {
+
+}
+
+bool Field::operator<(Field &f) {
+ const Field *fp = &f;
+ Field *tp = this;
+ if (f.getType() != getType()) return fp < tp;
+ switch (getType()) {
+ case OFTString:
+ return (*(StringField *)fp) < (*(StringField *)tp);
+ break;
+ case OFTReal:
+ return (*(DoubleField *)fp) < (*(DoubleField *)tp);
+ break;
+ case OFTInteger:
+ return (*(IntField *)fp) < (*(IntField *)tp);
+ break;
+ default:
+ return false;
+ break;
+ }
+}
+
+bool Field::operator==(Field &f) {
+ const Field *fp = &f;
+ Field *tp = this;
+ if (f.getType() != getType()) return fp == tp;
+ switch (getType()) {
+ case OFTString:
+ return (*(StringField *)fp) == (*(StringField *)tp);
+ break;
+ case OFTReal:
+ return (*(DoubleField *)fp) == (*(DoubleField *)tp);
+ break;
+ case OFTInteger:
+ return (*(IntField *)fp) == (*(IntField *)tp);
+ break;
+ default:
+ return false;
+ break;
+ }
+}
+
+const char * Field::getValueAsString() {
+ std::cout << "Error: Getting value from abstract base class." << std::endl;
+ return "";
+}
+
+double Field::getValueAsDouble() {
+ std::cout << "Error: Getting value from abstract base class." << std::endl;
+ return 0.0;
+}
+
+int Field::getValueAsInt() {
+ std::cout << "Error: Getting value from abstract base class." << std::endl;
+ return 0;
+}
+
+void Field::setValueFromString(const char *v) {
+ std::cout << "Error: Setting value to abstract base class." << std::endl;
+}
+
+void Field::setValueFromDouble(double v) {
+ std::cout << "Error: Setting value to abstract base class." << std::endl;
+}
+
+void Field::setValueFromInt(int v) {
+ std::cout << "Error: Setting value to abstract base class." << std::endl;
+}
+
+StringField::StringField(const char *v) {
+ setValueFromString(v);
+}
+
+StringField::~StringField() {
+ free(contents);
+}
+
+bool StringField::operator<(const StringField &f) {
+ return strcmp(f.contents, contents) < 0;
+}
+
+bool StringField::operator==(const StringField &f) {
+ return strcmp(f.contents, contents) == 0;
+}
+
+const OGRFieldType StringField::getType() {
+ return OFTString;
+}
+
+const char * StringField::getValueAsString() {
+ return contents;
+}
+
+void StringField::setValueFromString(const char *v) {
+ contents = new char[(strlen(v)+1)];
+ strcpy(contents, v);
+}
+
+DoubleField::DoubleField(double v) {
+ setValueFromDouble(v);
+}
+
+bool DoubleField::operator<(const DoubleField &f) {
+ return f.contents < contents;
+}
+
+bool DoubleField::operator==(const DoubleField &f) {
+ return f.contents == contents;
+}
+
+const OGRFieldType DoubleField::getType() {
+ return OFTReal;
+}
+
+double DoubleField::getValueAsDouble() {
+ return contents;
+}
+
+void DoubleField::setValueFromDouble(double v) {
+ contents = v;
+}
+
+IntField::IntField(int v) {
+ setValueFromInt(v);
+}
+
+bool IntField::operator<(const IntField &f) {
+ return f.contents < contents;
+}
+
+bool IntField::operator==(const IntField &f) {
+ return f.contents == contents;
+}
+
+const OGRFieldType IntField::getType() {
+ return OFTInteger;
+}
+
+int IntField::getValueAsInt() {
+ return contents;
+}
+
+void IntField::setValueFromInt(int v) {
+ contents = v;
+}
+
+PolygonHandle::PolygonHandle(unsigned int si, char *of, unsigned int l, long fid) {
+ schemaIndex = si;
+ originalFile = of;
+ layer = l;
+}
+
+PolygonHandle::~PolygonHandle() {
+ for (unsigned int i = 0; i < fields.size(); ++i) {
+ delete fields[i];
+ }
+}
+
+void PolygonHandle::addField(Field *field) {
+ fields.push_back(field);
+}
+
+Field * PolygonHandle::getSchemaField() {
+ return fields[schemaIndex];
+}
+
+Field * PolygonHandle::getField(unsigned int i) {
+ return fields[i];
+}
+
+unsigned int PolygonHandle::getNumberOfFields() {
+ return fields.size();
+}
+
+char * PolygonHandle::getOriginalFile() {
+ return originalFile;
+}
+
+unsigned int PolygonHandle::getLayer() {
+ return layer;
+}
+
+const bool PolygonHandle::isMultiPolygonHandle() {
+ return false;
+}
+
+MultiPolygonHandle::MultiPolygonHandle(PolygonHandle *ph) {
+ if (ph->isMultiPolygonHandle()) {
+ for (std::list<PolygonHandle *>::iterator currentHandle = ((MultiPolygonHandle *)ph)->handles.begin();
+ currentHandle != ((MultiPolygonHandle *)ph)->handles.end();
+ ++currentHandle) {
+ handles.push_back(*currentHandle);
+ }
+ } else if (ph != NULL) {
+ handles.push_back(ph);
+ }
+}
+
+MultiPolygonHandle::~MultiPolygonHandle() {
+ for (unsigned int i = 0; i < fields.size(); ++i) {
+ delete fields[i];
+ }
+}
+
+const bool MultiPolygonHandle::isMultiPolygonHandle() {
+ return true;
+}
+
+bool MultiPolygonHandle::hasHandle(PolygonHandle *handle) {
+ if (find(handles.begin(), handles.end(), handle) != handles.end()) return true;
+ return false;
+}
+
+void MultiPolygonHandle::addHandle(PolygonHandle *handle) {
+ if (handle->isMultiPolygonHandle()) {
+ for (std::list<PolygonHandle *>::iterator currentHandle = static_cast<MultiPolygonHandle *>(handle)->handles.begin();
+ currentHandle != static_cast<MultiPolygonHandle *>(handle)->handles.end();
+ ++currentHandle) {
+ handles.push_back(*currentHandle);
+ }
+ } else handles.push_back(handle);
+}
+
+const std::list<PolygonHandle *> *MultiPolygonHandle::getHandles() {
+ return &handles;
+}
+
+unsigned int MultiPolygonHandle::numberOfHandles() {
+ return handles.size();
+}
\ No newline at end of file
diff --git a/PolygonHandle.h b/PolygonHandle.h
new file mode 100644
index 0000000..f79548d
--- /dev/null
+++ b/PolygonHandle.h
@@ -0,0 +1,144 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef POLYGONHANDLE_H
+#define POLYGONHANDLE_H
+
+#include "definitions/definitions.h"
+
+// Abstract class to store different types of attributes
+class Field {
+public:
+ // Destructor
+ virtual ~Field() = 0;
+
+ // Find the type of field
+ const virtual OGRFieldType getType() = 0;
+
+ // Comparison
+ bool operator<(Field &f);
+ bool operator==(Field &f);
+
+ // Getters
+ virtual const char * getValueAsString();
+ virtual double getValueAsDouble();
+ virtual int getValueAsInt();
+
+ // Setters
+ virtual void setValueFromString(const char *v);
+ virtual void setValueFromDouble(double v);
+ virtual void setValueFromInt(int v);
+};
+
+// Specific classes
+class StringField : public Field {
+public:
+ StringField(const char *v);
+ ~StringField();
+
+ bool operator<(const StringField &f);
+ bool operator==(const StringField &f);
+
+ const OGRFieldType getType();
+ const char * getValueAsString();
+ void setValueFromString(const char *v);
+private:
+ char * contents;
+};
+class DoubleField : public Field {
+public:
+ DoubleField(double v);
+
+ bool operator<(const DoubleField &f);
+ bool operator==(const DoubleField &f);
+
+ const OGRFieldType getType();
+ double getValueAsDouble();
+ void setValueFromDouble(double v);
+private:
+ double contents;
+};
+class IntField : public Field {
+public:
+ IntField(int v);
+
+ bool operator<(const IntField &f);
+ bool operator==(const IntField &f);
+
+ const OGRFieldType getType();
+ int getValueAsInt();
+ void setValueFromInt(int v);
+private:
+ int contents;
+};
+
+// Store a tag
+class PolygonHandle {
+public:
+ // Constructors and destructors
+ PolygonHandle(unsigned int si = 0, char *of = NULL, unsigned int l = 0, long fid = 0);
+ virtual ~PolygonHandle();
+
+ // References
+ char * getOriginalFile();
+ unsigned int getLayer();
+
+ // Field information
+ void addField(Field *field);
+ Field * getSchemaField();
+ Field * getField(unsigned int i);
+ unsigned int getNumberOfFields();
+
+ // Checking whether it's a MultiPolygonHandle
+ virtual const bool isMultiPolygonHandle();
+protected:
+ char *originalFile;
+ unsigned int layer;
+ //long featureID;
+
+ // The field to use as schema
+ // (could be changed to a set or regex to represent complex criteria)
+ unsigned int schemaIndex;
+
+ // Fields it contains
+ std::vector<Field *> fields;
+};
+
+// Trick to save memory when multiple tags are not present
+class MultiPolygonHandle : public PolygonHandle {
+public:
+ // Constructor. No need to start with less than two
+ MultiPolygonHandle(PolygonHandle *ph);
+ ~MultiPolygonHandle();
+
+ // Checking whether it's a MultiPolygonHandle
+ virtual const bool isMultiPolygonHandle();
+
+ // Access functions to the individual PolygonHandles
+ bool hasHandle(PolygonHandle *handle);
+ void addHandle(PolygonHandle *handle);
+ const std::list<PolygonHandle *> *getHandles();
+ unsigned int numberOfHandles();
+private:
+ std::list<PolygonHandle *> handles;
+};
+
+#endif
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..32205b3
--- /dev/null
+++ b/README.md
@@ -0,0 +1,52 @@
+## What is pprepair?
+
+pprepair (*p*lanar *p*artition repair) takes a set of polygons and ensures that they form a valid planar partition, made of valid polygons and having no gaps or overlaps. It can be used as a validator, telling of problems in individual polygons or in the planar partition, and also as an automatic repair tool, outputting a set of polygons that do form a valid planar partition. If you are only interested in repairing individual polygons, have a look at [prepair](https://github.com/tudelft- [...]
+
+## What is a planar partition and why is it important to have valid planar partitions?
+
+Planar partitions are subdivisions of the plane into polygons, and are frequently used in GIS to model various concepts like land use, geology, administrative subdivisions, natural features and cadastral parcels, among many others.
+
+However, the polygons in a planar partition are often created separately, and thus cannot be expected to fit with each other exactly. Other times, these polygons are stored and modified separately, causing different errors and inconsistencies to be introduced. These come in the form of invalid polygons, gaps, overlaps and disconnected polygons.
+
+When software that expects a planar partition received one that is not so, it can give erroneous results (in the best case), or fail to give a result at all, often without a clear explanation to the user.
+
+## How does pprepair work?
+
+In short, pprepair creates a constrained triangulation of the polygons, tags each triangle with the polygon that it belongs to, modifies the triangulation to ensure that only one tag is present in each, and reconstructs the polygons from the triangulation.
+
+Many more details are available in Ken Arroyo Ohori's MSc thesis [here](http://www.gdmc.nl/ken/files/10_msc_thesis.pdf).
+
+If you use pprepair for your research, please cite this publication:
+
+> Arroyo Ohori, Ken, Ledoux, Hugo and Meijers, Martijn (2012). Validation and automatic repair of planar partitions using a constrained triangulation. *Photogrammetrie, Fernerkundung, Geoinformation (PFG)*. 5:613–630. [ [PDF] ](http://www.gdmc.nl/ken/files/12_pfg.pdf) [ [DOI] ](http://dx.doi.org/10.1127/1432-8364/2012/0143)
+
+## How do I use pprepair?
+
+pprepair is a command-line program, which we provide as source code. It is very easy to compile it on Linux and Mac. We plan on offering binaries (including for Windows) in the future.
+
+To compile pprepair, you first need to install the free libraries [CGAL](http://www.cgal.org) and [GDAL](http://www.gdal.org). [CMake](http://www.cmake.org) is highly recommended. Under Mac, we recommend using [Homebrew](http://brew.sh/) to install CGAL (and all its dependencies) and CMake, and GDAL is easily installed with the framework installed of [KyngChaos](http://www.kyngchaos.com/software/frameworks#gdal_complete).
+
+To install it, run:
+
+ $ cmake .
+ $ make
+ $ ./pprepair -i inputfile -o outputfile -fix
+
+You can get all the options simply by running pprepair with no arguments
+ $ ./pprepair
+
+## Can I use pprepair in my organisation? What is the license of pprepair?
+
+Following in CGAL's footsteps, pprepair is available under a dual license scheme, GPLv3 and commercial. If you choose to use pprepair under the free-of-charge GPLv3 license, you have to comply with its terms. If these are not suitable for you, you have to buy a commercial license.
+
+The [GPLv3](http://www.gnu.org/copyleft/gpl.html) allows you to use, copy and modify the software freely. However, if you incorporate pprepair in your software, you must distribute the source code of your software, as well as any modifications made to pprepair, under the GPLv3 as well.
+
+If you are interested in getting a commercial license for pprepair, please contact [Ken Arroyo Ohori](mailto:g.a.k.arroyoohori at tudelft.nl).
+
+## Help! pprepair is crashing or giving weird results
+
+This can be due to several reasons. 99% of the time it can be solved by:
+ - If your data set has very large polygons, try passing the -bd flag
+ - If your data set has points that are **very** close together, try uncommenting line 26 in definitions/CGALDefinitions.h (#define EXACT_CONSTRUCTIONS)
+
+If your problem persists, please report it [here](https://github.com/tudelft-gist/pprepair/issues?state=open).
diff --git a/definitions/CGALDefinitions.h b/definitions/CGALDefinitions.h
new file mode 100644
index 0000000..7158cb2
--- /dev/null
+++ b/definitions/CGALDefinitions.h
@@ -0,0 +1,165 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef CGALDEFINITIONS_H
+#define CGALDEFINITIONS_H
+
+// Compile-time options
+#define EXACT_CONSTRUCTIONS // Exact arithmetic: memory and processing time increase
+//#define TRIANGULATION_HIERARCHY // Faster point location algorithm: more memory
+
+// CGAL kernel
+#ifdef EXACT_CONSTRUCTIONS
+#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
+#else
+#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
+#endif
+
+// CGAL values
+#include <CGAL/enum.h>
+
+// CGAL classes
+#include <CGAL/Polygon_2.h>
+#include <CGAL/Triangulation_face_base_with_info_2.h>
+#include <CGAL/Constrained_Delaunay_triangulation_2.h>
+#include <CGAL/Triangulation_hierarchy_2.h>
+#include <CGAL/Constrained_triangulation_plus_2.h>
+
+// VertexInfo for SAFE
+#ifdef USE_VERTEX_INFO
+#include <VertexInfo.h>
+typedef std::vector<VertexInfo> RingInfo;
+#endif
+
+// Kernel
+#ifdef EXACT_CONSTRUCTIONS
+typedef CGAL::Exact_predicates_exact_constructions_kernel K;
+#else
+typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
+#endif
+
+// Low level stuff
+#ifdef TRIANGULATION_HIERARCHY
+#ifdef USE_VERTEX_INFO
+typedef CGAL::Triangulation_vertex_base_with_info_2<VertexInfo,K> TVB;
+#else
+typedef CGAL::Triangulation_vertex_base_2<K> TVB;
+#endif
+typedef CGAL::Triangulation_hierarchy_vertex_base_2<TVB> VB;
+#else
+typedef CGAL::Triangulation_vertex_base_2<K> VB;
+#endif
+typedef CGAL::Constrained_triangulation_face_base_2<K> FB;
+typedef CGAL::Triangulation_face_base_with_info_2<FaceInfo, K, FB> FBWI;
+typedef CGAL::Triangulation_data_structure_2<VB, FBWI> TDS;
+typedef CGAL::Exact_predicates_tag PT;
+typedef CGAL::Exact_intersections_tag IT;
+#ifdef EXACT_CONSTRUCTIONS
+typedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, IT> CDT;
+#else
+typedef CGAL::Constrained_Delaunay_triangulation_2<K, TDS, PT> CDT;
+#endif
+#ifdef TRIANGULATION_HIERARCHY
+typedef CGAL::Triangulation_hierarchy_2<CDT> CDTH;
+typedef CGAL::Constrained_triangulation_plus_2<CDTH> Triangulation;
+#else
+typedef CGAL::Constrained_triangulation_plus_2<CDT> Triangulation;
+#endif
+
+// Other types, for easy reading
+typedef Triangulation::Point Point;
+typedef Triangulation::Segment Segment;
+typedef CGAL::Polygon_2<K> Ring;
+
+// Non CGAL types
+typedef std::vector<std::pair<std::vector<Triangulation::Vertex_handle>, std::vector<std::vector<Triangulation::Vertex_handle> > > > TaggingVector;
+
+// Polygon type to avoid CGAL's Polygon_with_holes_2
+class Polygon {
+public:
+ typedef std::vector<Ring>::const_iterator Hole_const_iterator;
+#ifdef USE_VERTEX_INFO
+ typedef std::vector<RingInfo>::const_iterator HoleInfo_const_iterator;
+#endif
+
+ Polygon(const Ring &outer, const std::vector<Ring>::iterator innerBegin, const std::vector<Ring>::iterator innerEnd) {
+ outerRing = outer;
+ innerRings = std::vector<Ring>(innerBegin, innerEnd);
+#ifdef USE_VERTEX_INFO
+ for (size_t i = 0; i < oRing.size(); ++i) outerRingInfo.push_back(VertexInfo());
+ for (size_t i=0; i < innerRings.size(); i++) {
+ innerRingsInfo.push_back(RingInfo());
+ for (size_t j=0; j < innerRings[i].size(); j++) innerRingsInfo.back().push_back(VertexInfo());
+ }
+#endif
+ }
+
+#ifdef USE_VERTEX_INFO
+ Polygon(const Ring oRing, const std::vector<Ring> iRings, const RingInfo oRingInfo, const std::vector<RingInfo> iRingsInfo) :
+ outerRing(oRing), innerRings(iRings), outerRingInfo(oRingInfo), innerRingsInfo(iRingsInfo) {
+ }
+
+
+ Polygon(const Ring oRing, const std::vector<Ring> iRings) :
+ outerRing(oRing), innerRings(iRings) {
+ for (size_t i=0; i < oRing.size(); i++) outerRingInfo.push_back(VertexInfo());
+ for (size_t i=0; i < innerRings.size(); i++) {
+ innerRingsInfo.push_back(RingInfo());
+ for (size_t j=0; j < innerRings[i].size(); j++) innerRingsInfo.back().push_back(VertexInfo());
+ }
+ }
+#endif
+
+ const Ring &outer_boundary() const {
+ return outerRing;
+ }
+
+ Hole_const_iterator holes_begin() const {
+ return innerRings.begin();
+ }
+
+ Hole_const_iterator holes_end() const {
+ return innerRings.end();
+ }
+
+#ifdef USE_VERTEX_INFO
+ const RingInfo& outer_boundary_info() const {
+ return outerRingInfo;
+ }
+
+ std::vector<RingInfo>::const_iterator holes_info_begin() const {
+ return innerRingsInfo.begin();
+ }
+
+ std::vector<RingInfo>::const_iterator holes_info_end() const {
+ return innerRingsInfo.end();
+ }
+#endif
+private:
+ Ring outerRing;
+ std::vector<Ring> innerRings;
+#ifdef USE_VERTEX_INFO
+ RingInfo outerRingInfo;
+ std::vector<RingInfo> innerRingsInfo;
+#endif
+};
+
+#endif
\ No newline at end of file
diff --git a/definitions/definitions.h b/definitions/definitions.h
new file mode 100644
index 0000000..b424361
--- /dev/null
+++ b/definitions/definitions.h
@@ -0,0 +1,38 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#ifndef DEFINITIONS_H
+#define DEFINITIONS_H
+
+// OGR, to store OGR types directly
+#include <gdal/ogrsf_frmts.h>
+
+// Standard libraries
+#include <iostream>
+#include <fstream>
+#include <time.h>
+
+// STL containers
+#include <vector>
+#include <list>
+#include <algorithm>
+
+#endif
\ No newline at end of file
diff --git a/icon.png b/icon.png
new file mode 100644
index 0000000..cabde5c
Binary files /dev/null and b/icon.png differ
diff --git a/pprepair.cpp b/pprepair.cpp
new file mode 100644
index 0000000..5ad6119
--- /dev/null
+++ b/pprepair.cpp
@@ -0,0 +1,399 @@
+/*
+ Copyright (c) 2009-2013,
+ Ken Arroyo Ohori g.a.k.arroyoohori at tudelft.nl
+ Hugo Ledoux h.ledoux at tudelft.nl
+ Martijn Meijers b.m.meijers at tudelft.nl
+ All rights reserved.
+
+ This file is part of pprepair: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ Licensees holding a valid commercial license may use this file in
+ accordance with the commercial license agreement provided with
+ the software.
+
+ This file is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#include "PlanarPartition.h"
+
+enum RepairMethod {
+ VALIDATE_ONLY = -1,
+ NUMBER_OF_NEIGHBOURS = 0,
+ ABSOLUTE_MAJORITY = 1,
+ LONGEST_BOUNDARY = 2,
+ REGIONS_BY_LONGEST_BOUNDARY = 3,
+ REGIONS_BY_RANDOM_NEIGHBOUR = 4,
+ PRIORITY_LIST = 5,
+ PRIORITY_LIST_EDGEMATCHING = 6
+};
+
+int main(int argc, const char *argv[]) {
+
+ time_t startTime = time(NULL);
+ PlanarPartition pp;
+ bool processInOrder = false;
+
+ std::list<std::pair<std::string, int> > inputFiles;
+ std::string outputFile, outputFileWithProvenance, taggedTriangulationOutputFile, triangulationOutputFile, triangulationOutputFileWithProvenance;
+ bool makeHolesValid = false, splitRegions = false, alsoUniverse = false, matchSchemata = false, bigData = false;
+ double splitRegionsRatio;
+ std::list<std::pair<RepairMethod, std::string> > repairMethods;
+
+ // Process help argument
+ if (argc == 1 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
+ std::cout << "=== pprepair Help ===" << std::endl;
+ std::cout << " Simple: pprepair [options]" << std::endl;
+ std::cout << " Advanced: pprepair -p [processing steps in order]" << std::endl;
+ std::cout << " Example: ./pprepair -i \"myInput.shp\" -o \"myOutput.shp\" -fix" << std::endl;
+ std::cout << "== Basic options ==" << std::endl;
+ std::cout << " -i filename [schemaindex] Add this file to the triangulation using this schema index" << std::endl;
+ std::cout << " -o filename Output the reconstructed polygons in this file" << std::endl;
+ std::cout << " -fix Automagically repair (same as -rrlb -rrrn)" << std::endl;
+ std::cout << " -d Dissolve the boundaries between regions with the same tag according to the schema index" << std::endl;
+ std::cout << "== Possible steps (in usual processing order) ==" << std::endl;
+ std::cout << " -i filename [schemaindex] Add this file to the triangulation using this schema index" << std::endl;
+ std::cout << " -t Tag the triangulation" << std::endl;
+ std::cout << " -otnt filename Output the tagged triangulation with the number of tags to this file" << std::endl;
+ std::cout << " -vh Consider holes as valid" << std::endl;
+ std::cout << " -sr ratio Split invalid regions at triangles with a higher aspect ratio than this" << std::endl;
+ std::cout << " -v Validate" << std::endl;
+ std::cout << " -au Allow removing invalid regions (where convenient)" << std::endl;
+ std::cout << " -rtnn Repair triangles by assigning them to the neighbour present on most sides" << std::endl;
+ std::cout << " -rtam Repair triangles by assigning them to a neighbour present on at least 2 sides" << std::endl;
+ std::cout << " -rtlb Repair triangles by assigning them to the neighbour present along the longest part of their boundary" << std::endl;
+ std::cout << " -rrlb Repair regions by assigning them to the neighbour present along the longest part of their boundary" << std::endl;
+ std::cout << " -rrrn Repair regions by assigning them to a random neighbour" << std::endl;
+ std::cout << " -rpl filename Repair by assigning according to the priority list in this file" << std::endl;
+ std::cout << " -rem filename Repair for edge matching according to the priority list in this file" << std::endl;
+ std::cout << " -ot filename Output the triangulation to this file" << std::endl;
+ std::cout << " -otwp filename Output the triangulation to this file, including the input file where each triangle came from" << std::endl;
+ std::cout << " -bd Removes unnecessary vertices before reconstruction to support larger data sets (try if you get a segmentation fault)" << std::endl;
+ std::cout << " -rp Reconstruct polygons" << std::endl;
+ std::cout << " -o filename Output the reconstructed polygons in this file" << std::endl;
+ std::cout << " -owp filename Output the reconstructed polygons in this file, including the input file where they came from" << std::endl;
+ std::cout << " -pi Print triangulation information" << std::endl;
+ return 0;
+ }
+
+ for (int argNum = 1; argNum < argc; ++argNum) {
+
+ // IMPORTANT: When adding new options, check that their order doesn't cause parsing conflicts!!!
+
+ // Process in order
+ if (strcmp(argv[argNum], "-p") == 0 && strcmp(argv[argNum], "-pi") != 0) {
+ processInOrder = true;
+ }
+
+ // Input
+ else if (strcmp(argv[argNum], "-i") == 0) {
+ if (argNum + 2 <= argc - 1 && argv[argNum+2][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.addToTriangulation(argv[argNum], atoi(argv[argNum+1]));
+ else inputFiles.push_back(std::pair<std::string, int>(argv[argNum], atoi(argv[argNum+1])));
+ ++argNum;
+ } else if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.addToTriangulation(argv[argNum]);
+ else inputFiles.push_back(std::pair<std::string, int>(argv[argNum], 0));
+ } else {
+ std::cerr << "Error: Missing filename argument for -i";
+ return 1;
+ }
+ }
+
+ // Tag triangulation
+ else if (strcmp(argv[argNum], "-fix") == 0) {
+ if (!processInOrder) {
+ repairMethods.push_back(std::pair<RepairMethod, std::string>(REGIONS_BY_LONGEST_BOUNDARY, std::string()));
+ repairMethods.push_back(std::pair<RepairMethod, std::string>(REGIONS_BY_RANDOM_NEIGHBOUR, std::string()));
+ }
+ }
+
+ // Tag triangulation
+ else if (strcmp(argv[argNum], "-t") == 0) {
+ if (processInOrder) pp.tagTriangulation();
+ }
+
+ // Output tagged triangulation
+ else if (strcmp(argv[argNum], "-otnt") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.exportTriangulation(argv[argNum], true, false, false);
+ else taggedTriangulationOutputFile = argv[argNum];
+ } else {
+ std::cerr << "Error: Missing filename argument for -otnt";
+ return 1;
+ }
+ }
+
+ // Make all holes valid
+ else if (strcmp(argv[argNum], "-vh") == 0) {
+ if (processInOrder) pp.makeAllHolesValid();
+ else makeHolesValid = true;
+ }
+
+ // Split regions
+ else if (strcmp(argv[argNum], "-sr") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.splitRegions(atof(argv[argNum]));
+ else {
+ splitRegions = true;
+ splitRegionsRatio = atof(argv[argNum]);
+ }
+ } else {
+ std::cerr << "Error: Missing ratio argument for -sr";
+ return 1;
+ }
+ }
+
+ // Validate
+ else if (strcmp(argv[argNum], "-v") == 0) {
+ if (processInOrder) pp.checkValidity();
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(VALIDATE_ONLY, std::string()));
+ }
+
+ // Validate
+ else if (strcmp(argv[argNum], "-au") == 0) {
+ alsoUniverse = !alsoUniverse;
+ }
+
+ // Repair triangle by number of neighbours
+ else if (strcmp(argv[argNum], "-rtnn") == 0) {
+ if (processInOrder) pp.repairTrianglesByNumberOfNeighbours(alsoUniverse);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(NUMBER_OF_NEIGHBOURS, std::string()));
+ }
+
+ // Repair triangles by absolute majority
+ else if (strcmp(argv[argNum], "-rtam") == 0) {
+ if (processInOrder) pp.repairTrianglesByAbsoluteMajority(alsoUniverse);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(ABSOLUTE_MAJORITY, std::string()));
+ }
+
+ // Repair triangles by longest boundary
+ else if (strcmp(argv[argNum], "-rtlb") == 0) {
+ if (processInOrder) pp.repairTrianglesByLongestBoundary(alsoUniverse);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(LONGEST_BOUNDARY, std::string()));
+ }
+
+ // Repair regions by longest boundary
+ else if (strcmp(argv[argNum], "-rrlb") == 0) {
+ if (processInOrder) pp.repairRegionsByLongestBoundary(alsoUniverse);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(REGIONS_BY_LONGEST_BOUNDARY, std::string()));
+ }
+
+ // Repair regions by random neighbour
+ else if (strcmp(argv[argNum], "-rrrn") == 0) {
+ if (processInOrder) pp.repairRegionsByRandomNeighbour(alsoUniverse);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(REGIONS_BY_RANDOM_NEIGHBOUR, std::string()));
+ }
+
+ // Repair by priority list
+ else if (strcmp(argv[argNum], "-rpl") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.repairByPriorityList(argv[argNum]);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(PRIORITY_LIST, argv[argNum]));
+ } else {
+ std::cerr << "Error: Missing priority list argument for -rpl";
+ return 1;
+ }
+ }
+
+ // Repair by priority list (edge matching)
+ else if (strcmp(argv[argNum], "-rem") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.repairEdgeMatching(argv[argNum]);
+ else repairMethods.push_back(std::pair<RepairMethod, std::string>(PRIORITY_LIST_EDGEMATCHING, argv[argNum]));
+ } else {
+ std::cerr << "Error: Missing priority list argument for -rem";
+ return 1;
+ }
+ }
+
+ // Output triangulation with provenance
+ else if (strcmp(argv[argNum], "-otwp") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.exportTriangulation(argv[argNum], false, true, true);
+ else triangulationOutputFileWithProvenance = argv[argNum];
+ } else {
+ std::cerr << "Error: Missing filename argument for -otwp";
+ return 1;
+ }
+ }
+
+ // Output triangulation
+ else if (strcmp(argv[argNum], "-ot") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.exportTriangulation(argv[argNum], false, true, false);
+ else triangulationOutputFile = argv[argNum];
+ } else {
+ std::cerr << "Error: Missing filename argument for -ot";
+ return 1;
+ }
+ }
+
+ // Match schemata
+ else if (strcmp(argv[argNum], "-d") == 0) {
+ if (processInOrder) pp.matchSchemata();
+ else matchSchemata = true;
+ }
+
+ // Match schemata
+ else if (strcmp(argv[argNum], "-bd") == 0) {
+ bigData = true;
+ }
+
+ // Reconstruct polygons
+ else if (strcmp(argv[argNum], "-rp") == 0) {
+ if (processInOrder) pp.reconstructPolygons(bigData);
+ }
+
+ // Output with provenance
+ else if (strcmp(argv[argNum], "-owp") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.exportPolygons(argv[argNum], true);
+ else outputFileWithProvenance = argv[argNum];
+ } else {
+ std::cerr << "Error: Missing filename argument for -o";
+ return 1;
+ }
+ }
+
+ // Output
+ else if (strcmp(argv[argNum], "-o") == 0) {
+ if (argNum + 1 <= argc - 1 && argv[argNum+1][0] != '-') {
+ ++argNum;
+ if (processInOrder) pp.exportPolygons(argv[argNum], false);
+ else outputFile = argv[argNum];
+ } else {
+ std::cerr << "Error: Missing filename argument for -o";
+ return 1;
+ }
+ }
+
+ // Print triangulation information
+ else if (strcmp(argv[argNum], "-pi") == 0) {
+ if (processInOrder) pp.printInfo();
+ }
+
+ // Unrecognised option
+ else {
+ std::cerr << "Error: unrecognised option " << argv[argNum] << std::endl;
+ }
+ }
+
+ // For the simple mode
+ if (!processInOrder) {
+
+ // Process input
+ if (inputFiles.size() == 0) {
+ std::cerr << "Error: No input files given.";
+ return 1;
+ } for (std::list<std::pair<std::string, int> >::iterator currentFile = inputFiles.begin(); currentFile != inputFiles.end(); ++currentFile)
+ pp.addToTriangulation(currentFile->first.c_str(), currentFile->second);
+
+ // Tag
+ pp.tagTriangulation();
+
+ // Print info
+ std::cout << "Input triangulation:" << std::endl;
+ pp.printInfo();
+
+ // Output triangulation with number of tags
+ if (taggedTriangulationOutputFile.size() > 0) pp.exportTriangulation(taggedTriangulationOutputFile.c_str(), true, false, false);
+
+ // Consider holes as valid
+ if (makeHolesValid) pp.makeAllHolesValid();
+
+ // Split regions
+ if (splitRegions) pp.splitRegions(splitRegionsRatio);
+
+ // Repair
+ bool outputResults = false;
+ for (std::list<std::pair<RepairMethod, std::string> >::iterator currentFile = repairMethods.begin(); currentFile != repairMethods.end(); ++currentFile) {
+ switch (currentFile->first) {
+ case VALIDATE_ONLY:
+ pp.checkValidity();
+ break;
+
+ case NUMBER_OF_NEIGHBOURS:
+ pp.repairTrianglesByNumberOfNeighbours(alsoUniverse);
+ outputResults = true;
+ break;
+
+ case ABSOLUTE_MAJORITY:
+ pp.repairTrianglesByAbsoluteMajority(alsoUniverse);
+ outputResults = true;
+ break;
+
+ case LONGEST_BOUNDARY:
+ pp.repairTrianglesByLongestBoundary(alsoUniverse);
+ outputResults = true;
+ break;
+
+ case REGIONS_BY_LONGEST_BOUNDARY:
+ pp.repairRegionsByLongestBoundary(alsoUniverse);
+ outputResults = true;
+ break;
+
+ case REGIONS_BY_RANDOM_NEIGHBOUR:
+ pp.repairRegionsByRandomNeighbour(alsoUniverse);
+ outputResults = true;
+ break;
+
+ case PRIORITY_LIST:
+ pp.repairByPriorityList(currentFile->second.c_str());
+ outputResults = true;
+ break;
+
+ case PRIORITY_LIST_EDGEMATCHING:
+ pp.repairEdgeMatching(currentFile->second.c_str());
+ outputResults = true;
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ // Print info
+ if (outputResults) {
+ std::cout << "Repaired triangulation:" << std::endl;
+ pp.printInfo();
+ }
+
+ // Output the triangulation
+ if (triangulationOutputFile.size() > 0) pp.exportTriangulation(triangulationOutputFile.c_str(), false, true, false);
+
+ // Output the triangulation with provenance
+ if (triangulationOutputFileWithProvenance.size() > 0) pp.exportTriangulation(triangulationOutputFileWithProvenance.c_str(), false, true, true);
+
+ // Match schemata
+ if (matchSchemata) pp.matchSchemata();
+
+ // Reconstruct polygons
+ if (outputFile.size() > 0 || outputFileWithProvenance.size() > 0) pp.reconstructPolygons(bigData);
+
+ // Output
+ if (outputFile.size() > 0) pp.exportPolygons(outputFile.c_str(), false);
+
+ // Output with provenance
+ if (outputFileWithProvenance.size() > 0) pp.exportPolygons(outputFileWithProvenance.c_str(), true);
+ }
+
+ time_t totalTime = time(NULL)-startTime;
+ std::cout << "Done! Process finished in " << totalTime/60 << " minutes " << totalTime%60 << " seconds." << std::endl;
+
+ return 0;
+}
+
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/pprepair.git
More information about the Pkg-grass-devel
mailing list