| 1 | // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics) |
| 2 | // SPDX-FileCopyrightText: 2021 Jorrit Rouwe |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #pragma once |
| 6 | |
| 7 | //#define JPH_CONVEX_BUILDER_DEBUG |
| 8 | //#define JPH_CONVEX_BUILDER_DUMP_SHAPE |
| 9 | |
| 10 | #ifdef JPH_CONVEX_BUILDER_DEBUG |
| 11 | #include <Jolt/Core/Color.h> |
| 12 | #endif |
| 13 | |
| 14 | #include <Jolt/Core/StaticArray.h> |
| 15 | #include <Jolt/Core/NonCopyable.h> |
| 16 | |
| 17 | JPH_NAMESPACE_BEGIN |
| 18 | |
| 19 | /// A convex hull builder that tries to create hulls as accurately as possible. Used for offline processing. |
| 20 | class JPH_EXPORT ConvexHullBuilder : public NonCopyable |
| 21 | { |
| 22 | public: |
| 23 | // Forward declare |
| 24 | class Face; |
| 25 | |
| 26 | /// Class that holds the information of an edge |
| 27 | class Edge : public NonCopyable |
| 28 | { |
| 29 | public: |
| 30 | JPH_OVERRIDE_NEW_DELETE |
| 31 | |
| 32 | /// Constructor |
| 33 | Edge(Face *inFace, int inStartIdx) : mFace(inFace), mStartIdx(inStartIdx) { } |
| 34 | |
| 35 | /// Get the previous edge |
| 36 | inline Edge * GetPreviousEdge() |
| 37 | { |
| 38 | Edge *prev_edge = this; |
| 39 | while (prev_edge->mNextEdge != this) |
| 40 | prev_edge = prev_edge->mNextEdge; |
| 41 | return prev_edge; |
| 42 | } |
| 43 | |
| 44 | Face * mFace; ///< Face that this edge belongs to |
| 45 | Edge * mNextEdge = nullptr; ///< Next edge of this face |
| 46 | Edge * mNeighbourEdge = nullptr; ///< Edge that this edge is connected to |
| 47 | int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge |
| 48 | }; |
| 49 | |
| 50 | using ConflictList = Array<int>; |
| 51 | |
| 52 | /// Class that holds the information of one face |
| 53 | class Face : public NonCopyable |
| 54 | { |
| 55 | public: |
| 56 | JPH_OVERRIDE_NEW_DELETE |
| 57 | |
| 58 | /// Destructor |
| 59 | ~Face(); |
| 60 | |
| 61 | /// Initialize a face with three indices |
| 62 | void Initialize(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions); |
| 63 | |
| 64 | /// Calculates the centroid and normal for this face |
| 65 | void CalculateNormalAndCentroid(const Vec3 *inPositions); |
| 66 | |
| 67 | /// Check if face inFace is facing inPosition |
| 68 | inline bool IsFacing(Vec3Arg inPosition) const |
| 69 | { |
| 70 | JPH_ASSERT(!mRemoved); |
| 71 | return mNormal.Dot(inPosition - mCentroid) > 0.0f; |
| 72 | } |
| 73 | |
| 74 | Vec3 mNormal; ///< Normal of this face, length is 2 times area of face |
| 75 | Vec3 mCentroid; ///< Center of the face |
| 76 | ConflictList mConflictList; ///< Positions associated with this edge (that are closest to this edge). The last position in the list is the point that is furthest away from the face. |
| 77 | Edge * mFirstEdge = nullptr; ///< First edge of this face |
| 78 | float mFurthestPointDistanceSq = 0.0f; ///< Squared distance of furthest point from the conflict list to the face |
| 79 | bool mRemoved = false; ///< Flag that indicates that face has been removed (face will be freed later) |
| 80 | #ifdef JPH_CONVEX_BUILDER_DEBUG |
| 81 | int mIteration; ///< Iteration that this face was created |
| 82 | #endif |
| 83 | }; |
| 84 | |
| 85 | // Typedefs |
| 86 | using Positions = Array<Vec3>; |
| 87 | using Faces = Array<Face *>; |
| 88 | |
| 89 | /// Constructor |
| 90 | explicit ConvexHullBuilder(const Positions &inPositions); |
| 91 | |
| 92 | /// Destructor |
| 93 | ~ConvexHullBuilder() { FreeFaces(); } |
| 94 | |
| 95 | /// Result enum that indicates how the hull got created |
| 96 | enum class EResult |
| 97 | { |
| 98 | Success, ///< Hull building finished successfully |
| 99 | MaxVerticesReached, ///< Hull building finished successfully, but the desired accuracy was not reached because the max vertices limit was reached |
| 100 | TooFewPoints, ///< Too few points to create a hull |
| 101 | TooFewFaces, ///< Too few faces in the created hull (signifies precision errors during building) |
| 102 | Degenerate, ///< Degenerate hull detected |
| 103 | }; |
| 104 | |
| 105 | /// Takes all positions as provided by the constructor and use them to build a hull |
| 106 | /// Any points that are closer to the hull than inTolerance will be discarded |
| 107 | /// @param inMaxVertices Max vertices to allow in the hull. Specify INT_MAX if there is no limit. |
| 108 | /// @param inTolerance Max distance that a point is allowed to be outside of the hull |
| 109 | /// @param outError Error message when building fails |
| 110 | /// @return Status code that reports if the hull was created or not |
| 111 | EResult Initialize(int inMaxVertices, float inTolerance, const char *&outError); |
| 112 | |
| 113 | /// Returns the amount of vertices that are currently used by the hull |
| 114 | int GetNumVerticesUsed() const; |
| 115 | |
| 116 | /// Returns true if the hull contains a polygon with inIndices (counter clockwise indices in mPositions) |
| 117 | bool ContainsFace(const Array<int> &inIndices) const; |
| 118 | |
| 119 | /// Calculate the center of mass and the volume of the current convex hull |
| 120 | void GetCenterOfMassAndVolume(Vec3 &outCenterOfMass, float &outVolume) const; |
| 121 | |
| 122 | /// Determines the point that is furthest outside of the hull and reports how far it is outside of the hull (which indicates a failure during hull building) |
| 123 | /// @param outFaceWithMaxError The face that caused the error |
| 124 | /// @param outMaxError The maximum distance of a point to the hull |
| 125 | /// @param outMaxErrorPositionIdx The index of the point that had this distance |
| 126 | /// @param outCoplanarDistance Points that are less than this distance from the hull are considered on the hull. This should be used as a lowerbound for the allowed error. |
| 127 | void DetermineMaxError(Face *&outFaceWithMaxError, float &outMaxError, int &outMaxErrorPositionIdx, float &outCoplanarDistance) const; |
| 128 | |
| 129 | /// Access to the created faces. Memory is owned by the convex hull builder. |
| 130 | const Faces & GetFaces() const { return mFaces; } |
| 131 | |
| 132 | private: |
| 133 | /// Minimal square area of a triangle (used for merging and checking if a triangle is degenerate) |
| 134 | static constexpr float cMinTriangleAreaSq = 1.0e-12f; |
| 135 | |
| 136 | #ifdef JPH_CONVEX_BUILDER_DEBUG |
| 137 | /// Factor to scale convex hull when debug drawing the construction process |
| 138 | static constexpr Real cDrawScale = 10; |
| 139 | #endif |
| 140 | |
| 141 | /// Class that holds an edge including start and end index |
| 142 | class FullEdge |
| 143 | { |
| 144 | public: |
| 145 | Edge * mNeighbourEdge; ///< Edge that this edge is connected to |
| 146 | int mStartIdx; ///< Vertex index in mPositions that indicates the start vertex of this edge |
| 147 | int mEndIdx; ///< Vertex index in mPosition that indicates the end vertex of this edge |
| 148 | }; |
| 149 | |
| 150 | // Private typedefs |
| 151 | using FullEdges = Array<FullEdge>; |
| 152 | |
| 153 | // Determine a suitable tolerance for detecting that points are coplanar |
| 154 | float DetermineCoplanarDistance() const; |
| 155 | |
| 156 | /// Find the face for which inPoint is furthest to the front |
| 157 | /// @param inPoint Point to test |
| 158 | /// @param inFaces List of faces to test |
| 159 | /// @param outFace Returns the best face |
| 160 | /// @param outDistSq Returns the squared distance how much inPoint is in front of the plane of the face |
| 161 | void GetFaceForPoint(Vec3Arg inPoint, const Faces &inFaces, Face *&outFace, float &outDistSq) const; |
| 162 | |
| 163 | /// @brief Calculates the distance between inPoint and inFace |
| 164 | /// @param inFace Face to test |
| 165 | /// @param inPoint Point to test |
| 166 | /// @return If the projection of the point on the plane is interior to the face 0, otherwise the squared distance to the closest edge |
| 167 | float GetDistanceToEdgeSq(Vec3Arg inPoint, const Face *inFace) const; |
| 168 | |
| 169 | /// Assigns a position to one of the supplied faces based on which face is closest. |
| 170 | /// @param inPositionIdx Index of the position to add |
| 171 | /// @param inFaces List of faces to consider |
| 172 | /// @param inToleranceSq Tolerance of the hull, if the point is closer to the face than this, we ignore it |
| 173 | /// @return True if point was assigned, false if it was discarded or added to the coplanar list |
| 174 | bool AssignPointToFace(int inPositionIdx, const Faces &inFaces, float inToleranceSq); |
| 175 | |
| 176 | /// Add a new point to the convex hull |
| 177 | void AddPoint(Face *inFacingFace, int inIdx, float inToleranceSq, Faces &outNewFaces); |
| 178 | |
| 179 | /// Remove all faces that have been marked 'removed' from mFaces list |
| 180 | void GarbageCollectFaces(); |
| 181 | |
| 182 | /// Create a new face |
| 183 | Face * CreateFace(); |
| 184 | |
| 185 | /// Create a new triangle |
| 186 | Face * CreateTriangle(int inIdx1, int inIdx2, int inIdx3); |
| 187 | |
| 188 | /// Delete a face (checking that it is not connected to any other faces) |
| 189 | void FreeFace(Face *inFace); |
| 190 | |
| 191 | /// Release all faces and edges |
| 192 | void FreeFaces(); |
| 193 | |
| 194 | /// Link face edge to other face edge |
| 195 | static void sLinkFace(Edge *inEdge1, Edge *inEdge2); |
| 196 | |
| 197 | /// Unlink this face from all of its neighbours |
| 198 | static void sUnlinkFace(Face *inFace); |
| 199 | |
| 200 | /// Given one face that faces inVertex, find the edges of the faces that are not facing inVertex. |
| 201 | /// Will flag all those faces for removal. |
| 202 | void FindEdge(Face *inFacingFace, Vec3Arg inVertex, FullEdges &outEdges) const; |
| 203 | |
| 204 | /// Merges the two faces that share inEdge into the face inEdge->mFace |
| 205 | void MergeFaces(Edge *inEdge); |
| 206 | |
| 207 | /// Merges inFace with a neighbour if it is degenerate (a sliver) |
| 208 | void MergeDegenerateFace(Face *inFace, Faces &ioAffectedFaces); |
| 209 | |
| 210 | /// Merges any coplanar as well as neighbours that form a non-convex edge into inFace. |
| 211 | /// Faces are considered coplanar if the distance^2 of the other face's centroid is smaller than inToleranceSq. |
| 212 | void MergeCoplanarOrConcaveFaces(Face *inFace, float inToleranceSq, Faces &ioAffectedFaces); |
| 213 | |
| 214 | /// Mark face as affected if it is not already in the list |
| 215 | static void sMarkAffected(Face *inFace, Faces &ioAffectedFaces); |
| 216 | |
| 217 | /// Removes all invalid edges. |
| 218 | /// 1. Merges inFace with faces that share two edges with it since this means inFace or the other face cannot be convex or the edge is colinear. |
| 219 | /// 2. Removes edges that are interior to inFace (that have inFace on both sides) |
| 220 | /// Any faces that need to be checked for validity will be added to ioAffectedFaces. |
| 221 | void RemoveInvalidEdges(Face *inFace, Faces &ioAffectedFaces); |
| 222 | |
| 223 | /// Removes inFace if it consists of only 2 edges, linking its neighbouring faces together |
| 224 | /// Any faces that need to be checked for validity will be added to ioAffectedFaces. |
| 225 | /// @return True if face was removed. |
| 226 | bool RemoveTwoEdgeFace(Face *inFace, Faces &ioAffectedFaces) const; |
| 227 | |
| 228 | #ifdef JPH_ENABLE_ASSERTS |
| 229 | /// Dumps the text representation of a face to the TTY |
| 230 | void DumpFace(const Face *inFace) const; |
| 231 | |
| 232 | /// Dumps the text representation of all faces to the TTY |
| 233 | void DumpFaces() const; |
| 234 | |
| 235 | /// Check consistency of 1 face |
| 236 | void ValidateFace(const Face *inFace) const; |
| 237 | |
| 238 | /// Check consistency of all faces |
| 239 | void ValidateFaces() const; |
| 240 | #endif |
| 241 | |
| 242 | #ifdef JPH_CONVEX_BUILDER_DEBUG |
| 243 | /// Draw state of algorithm |
| 244 | void DrawState(bool inDrawConflictList = false) const; |
| 245 | |
| 246 | /// Draw a face for debugging purposes |
| 247 | void DrawWireFace(const Face *inFace, ColorArg inColor) const; |
| 248 | |
| 249 | /// Draw an edge for debugging purposes |
| 250 | void DrawEdge(const Edge *inEdge, ColorArg inColor) const; |
| 251 | #endif |
| 252 | |
| 253 | #ifdef JPH_CONVEX_BUILDER_DUMP_SHAPE |
| 254 | void DumpShape() const; |
| 255 | #endif |
| 256 | |
| 257 | const Positions & mPositions; ///< List of positions (some of them are part of the hull) |
| 258 | Faces mFaces; ///< List of faces that are part of the hull (if !mRemoved) |
| 259 | |
| 260 | struct Coplanar |
| 261 | { |
| 262 | int mPositionIdx; ///< Index in mPositions |
| 263 | float mDistanceSq; ///< Distance to the edge of closest face (should be > 0) |
| 264 | }; |
| 265 | using CoplanarList = Array<Coplanar>; |
| 266 | |
| 267 | CoplanarList mCoplanarList; ///< List of positions that are coplanar to a face but outside of the face, these are added to the hull at the end |
| 268 | |
| 269 | #ifdef JPH_CONVEX_BUILDER_DEBUG |
| 270 | int mIteration; ///< Number of iterations we've had so far (for debug purposes) |
| 271 | mutable RVec3 mOffset; ///< Offset to use for state drawing |
| 272 | Vec3 mDelta; ///< Delta offset between next states |
| 273 | #endif |
| 274 | }; |
| 275 | |
| 276 | JPH_NAMESPACE_END |