MeshShape.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Collision/Shape/Shape.h>
  6. #include <Jolt/Physics/Collision/PhysicsMaterial.h>
  7. #include <Jolt/Core/ByteBuffer.h>
  8. #include <Jolt/Geometry/Triangle.h>
  9. #include <Jolt/Geometry/IndexedTriangle.h>
  10. #ifdef JPH_DEBUG_RENDERER
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. JPH_NAMESPACE_BEGIN
  14. class ConvexShape;
  15. class CollideShapeSettings;
  16. /// Class that constructs a MeshShape
  17. class JPH_EXPORT MeshShapeSettings final : public ShapeSettings
  18. {
  19. JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, MeshShapeSettings)
  20. public:
  21. /// Default constructor for deserialization
  22. MeshShapeSettings() = default;
  23. /// Create a mesh shape.
  24. MeshShapeSettings(const TriangleList &inTriangles, PhysicsMaterialList inMaterials = PhysicsMaterialList());
  25. MeshShapeSettings(VertexList inVertices, IndexedTriangleList inTriangles, PhysicsMaterialList inMaterials = PhysicsMaterialList());
  26. /// Sanitize the mesh data. Remove duplicate and degenerate triangles. This is called automatically when constructing the MeshShapeSettings with a list of (indexed-) triangles.
  27. void Sanitize();
  28. // See: ShapeSettings
  29. virtual ShapeResult Create() const override;
  30. /// Vertices belonging to mIndexedTriangles
  31. VertexList mTriangleVertices;
  32. /// Original list of indexed triangles (triangles will be reordered internally in the mesh shape).
  33. /// Triangles must be provided in counter clockwise order.
  34. /// Degenerate triangles will automatically be removed during mesh creation but no other mesh simplifications are performed, use an external library if this is desired.
  35. /// For simulation, the triangles are considered to be single sided.
  36. /// For ray casts you can choose to make triangles double sided by setting RayCastSettings::mBackFaceMode to EBackFaceMode::CollideWithBackFaces.
  37. /// For collide shape tests you can use CollideShapeSettings::mBackFaceMode and for shape casts you can use ShapeCastSettings::mBackFaceModeTriangles.
  38. IndexedTriangleList mIndexedTriangles;
  39. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  40. PhysicsMaterialList mMaterials;
  41. /// Maximum number of triangles in each leaf of the axis aligned box tree. This is a balance between memory and performance. Can be in the range [1, MeshShape::MaxTrianglesPerLeaf].
  42. /// Sensible values are between 4 (for better performance) and 8 (for less memory usage).
  43. uint mMaxTrianglesPerLeaf = 8;
  44. /// Cosine of the threshold angle (if the angle between the two triangles is bigger than this, the edge is active, note that a concave edge is always inactive).
  45. /// Setting this value too small can cause ghost collisions with edges, setting it too big can cause depenetration artifacts (objects not depenetrating quickly).
  46. /// Valid ranges are between cos(0 degrees) and cos(90 degrees). The default value is cos(5 degrees).
  47. /// Negative values will make all edges active and causes EActiveEdgeMode::CollideOnlyWithActive to behave as EActiveEdgeMode::CollideWithAll.
  48. /// This speeds up the build process but will require all bodies that can interact with the mesh to use BodyCreationSettings::mEnhancedInternalEdgeRemoval = true.
  49. float mActiveEdgeCosThresholdAngle = 0.996195f; // cos(5 degrees)
  50. /// When true, we store the user data coming from Triangle::mUserData or IndexedTriangle::mUserData in the mesh shape.
  51. /// This can be used to store additional data like the original index of the triangle in the mesh.
  52. /// Can be retrieved using MeshShape::GetTriangleUserData.
  53. /// Turning this on increases the memory used by the MeshShape by roughly 25%.
  54. bool mPerTriangleUserData = false;
  55. enum class EBuildQuality
  56. {
  57. FavorRuntimePerformance, ///< Favor runtime performance, takes more time to build the MeshShape but performs better
  58. FavorBuildSpeed, ///< Favor build speed, build the tree faster but the MeshShape will be slower
  59. };
  60. /// Determines the quality of the tree building process.
  61. EBuildQuality mBuildQuality = EBuildQuality::FavorRuntimePerformance;
  62. };
  63. /// A mesh shape, consisting of triangles. Mesh shapes are mostly used for static geometry.
  64. /// They can be used by dynamic or kinematic objects but only if they don't collide with other mesh or heightfield shapes as those collisions are currently not supported.
  65. /// Note that if you make a mesh shape a dynamic or kinematic object, you need to provide a mass yourself as mesh shapes don't need to form a closed hull so don't have a well defined volume from which the mass can be calculated.
  66. class JPH_EXPORT MeshShape final : public Shape
  67. {
  68. public:
  69. JPH_OVERRIDE_NEW_DELETE
  70. /// Constructor
  71. MeshShape() : Shape(EShapeType::Mesh, EShapeSubType::Mesh) { }
  72. MeshShape(const MeshShapeSettings &inSettings, ShapeResult &outResult);
  73. // See Shape::MustBeStatic
  74. virtual bool MustBeStatic() const override { return true; }
  75. // See Shape::GetLocalBounds
  76. virtual AABox GetLocalBounds() const override;
  77. // See Shape::GetSubShapeIDBitsRecursive
  78. virtual uint GetSubShapeIDBitsRecursive() const override;
  79. // See Shape::GetInnerRadius
  80. virtual float GetInnerRadius() const override { return 0.0f; }
  81. // See Shape::GetMassProperties
  82. virtual MassProperties GetMassProperties() const override;
  83. // See Shape::GetMaterial
  84. virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
  85. /// Get the list of all materials
  86. const PhysicsMaterialList & GetMaterialList() const { return mMaterials; }
  87. /// Determine which material index a particular sub shape uses (note that if there are no materials this function will return 0 so check the array size)
  88. /// Note: This could for example be used to create a decorator shape around a mesh shape that overrides the GetMaterial call to replace a material with another material.
  89. uint GetMaterialIndex(const SubShapeID &inSubShapeID) const;
  90. // See Shape::GetSurfaceNormal
  91. virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
  92. // See Shape::GetSupportingFace
  93. virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
  94. #ifdef JPH_DEBUG_RENDERER
  95. // See Shape::Draw
  96. virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
  97. #endif // JPH_DEBUG_RENDERER
  98. // See Shape::CastRay
  99. virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
  100. virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  101. /// See: Shape::CollidePoint
  102. /// Note that for CollidePoint to work for a mesh shape, the mesh needs to be closed (a manifold) or multiple non-intersecting manifolds. Triangles may be facing the interior of the manifold.
  103. /// Insideness is tested by counting the amount of triangles encountered when casting an infinite ray from inPoint. If the number of hits is odd we're inside, if it's even we're outside.
  104. virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  105. // See: Shape::CollideSoftBodyVertices
  106. virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const override;
  107. // See Shape::GetTrianglesStart
  108. virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
  109. // See Shape::GetTrianglesNext
  110. virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
  111. // See Shape::GetSubmergedVolume
  112. virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override { JPH_ASSERT(false, "Not supported"); }
  113. // See Shape
  114. virtual void SaveBinaryState(StreamOut &inStream) const override;
  115. virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const override;
  116. virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) override;
  117. // See Shape::GetStats
  118. virtual Stats GetStats() const override;
  119. // See Shape::GetVolume
  120. virtual float GetVolume() const override { return 0; }
  121. // When MeshShape::mPerTriangleUserData is true, this function can be used to retrieve the user data that was stored in the mesh shape.
  122. uint32 GetTriangleUserData(const SubShapeID &inSubShapeID) const;
  123. #ifdef JPH_DEBUG_RENDERER
  124. // Settings
  125. static bool sDrawTriangleGroups;
  126. static bool sDrawTriangleOutlines;
  127. #endif // JPH_DEBUG_RENDERER
  128. // Register shape functions with the registry
  129. static void sRegister();
  130. protected:
  131. // See: Shape::RestoreBinaryState
  132. virtual void RestoreBinaryState(StreamIn &inStream) override;
  133. private:
  134. struct MSGetTrianglesContext; ///< Context class for GetTrianglesStart/Next
  135. static constexpr int NumTriangleBits = 3; ///< How many bits to reserve to encode the triangle index
  136. static constexpr int MaxTrianglesPerLeaf = 1 << NumTriangleBits; ///< Number of triangles that are stored max per leaf aabb node
  137. /// Find and flag active edges
  138. static void sFindActiveEdges(const MeshShapeSettings &inSettings, IndexedTriangleList &ioIndices);
  139. /// Visit the entire tree using a visitor pattern
  140. template <class Visitor>
  141. void WalkTree(Visitor &ioVisitor) const;
  142. /// Same as above but with a callback per triangle instead of per block of triangles
  143. template <class Visitor>
  144. void WalkTreePerTriangle(const SubShapeIDCreator &inSubShapeIDCreator2, Visitor &ioVisitor) const;
  145. /// Decode a sub shape ID
  146. inline void DecodeSubShapeID(const SubShapeID &inSubShapeID, const void *&outTriangleBlock, uint32 &outTriangleIndex) const;
  147. // Helper functions called by CollisionDispatch
  148. static void sCollideConvexVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
  149. static void sCollideSphereVsMesh(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter);
  150. static void sCastConvexVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
  151. static void sCastSphereVsMesh(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
  152. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  153. PhysicsMaterialList mMaterials;
  154. ByteBuffer mTree; ///< Resulting packed data structure
  155. /// 8 bit flags stored per triangle
  156. enum ETriangleFlags
  157. {
  158. /// Material index
  159. FLAGS_MATERIAL_BITS = 5,
  160. FLAGS_MATERIAL_MASK = (1 << FLAGS_MATERIAL_BITS) - 1,
  161. /// Active edge bits
  162. FLAGS_ACTIVE_EGDE_SHIFT = FLAGS_MATERIAL_BITS,
  163. FLAGS_ACTIVE_EDGE_BITS = 3,
  164. FLAGS_ACTIVE_EDGE_MASK = (1 << FLAGS_ACTIVE_EDGE_BITS) - 1
  165. };
  166. #ifdef JPH_DEBUG_RENDERER
  167. mutable DebugRenderer::GeometryRef mGeometry; ///< Debug rendering data
  168. mutable bool mCachedTrianglesColoredPerGroup = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  169. mutable bool mCachedUseMaterialColors = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  170. #endif // JPH_DEBUG_RENDERER
  171. };
  172. JPH_NAMESPACE_END