ConvexHullBuilder.h 11 KB

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