Debian Codegraph @

thirdparty/manifold/src/quickhull.h

raw symbols SCIP
1 // Copyright 2024 The Manifold Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 // Derived from the public domain work of Antti Kuukka at
16 // https://github.com/akuukka/quickhull
17
18 /*
19 * INPUT: a list of points in 3D space (for example, vertices of a 3D mesh)
20 *
21 * OUTPUT: a ConvexHull object which provides vertex and index buffers of the
22 *generated convex hull as a triangle mesh.
23 *
24 *
25 *
26 * The implementation is thread-safe if each thread is using its own QuickHull
27 *object.
28 *
29 *
30 * SUMMARY OF THE ALGORITHM:
31 * - Create initial simplex (tetrahedron) using extreme points. We have
32 *four faces now and they form a convex mesh M.
33 * - For each point, assign them to the first face for which they are on
34 *the positive side of (so each point is assigned to at most one face). Points
35 *inside the initial tetrahedron are left behind now and no longer affect the
36 *calculations.
37 * - Add all faces that have points assigned to them to Face Stack.
38 * - Iterate until Face Stack is empty:
39 * - Pop topmost face F from the stack
40 * - From the points assigned to F, pick the point P that is
41 *farthest away from the plane defined by F.
42 * - Find all faces of M that have P on their positive side. Let us
43 *call these the "visible faces".
44 * - Because of the way M is constructed, these faces are
45 *connected. Solve their horizon edge loop.
46 * - "Extrude to P": Create new faces by connecting
47 *P with the points belonging to the horizon edge. Add the new faces to M and
48 *remove the visible faces from M.
49 * - Each point that was assigned to visible faces is now assigned
50 *to at most one of the newly created faces.
51 * - Those new faces that have points assigned to them are added to
52 *the top of Face Stack.
53 * - M is now the convex hull.
54 *
55 * */
56 #pragma once
57 #include <array>
58 #include <deque>
59 #include <vector>
60
61 #include "shared.h"
62 #include "vec.h"
63
64 namespace manifold {
65
66 class Pool {
67 std::vector<std::unique_ptr<Vec<size_t>>> data;
68
69 public:
70 void clear() { data.clear(); }
71
72 void reclaim(std::unique_ptr<Vec<size_t>>& ptr) {
73 data.push_back(std::move(ptr));
74 }
75
76 std::unique_ptr<Vec<size_t>> get() {
77 if (data.size() == 0) {
78 return std::make_unique<Vec<size_t>>();
79 }
80 auto it = data.end() - 1;
81 std::unique_ptr<Vec<size_t>> r = std::move(*it);
82 data.erase(it);
83 return r;
84 }
85 };
86
87 class Plane {
88 public:
89 vec3 N;
90
91 // Signed distance (if normal is of length 1) to the plane from origin
92 double D;
93
94 // Normal length squared
95 double sqrNLength;
96
97 bool isPointOnPositiveSide(const vec3& Q) const {
98 double d = la::dot(N, Q) + D;
99 if (d >= 0) return true;
100 return false;
101 }
102
103 Plane() = default;
104
105 // Construct a plane using normal N and any point P on the plane
106 Plane(const vec3& N, const vec3& P)
107 : N(N), D(la::dot(-N, P)), sqrNLength(la::dot(N, N)) {}
108 };
109
110 struct Ray {
111 const vec3 S;
112 const vec3 V;
113 const double VInvLengthSquared;
114
115 Ray(const vec3& S, const vec3& V)
116 : S(S), V(V), VInvLengthSquared(1 / (la::dot(V, V))) {}
117 };
118
119 class MeshBuilder {
120 public:
121 struct Face {
122 int he;
123 Plane P{};
124 double mostDistantPointDist = 0.0;
125 size_t mostDistantPoint = 0;
126 size_t visibilityCheckedOnIteration = 0;
127 std::uint8_t isVisibleFaceOnCurrentIteration : 1;
128 std::uint8_t inFaceStack : 1;
129 // Bit for each half edge assigned to this face, each being 0 or 1 depending
130 // on whether the edge belongs to horizon edge
131 std::uint8_t horizonEdgesOnCurrentIteration : 3;
132 std::unique_ptr<Vec<size_t>> pointsOnPositiveSide;
133
134 Face(size_t he)
135 : he(he),
136 isVisibleFaceOnCurrentIteration(0),
137 inFaceStack(0),
138 horizonEdgesOnCurrentIteration(0) {}
139
140 Face()
141 : he(-1),
142 isVisibleFaceOnCurrentIteration(0),
143 inFaceStack(0),
144 horizonEdgesOnCurrentIteration(0) {}
145
146 void disable() { he = -1; }
147
148 bool isDisabled() const { return he == -1; }
149 };
150
151 // Mesh data
152 std::vector<Face> faces;
153 Vec<Halfedge> halfedges;
154 Vec<int> halfedgeToFace;
155 Vec<int> halfedgeNext;
156
157 // When the mesh is modified and faces and half edges are removed from it, we
158 // do not actually remove them from the container vectors. Insted, they are
159 // marked as disabled which means that the indices can be reused when we need
160 // to add new faces and half edges to the mesh. We store the free indices in
161 // the following vectors.
162 Vec<size_t> disabledFaces, disabledHalfedges;
163
164 size_t addFace();
165
166 size_t addHalfedge();
167
168 // Mark a face as disabled and return a pointer to the points that were on the
169 // positive of it.
170 std::unique_ptr<Vec<size_t>> disableFace(size_t faceIndex) {
171 auto& f = faces[faceIndex];
172 f.disable();
173 disabledFaces.push_back(faceIndex);
174 return std::move(f.pointsOnPositiveSide);
175 }
176
177 void disableHalfedge(size_t heIndex) {
178 auto& he = halfedges[heIndex];
179 he.pairedHalfedge = -1;
180 disabledHalfedges.push_back(heIndex);
181 }
182
183 MeshBuilder() = default;
184
185 // Create a mesh with initial tetrahedron ABCD. Dot product of AB with the
186 // normal of triangle ABC should be negative.
187 void setup(int a, int b, int c, int d);
188
189 std::array<int, 3> getVertexIndicesOfFace(const Face& f) const;
190
191 std::array<int, 2> getVertexIndicesOfHalfEdge(const Halfedge& he) const {
192 return {halfedges[he.pairedHalfedge].endVert, he.endVert};
193 }
194
195 std::array<int, 3> getHalfEdgeIndicesOfFace(const Face& f) const {
196 return {f.he, halfedgeNext[f.he], halfedgeNext[halfedgeNext[f.he]]};
197 }
198 };
199
200 class HalfEdgeMesh {
201 public:
202 Vec<vec3> vertices;
203 // Index of one of the half edges of the faces
204 std::vector<size_t> halfEdgeIndexFaces;
205 Vec<Halfedge> halfedges;
206 Vec<int> halfedgeToFace;
207 Vec<int> halfedgeNext;
208
209 HalfEdgeMesh(const MeshBuilder& builderObject,
210 const VecView<vec3>& vertexData);
211 };
212
213 double defaultEps();
214
215 class QuickHull {
216 struct FaceData {
217 int faceIndex;
218 // If the face turns out not to be visible, this half edge will be marked as
219 // horizon edge
220 int enteredFromHalfedge;
221 };
222
223 double m_epsilon, epsilonSquared, scale;
224 bool planar;
225 Vec<vec3> planarPointCloudTemp;
226 VecView<vec3> originalVertexData;
227 MeshBuilder mesh;
228 std::array<size_t, 6> extremeValues;
229 size_t failedHorizonEdges = 0;
230
231 // Temporary variables used during iteration process
232 Vec<size_t> newFaceIndices;
233 Vec<size_t> newHalfedgeIndices;
234 Vec<size_t> visibleFaces;
235 Vec<size_t> horizonEdgesData;
236 Vec<FaceData> possiblyVisibleFaces;
237 std::vector<std::unique_ptr<Vec<size_t>>> disabledFacePointVectors;
238 std::deque<int> faceList;
239
240 // Create a half edge mesh representing the base tetrahedron from which the
241 // QuickHull iteration proceeds. extremeValues must be properly set up when
242 // this is called.
243 void setupInitialTetrahedron();
244
245 // Given a list of half edges, try to rearrange them so that they form a loop.
246 // Return true on success.
247 bool reorderHorizonEdges(VecView<size_t>& horizonEdges);
248
249 // Find indices of extreme values (max x, min x, max y, min y, max z, min z)
250 // for the given point cloud
251 std::array<size_t, 6> getExtremeValues();
252
253 // Compute scale of the vertex data.
254 double getScale(const std::array<size_t, 6>& extremeValuesInput);
255
256 // Each face contains a unique pointer to a vector of indices. However, many -
257 // often most - faces do not have any points on the positive side of them
258 // especially at the the end of the iteration. When a face is removed from the
259 // mesh, its associated point vector, if such exists, is moved to the index
260 // vector pool, and when we need to add new faces with points on the positive
261 // side to the mesh, we reuse these vectors. This reduces the amount of
262 // std::vectors we have to deal with, and impact on performance is remarkable.
263 Pool indexVectorPool;
264 inline std::unique_ptr<Vec<size_t>> getIndexVectorFromPool();
265 inline void reclaimToIndexVectorPool(std::unique_ptr<Vec<size_t>>& ptr);
266
267 // Associates a point with a face if the point resides on the positive side of
268 // the plane. Returns true if the points was on the positive side.
269 inline bool addPointToFace(typename MeshBuilder::Face& f, size_t pointIndex);
270
271 // This will create HalfedgeMesh from which we create the ConvexHull object
272 // that buildMesh function returns
273 void createConvexHalfedgeMesh();
274
275 public:
276 // This function assumes that the pointCloudVec data resides in memory in the
277 // following format: x_0,y_0,z_0,x_1,y_1,z_1,...
278 QuickHull(VecView<vec3> pointCloudVec)
279 : originalVertexData(VecView(pointCloudVec)) {}
280
281 // Computes convex hull for a given point cloud. Params: eps: minimum distance
282 // to a plane to consider a point being on positive side of it (for a point
283 // cloud with scale 1) Returns: Convex hull of the point cloud as halfEdge
284 // vector and vertex vector
285 std::pair<Vec<Halfedge>, Vec<vec3>> buildMesh(double eps = defaultEps());
286 };
287
288 } // namespace manifold