src/triangulate.cpp

changeset 321
180072db4a83
parent 320
af6633412a6c
child 369
57de8fab2237
--- a/src/triangulate.cpp	Sun Jul 03 14:35:06 2022 +0300
+++ b/src/triangulate.cpp	Sun Jul 03 15:59:22 2022 +0300
@@ -134,28 +134,29 @@
 	std::vector<glm::vec3>::const_iterator end)
 {
 	std::vector<PlainPolygonElement> result;
-	const glm::vec3 xvec = *begin - *(begin + 1);
-	const glm::vec3 yvec = *(begin + 2) - *(begin + 1);
-	const glm::vec3 zvec = glm::cross(xvec, yvec);
-	const glm::mat3 inverseMatrix = glm::inverse(glm::mat3{xvec, yvec, zvec});
-	std::vector<std::vector<glm::vec3>> polygons{1};
-	std::vector<glm::vec3>& polygon2d = polygons.back();
-	polygon2d.reserve(static_cast<std::size_t>(end - begin));
-	for (std::vector<glm::vec3>::const_iterator it = begin; it != end; ++it) {
-		polygon2d.push_back(inverseMatrix * glm::vec4{*it, 1});
-	}
-	const std::vector<triangulate::index_t> indices = mapbox::earcut<triangulate::index_t>(polygons);
-	triangulate::MergedTriangles mergedTriangles = triangulate::mergeTriangles(indices, begin);
-	for (Quadrilateral& quad : mergedTriangles.quadrilaterals) {
-		result.push_back(quad);
-	}
-	for (std::size_t i = 0; i < indices.size(); i += 3) {
-		if (not mergedTriangles.cutTriangles.contains({i})) {
-			Triangle tri = triangle(
+	// Transform the polygon into XY plane
+	opt<glm::mat3> normal = calculateNormal(begin, end);
+	if (normal.has_value()) {
+		const glm::mat3 normalInverse = glm::inverse(*normal);
+		std::vector<std::vector<glm::vec3>> polygons{1};
+		std::vector<glm::vec3>& polygon2d = polygons.back();
+		polygon2d.reserve(static_cast<std::size_t>(end - begin));
+		for (std::vector<glm::vec3>::const_iterator it = begin; it != end; ++it) {
+			polygon2d.push_back(normalInverse * glm::vec4{*it, 1});
+		}
+		const std::vector<triangulate::index_t> indices = mapbox::earcut<triangulate::index_t>(polygons);
+		triangulate::MergedTriangles mergedTriangles = triangulate::mergeTriangles(indices, begin);
+		for (Quadrilateral& quad : mergedTriangles.quadrilaterals) {
+			result.push_back(quad);
+		}
+		for (std::size_t i = 0; i < indices.size(); i += 3) {
+			if (not mergedTriangles.cutTriangles.contains({i})) {
+				Triangle tri = triangle(
 				*(begin + indices[i]),
 				*(begin + indices[i + 1]),
 				*(begin + indices[i + 2]));
-			result.push_back(tri);
+				result.push_back(tri);
+			}
 		}
 	}
 	return result;

mercurial