Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
Shape.h
Go to the documentation of this file.
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
11#include <Jolt/Geometry/AABox.h>
12#include <Jolt/Core/Reference.h>
13#include <Jolt/Core/Color.h>
14#include <Jolt/Core/Result.h>
20
22
23struct RayCast;
24class RayCastSettings;
25struct ShapeCast;
27class RayCastResult;
28class ShapeCastResult;
32class SubShapeID;
33class PhysicsMaterial;
35class Plane;
36class SoftBodyVertex;
37class Shape;
38class StreamOut;
39class StreamIn;
40#ifdef JPH_DEBUG_RENDERER
41class DebugRenderer;
42#endif // JPH_DEBUG_RENDERER
43
49
54
56enum class EShapeType : uint8
57{
58 Convex,
59 Compound,
60 Decorated,
61 Mesh,
63 SoftBody,
64
65 // User defined shapes
66 User1,
67 User2,
68 User3,
69 User4,
70};
71
73enum class EShapeSubType : uint8
74{
75 // Convex shapes
76 Sphere,
77 Box,
79 Capsule,
83
84 // Compound shapes
87
88 // Decorated shapes
90 Scaled,
92
93 // Other shapes
94 Mesh,
97
98 // User defined shapes
99 User1,
100 User2,
101 User3,
102 User4,
103 User5,
104 User6,
105 User7,
106 User8,
107
108 // User defined convex shapes
117};
118
119// Sets of shape sub types
122static constexpr EShapeSubType sCompoundSubShapeTypes[] = { EShapeSubType::StaticCompound, EShapeSubType::MutableCompound };
124
126static constexpr uint NumSubShapeTypes = uint(size(sAllSubShapeTypes));
127
129static constexpr const char *sSubShapeTypeNames[] = { "Sphere", "Box", "Triangle", "Capsule", "TaperedCapsule", "Cylinder", "ConvexHull", "StaticCompound", "MutableCompound", "RotatedTranslated", "Scaled", "OffsetCenterOfMass", "Mesh", "HeightField", "SoftBody", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "UserConvex1", "UserConvex2", "UserConvex3", "UserConvex4", "UserConvex5", "UserConvex6", "UserConvex7", "UserConvex8" };
130static_assert(size(sSubShapeTypeNames) == NumSubShapeTypes);
131
138class JPH_EXPORT ShapeSettings : public SerializableObject, public RefTarget<ShapeSettings>
139{
140public:
142
144
146 virtual ShapeResult Create() const = 0;
147
150 void ClearCachedResult() { mCachedResult.Clear(); }
151
153 uint64 mUserData = 0;
154
155protected:
157};
158
161{
162public:
164 Shape * (*mConstruct)() = nullptr;
165
168
170 static inline ShapeFunctions & sGet(EShapeSubType inSubType) { return sRegistry[int(inSubType)]; }
171
172private:
173 static ShapeFunctions sRegistry[NumSubShapeTypes];
174};
175
177class JPH_EXPORT Shape : public RefTarget<Shape>, public NonCopyable
178{
179public:
181
183
185 Shape(EShapeType inType, EShapeSubType inSubType) : mShapeType(inType), mShapeSubType(inSubType) { }
186 Shape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, [[maybe_unused]] ShapeResult &outResult) : mUserData(inSettings.mUserData), mShapeType(inType), mShapeSubType(inSubType) { }
187
189 virtual ~Shape() = default;
190
192 inline EShapeType GetType() const { return mShapeType; }
193 inline EShapeSubType GetSubType() const { return mShapeSubType; }
194
196 uint64 GetUserData() const { return mUserData; }
197 void SetUserData(uint64 inUserData) { mUserData = inUserData; }
198
200 virtual bool MustBeStatic() const { return false; }
201
203 virtual Vec3 GetCenterOfMass() const { return Vec3::sZero(); }
204
206 virtual AABox GetLocalBounds() const = 0;
207
209 virtual uint GetSubShapeIDBitsRecursive() const = 0;
210
214 virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const { return GetLocalBounds().Scaled(inScale).Transformed(inCenterOfMassTransform); }
215
217 AABox GetWorldSpaceBounds(DMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
218 {
219 // Use single precision version using the rotation only
220 AABox bounds = GetWorldSpaceBounds(inCenterOfMassTransform.GetRotation(), inScale);
221
222 // Apply translation
223 bounds.Translate(inCenterOfMassTransform.GetTranslation());
224
225 return bounds;
226 }
227
230 virtual float GetInnerRadius() const = 0;
231
234
236 virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const = 0;
237
240 virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const = 0;
241
244
252 virtual void GetSupportingFace([[maybe_unused]] const SubShapeID &inSubShapeID, [[maybe_unused]] Vec3Arg inDirection, [[maybe_unused]] Vec3Arg inScale, [[maybe_unused]] Mat44Arg inCenterOfMassTransform, [[maybe_unused]] SupportingFace &outVertices) const { /* Nothing */ }
253
255 virtual uint64 GetSubShapeUserData([[maybe_unused]] const SubShapeID &inSubShapeID) const { return mUserData; }
256
264 virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const;
265
273#ifdef JPH_DEBUG_RENDERER
275#endif
276 virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy
277#ifdef JPH_DEBUG_RENDERER // Not using JPH_IF_DEBUG_RENDERER for Doxygen
278 , RVec3Arg inBaseOffset
279#endif
280 ) const = 0;
281
282#ifdef JPH_DEBUG_RENDERER
284 virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const = 0;
285
287 virtual void DrawGetSupportFunction([[maybe_unused]] DebugRenderer *inRenderer, [[maybe_unused]] RMat44Arg inCenterOfMassTransform, [[maybe_unused]] Vec3Arg inScale, [[maybe_unused]] ColorArg inColor, [[maybe_unused]] bool inDrawSupportDirection) const { /* Only implemented for convex shapes */ }
288
290 virtual void DrawGetSupportingFace([[maybe_unused]] DebugRenderer *inRenderer, [[maybe_unused]] RMat44Arg inCenterOfMassTransform, [[maybe_unused]] Vec3Arg inScale) const { /* Only implemented for convex shapes */ }
291#endif // JPH_DEBUG_RENDERER
292
297 virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const = 0;
298
301 virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;
302
307 virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;
308
317 virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, float inDeltaTime, Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const = 0;
318
323 virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const;
324
329 virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const;
330
333 ShapeResult ScaleShape(Vec3Arg inScale) const;
334
336 struct alignas(16) GetTrianglesContext { uint8 mData[4288]; };
337
339 static constexpr int cGetTrianglesMinTrianglesRequested = 32;
340
346 virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const = 0;
347
354 virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const = 0;
355
362
364 virtual void SaveBinaryState(StreamOut &inStream) const;
365
367 static ShapeResult sRestoreFromBinaryState(StreamIn &inStream);
368
370 virtual void SaveMaterialState([[maybe_unused]] PhysicsMaterialList &outMaterials) const { /* By default do nothing */ }
371
373 virtual void RestoreMaterialState([[maybe_unused]] const PhysicsMaterialRefC *inMaterials, [[maybe_unused]] uint inNumMaterials) { JPH_ASSERT(inNumMaterials == 0); }
374
376 virtual void SaveSubShapeState([[maybe_unused]] ShapeList &outSubShapes) const { /* By default do nothing */ }
377
379 virtual void RestoreSubShapeState([[maybe_unused]] const ShapeRefC *inSubShapes, [[maybe_unused]] uint inNumShapes) { JPH_ASSERT(inNumShapes == 0); }
380
385
387 void SaveWithChildren(StreamOut &inStream, ShapeToIDMap &ioShapeMap, MaterialToIDMap &ioMaterialMap) const;
388
390 static ShapeResult sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap);
391
393
395 struct Stats
396 {
397 Stats(size_t inSizeBytes, uint inNumTriangles) : mSizeBytes(inSizeBytes), mNumTriangles(inNumTriangles) { }
398
399 size_t mSizeBytes;
401 };
402
404 virtual Stats GetStats() const = 0;
405
407
410 virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const;
411
413 virtual float GetVolume() const = 0;
414
427 virtual bool IsValidScale(Vec3Arg inScale) const;
428
434 virtual Vec3 MakeScaleValid(Vec3Arg inScale) const;
435
436#ifdef JPH_DEBUG_RENDERER
439#endif // JPH_DEBUG_RENDERER
440
441protected:
443 virtual void RestoreBinaryState(StreamIn &inStream);
444
446 static void sCollidePointUsingRayCast(const Shape &inShape, Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter);
447
448private:
449 uint64 mUserData = 0;
450 EShapeType mShapeType;
451 EShapeSubType mShapeSubType;
452};
453
std::uint8_t uint8
Definition: Core.h:453
#define JPH_EXPORT
Definition: Core.h:236
std::uint64_t uint64
Definition: Core.h:456
unsigned int uint
Definition: Core.h:452
#define JPH_NAMESPACE_END
Definition: Core.h:378
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:372
#define JPH_ASSERT(...)
Definition: IssueReporting.h:33
#define JPH_OVERRIDE_NEW_DELETE
Macro to override the new and delete functions.
Definition: Memory.h:31
#define JPH_DECLARE_SERIALIZABLE_ABSTRACT(linkage, class_name)
Definition: SerializableObject.h:120
EShapeSubType
This enumerates all shape types, each shape can return its type through Shape::GetSubType.
Definition: Shape.h:74
EShapeType
Shapes are categorized in groups, each shape can return which group it belongs to through its Shape::...
Definition: Shape.h:57
@ Compound
Used by CompoundShape.
@ Decorated
Used by DecoratedShape.
@ Mesh
Used by MeshShape.
@ Convex
Used by ConvexShape, all shapes that use the generic convex vs convex collision detection system (box...
@ HeightField
Used by HeightFieldShape.
@ SoftBody
Used by SoftBodyShape.
std::unordered_set< Key, Hash, KeyEqual, STLAllocator< Key > > UnorderedSet
Definition: UnorderedSet.h:13
Axis aligned box.
Definition: AABox.h:16
AABox Scaled(Vec3Arg inScale) const
Scale this bounding box, can handle non-uniform and negative scaling.
Definition: AABox.h:215
AABox Transformed(Mat44Arg inMatrix) const
Transform bounding box.
Definition: AABox.h:184
void Translate(Vec3Arg inTranslation)
Translate bounding box.
Definition: AABox.h:170
Definition: Array.h:36
Structure that holds the result of colliding a point against a shape.
Definition: CollidePointResult.h:14
Class that contains all information of two colliding shapes.
Definition: CollideShape.h:19
Virtual interface that allows collecting multiple collision results.
Definition: CollisionCollector.h:45
Class that holds an RGBA color with 8-bits per component.
Definition: Color.h:16
static const Color sBlack
Predefined colors.
Definition: Color.h:53
Holds a 4x4 matrix of floats with the last column consisting of doubles.
Definition: DMat44.h:13
JPH_INLINE DVec3 GetTranslation() const
Definition: DMat44.h:111
JPH_INLINE Mat44 GetRotation() const
Get rotation part only (note: retains the first 3 values from the bottom row)
Definition: DMat44.h:128
Definition: DebugRenderer.h:47
Class that holds 3 floats. Used as a storage class. Convert to Vec3 for calculations.
Definition: Float3.h:13
Describes the mass and inertia properties of a body. Used during body construction only.
Definition: MassProperties.h:16
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition: Mat44.h:13
Class that makes another class non-copyable. Usage: Inherit from NonCopyable.
Definition: NonCopyable.h:11
Definition: PhysicsMaterial.h:23
An infinite plane described by the formula X . Normal + Constant = 0.
Definition: Plane.h:11
Definition: Quat.h:33
Specialization of cast result against a shape.
Definition: CastResult.h:30
Settings to be passed with a ray cast.
Definition: RayCast.h:70
Definition: Reference.h:101
Definition: Reference.h:35
void Clear()
Clear result or error.
Definition: Result.h:111
Definition: SerializableObject.h:156
Result of a shape cast test.
Definition: ShapeCast.h:111
Settings to be passed with a shape cast.
Definition: ShapeCast.h:92
Filter class.
Definition: ShapeFilter.h:17
Function table for functions on shapes.
Definition: Shape.h:161
static ShapeFunctions & sGet(EShapeSubType inSubType)
Get an entry in the registry for a particular sub type.
Definition: Shape.h:170
Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...
Definition: Shape.h:178
virtual MassProperties GetMassProperties() const =0
Calculate the mass and inertia of this shape.
virtual void SaveSubShapeState(ShapeList &outSubShapes) const
Outputs the shape references that this shape has to outSubShapes.
Definition: Shape.h:376
Shape(EShapeType inType, EShapeSubType inSubType)
Constructor.
Definition: Shape.h:185
virtual float GetInnerRadius() const =0
virtual uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const
Get the user data of a particular sub shape ID.
Definition: Shape.h:255
virtual float GetVolume() const =0
virtual AABox GetLocalBounds() const =0
Get local bounding box including convex radius, this box is centered around the center of mass rather...
EShapeType GetType() const
Get type.
Definition: Shape.h:192
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials=nullptr) const =0
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const
Definition: Shape.h:252
virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
Draw the results of the GetSupportingFace function to show any errors introduced by this process (onl...
Definition: Shape.h:290
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter={ }) const =0
StreamUtils::ObjectToIDMap< Shape > ShapeToIDMap
Definition: Shape.h:381
Shape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, ShapeResult &outResult)
Definition: Shape.h:186
virtual bool MustBeStatic() const
Check if this shape can only be used to create a static body or if it can also be dynamic/kinematic.
Definition: Shape.h:200
virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
Restore the material references after calling sRestoreFromBinaryState. Note that the exact same mater...
Definition: Shape.h:373
virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const
Outputs the material references that this shape has to outMaterials.
Definition: Shape.h:370
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const =0
uint64 GetUserData() const
User data (to be used freely by the application)
Definition: Shape.h:196
StreamUtils::ObjectToIDMap< PhysicsMaterial > MaterialToIDMap
Definition: Shape.h:383
virtual Vec3 GetCenterOfMass() const
All shapes are centered around their center of mass. This function returns the center of mass positio...
Definition: Shape.h:203
virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const =0
Get the material assigned to a particular sub shape ID.
EShapeSubType GetSubType() const
Definition: Shape.h:193
virtual Stats GetStats() const =0
Get stats of this shape. Use for logging / data collection purposes only. Does not add values from ch...
virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const =0
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy, RVec3Arg inBaseOffset) const =0
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
Definition: Shape.h:214
virtual void RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes)
Restore the shape references after calling sRestoreFromBinaryState. Note that the exact same shapes n...
Definition: Shape.h:379
virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const
Draw the results of the GetSupportFunction with the convex radius added back on to show any errors in...
Definition: Shape.h:287
void SetUserData(uint64 inUserData)
Definition: Shape.h:197
virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, SoftBodyVertex *ioVertices, uint inNumVertices, float inDeltaTime, Vec3Arg inDisplacementDueToGravity, int inCollidingShapeIndex) const =0
virtual ~Shape()=default
Destructor.
AABox GetWorldSpaceBounds(DMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
Get world space bounds including convex radius.
Definition: Shape.h:217
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const =0
virtual uint GetSubShapeIDBitsRecursive() const =0
Get the max number of sub shape ID bits that are needed to be able to address any leaf shape in this ...
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const =0
Draw the shape at a particular location with a particular color (debugging purposes)
static bool sDrawSubmergedVolumes
Debug helper which draws the intersection between water and the shapes, the center of buoyancy and th...
Definition: Shape.h:438
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter={ }) const =0
UnorderedSet< const Shape * > VisitedShapes
Definition: Shape.h:406
Definition: Shape.h:139
Result< Ref< Shape > > ShapeResult
Definition: Shape.h:143
ShapeResult mCachedResult
Definition: Shape.h:156
Definition: SoftBodyVertex.h:16
Simple binary input stream.
Definition: StreamIn.h:13
Simple binary output stream.
Definition: StreamOut.h:13
Definition: SubShapeID.h:108
A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...
Definition: SubShapeID.h:23
Definition: TransformedShape.h:26
Definition: Vec3.h:17
static JPH_INLINE Vec3 sZero()
Vector with all zeros.
Definition: Vec3.inl:107
UnorderedMap< const Type *, uint32 > ObjectToIDMap
Definition: StreamUtils.h:18
Definition: RayCast.h:47
An opaque buffer that holds shape specific information during GetTrianglesStart/Next.
Definition: Shape.h:336
Class that holds information about the shape that can be used for logging / data collection purposes.
Definition: Shape.h:396
uint mNumTriangles
Number of triangles in this shape (when applicable)
Definition: Shape.h:400
Stats(size_t inSizeBytes, uint inNumTriangles)
Definition: Shape.h:397
size_t mSizeBytes
Amount of memory used by this shape (size in bytes)
Definition: Shape.h:399
Definition: ShapeCast.h:69