MeshShape.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 MeshShapeSettings final : public ShapeSettings
  18. {
  19. public:
  20. JPH_DECLARE_SERIALIZABLE_VIRTUAL(MeshShapeSettings)
  21. /// Default constructor for deserialization
  22. MeshShapeSettings() = default;
  23. /// Create a mesh shape.
  24. MeshShapeSettings(const TriangleList &inTriangles, const PhysicsMaterialList &inMaterials = PhysicsMaterialList());
  25. MeshShapeSettings(const VertexList &inVertices, const IndexedTriangleList &inTriangles, const PhysicsMaterialList &inMaterials = PhysicsMaterialList());
  26. /// Sanitize the mesh data. Remove duplicate and degenerate triangles.
  27. void Sanitize();
  28. // See: ShapeSettings
  29. virtual ShapeResult Create() const override;
  30. /// Mesh data.
  31. VertexList mTriangleVertices; ///< Vertices belonging to mIndexedTriangles
  32. IndexedTriangleList mIndexedTriangles; ///< Original list of indexed triangles
  33. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  34. PhysicsMaterialList mMaterials;
  35. /// 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].
  36. /// Sensible values are between 4 (for better performance) and 8 (for less memory usage).
  37. uint mMaxTrianglesPerLeaf = 8;
  38. };
  39. /// A mesh shape, consisting of triangles. Cannot be used as a dynamic object.
  40. class MeshShape final : public Shape
  41. {
  42. public:
  43. JPH_OVERRIDE_NEW_DELETE
  44. /// Constructor
  45. MeshShape() : Shape(EShapeType::Mesh, EShapeSubType::Mesh) { }
  46. MeshShape(const MeshShapeSettings &inSettings, ShapeResult &outResult);
  47. // See Shape::MustBeStatic
  48. virtual bool MustBeStatic() const override { return true; }
  49. // See Shape::GetLocalBounds
  50. virtual AABox GetLocalBounds() const override;
  51. // See Shape::GetSubShapeIDBitsRecursive
  52. virtual uint GetSubShapeIDBitsRecursive() const override;
  53. // See Shape::GetInnerRadius
  54. virtual float GetInnerRadius() const override { return 0.0f; }
  55. // See Shape::GetMassProperties
  56. virtual MassProperties GetMassProperties() const override;
  57. // See Shape::GetMaterial
  58. virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
  59. /// Get the list of all materials
  60. const PhysicsMaterialList & GetMaterialList() const { return mMaterials; }
  61. /// 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)
  62. /// 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.
  63. uint GetMaterialIndex(const SubShapeID &inSubShapeID) const;
  64. // See Shape::GetSurfaceNormal
  65. virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
  66. // See Shape::GetSupportingFace
  67. virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
  68. #ifdef JPH_DEBUG_RENDERER
  69. // See Shape::Draw
  70. virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
  71. #endif // JPH_DEBUG_RENDERER
  72. // See Shape::CastRay
  73. virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const override;
  74. virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  75. /// See: Shape::CollidePoint
  76. /// 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.
  77. /// 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.
  78. virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const override;
  79. // See Shape::GetTrianglesStart
  80. virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override;
  81. // See Shape::GetTrianglesNext
  82. virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override;
  83. // See Shape::GetSubmergedVolume
  84. 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"); }
  85. // See Shape
  86. virtual void SaveBinaryState(StreamOut &inStream) const override;
  87. virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const override;
  88. virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) override;
  89. // See Shape::GetStats
  90. virtual Stats GetStats() const override;
  91. // See Shape::GetVolume
  92. virtual float GetVolume() const override { return 0; }
  93. #ifdef JPH_DEBUG_RENDERER
  94. // Settings
  95. static bool sDrawTriangleGroups;
  96. static bool sDrawTriangleOutlines;
  97. #endif // JPH_DEBUG_RENDERER
  98. // Register shape functions with the registry
  99. static void sRegister();
  100. protected:
  101. // See: Shape::RestoreBinaryState
  102. virtual void RestoreBinaryState(StreamIn &inStream) override;
  103. private:
  104. struct MSGetTrianglesContext; ///< Context class for GetTrianglesStart/Next
  105. static constexpr int NumTriangleBits = 3; ///< How many bits to reserve to encode the triangle index
  106. static constexpr int MaxTrianglesPerLeaf = 1 << NumTriangleBits; ///< Number of triangles that are stored max per leaf aabb node
  107. /// Find and flag active edges
  108. static void sFindActiveEdges(const VertexList &inVertices, IndexedTriangleList &ioIndices);
  109. /// Visit the entire tree using a visitor pattern
  110. template <class Visitor>
  111. void WalkTree(Visitor &ioVisitor) const;
  112. /// Same as above but with a callback per triangle instead of per block of triangles
  113. template <class Visitor>
  114. void WalkTreePerTriangle(const SubShapeIDCreator &inSubShapeIDCreator2, Visitor &ioVisitor) const;
  115. /// Decode a sub shape ID
  116. inline void DecodeSubShapeID(const SubShapeID &inSubShapeID, const void *&outTriangleBlock, uint32 &outTriangleIndex) const;
  117. // Helper functions called by CollisionDispatch
  118. 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);
  119. 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);
  120. 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);
  121. 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);
  122. /// Materials assigned to the triangles. Each triangle specifies which material it uses through its mMaterialIndex
  123. PhysicsMaterialList mMaterials;
  124. ByteBuffer mTree; ///< Resulting packed data structure
  125. /// 8 bit flags stored per triangle
  126. enum ETriangleFlags
  127. {
  128. /// Material index
  129. FLAGS_MATERIAL_BITS = 5,
  130. FLAGS_MATERIAL_MASK = (1 << FLAGS_MATERIAL_BITS) - 1,
  131. /// Active edge bits
  132. FLAGS_ACTIVE_EGDE_SHIFT = FLAGS_MATERIAL_BITS,
  133. FLAGS_ACTIVE_EDGE_BITS = 3,
  134. FLAGS_ACTIVE_EDGE_MASK = (1 << FLAGS_ACTIVE_EDGE_BITS) - 1
  135. };
  136. #ifdef JPH_DEBUG_RENDERER
  137. mutable DebugRenderer::GeometryRef mGeometry; ///< Debug rendering data
  138. mutable bool mCachedTrianglesColoredPerGroup = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  139. mutable bool mCachedUseMaterialColors = false; ///< This is used to regenerate the triangle batch if the drawing settings change
  140. #endif // JPH_DEBUG_RENDERER
  141. };
  142. JPH_NAMESPACE_END