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>
19
21
22struct RayCast;
23class RayCastSettings;
24struct ShapeCast;
26class RayCastResult;
27class ShapeCastResult;
31class SubShapeID;
32class PhysicsMaterial;
34class Plane;
35class Shape;
36class StreamOut;
37class StreamIn;
38#ifdef JPH_DEBUG_RENDERER
39class DebugRenderer;
40#endif // JPH_DEBUG_RENDERER
41
47
52
54enum class EShapeType : uint8
55{
56 Convex,
57 Compound,
58 Decorated,
59 Mesh,
61
62 // User defined shapes
63 User1,
64 User2,
65 User3,
66 User4,
67};
68
70enum class EShapeSubType : uint8
71{
72 // Convex shapes
73 Sphere,
74 Box,
76 Capsule,
80
81 // Compound shapes
84
85 // Decorated shapes
87 Scaled,
89
90 // Other shapes
91 Mesh,
93
94 // User defined shapes
95 User1,
96 User2,
97 User3,
98 User4,
99 User5,
100 User6,
101 User7,
102 User8,
103
104 // User defined convex shapes
113};
114
115// Sets of shape sub types
118static constexpr EShapeSubType sCompoundSubShapeTypes[] = { EShapeSubType::StaticCompound, EShapeSubType::MutableCompound };
120
122static constexpr uint NumSubShapeTypes = (uint)size(sAllSubShapeTypes);
123
125static constexpr const char *sSubShapeTypeNames[] = { "Sphere", "Box", "Triangle", "Capsule", "TaperedCapsule", "Cylinder", "ConvexHull", "StaticCompound", "MutableCompound", "RotatedTranslated", "Scaled", "OffsetCenterOfMass", "Mesh", "HeightField", "User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "UserConvex1", "UserConvex2", "UserConvex3", "UserConvex4", "UserConvex5", "UserConvex6", "UserConvex7", "UserConvex8" };
126static_assert(size(sSubShapeTypeNames) == NumSubShapeTypes);
127
134class ShapeSettings : public SerializableObject, public RefTarget<ShapeSettings>
135{
136public:
138
140
142 virtual ShapeResult Create() const = 0;
143
146
147protected:
149};
150
153{
154public:
156 Shape * (*mConstruct)() = nullptr;
157
160
162 static inline ShapeFunctions & sGet(EShapeSubType inSubType) { return sRegistry[(int)inSubType]; }
163
164private:
165 static ShapeFunctions sRegistry[NumSubShapeTypes];
166};
167
169class Shape : public RefTarget<Shape>, public NonCopyable
170{
171public:
173
175
177 Shape(EShapeType inType, EShapeSubType inSubType) : mShapeType(inType), mShapeSubType(inSubType) { }
178 Shape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, [[maybe_unused]] ShapeResult &outResult) : mUserData(inSettings.mUserData), mShapeType(inType), mShapeSubType(inSubType) { }
179
181 virtual ~Shape() = default;
182
184 inline EShapeType GetType() const { return mShapeType; }
185 inline EShapeSubType GetSubType() const { return mShapeSubType; }
186
188 uint64 GetUserData() const { return mUserData; }
189 void SetUserData(uint64 inUserData) { mUserData = inUserData; }
190
192 virtual bool MustBeStatic() const { return false; }
193
195 virtual Vec3 GetCenterOfMass() const { return Vec3::sZero(); }
196
198 virtual AABox GetLocalBounds() const = 0;
199
201 virtual uint GetSubShapeIDBitsRecursive() const = 0;
202
206 virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const { return GetLocalBounds().Scaled(inScale).Transformed(inCenterOfMassTransform); }
207
209 AABox GetWorldSpaceBounds(DMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
210 {
211 // Use single precision version using the rotation only
212 AABox bounds = GetWorldSpaceBounds(inCenterOfMassTransform.GetRotation(), inScale);
213
214 // Apply translation
215 bounds.Translate(inCenterOfMassTransform.GetTranslation());
216
217 return bounds;
218 }
219
222 virtual float GetInnerRadius() const = 0;
223
226
228 virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const = 0;
229
232 virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const = 0;
233
236
244 virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const { /* Nothing */ }
245
247 virtual uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const { return mUserData; }
248
256 virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const;
257
265#ifdef JPH_DEBUG_RENDERER
267#endif
268 virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy
269#ifdef JPH_DEBUG_RENDERER // Not using JPH_IF_DEBUG_RENDERER for Doxygen
270 , RVec3Arg inBaseOffset
271#endif
272 ) const = 0;
273
274#ifdef JPH_DEBUG_RENDERER
276 virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const = 0;
277
279 virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const { /* Only implemented for convex shapes */ }
280
282 virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const { /* Only implemented for convex shapes */ }
283#endif // JPH_DEBUG_RENDERER
284
289 virtual bool CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const = 0;
290
293 virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;
294
299 virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter = { }) const = 0;
300
305 virtual void CollectTransformedShapes(const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, const SubShapeIDCreator &inSubShapeIDCreator, TransformedShapeCollector &ioCollector, const ShapeFilter &inShapeFilter) const;
306
311 virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const;
312
315 ShapeResult ScaleShape(Vec3Arg inScale) const;
316
318 struct alignas(16) GetTrianglesContext { uint8 mData[4288]; };
319
321 static constexpr int cGetTrianglesMinTrianglesRequested = 32;
322
328 virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const = 0;
329
336 virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const = 0;
337
343
345 virtual void SaveBinaryState(StreamOut &inStream) const;
346
348 static ShapeResult sRestoreFromBinaryState(StreamIn &inStream);
349
351 virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const { /* By default do nothing */ }
352
354 virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials) { JPH_ASSERT(inNumMaterials == 0); }
355
357 virtual void SaveSubShapeState(ShapeList &outSubShapes) const { /* By default do nothing */ }
358
360 virtual void RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes) { JPH_ASSERT(inNumShapes == 0); }
361
366
368 void SaveWithChildren(StreamOut &inStream, ShapeToIDMap &ioShapeMap, MaterialToIDMap &ioMaterialMap) const;
369
371 static ShapeResult sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap);
372
374
376 struct Stats
377 {
378 Stats(size_t inSizeBytes, uint inNumTriangles) : mSizeBytes(inSizeBytes), mNumTriangles(inNumTriangles) { }
379
380 size_t mSizeBytes;
382 };
383
385 virtual Stats GetStats() const = 0;
386
388
391 virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const;
392
394 virtual float GetVolume() const = 0;
395
398 virtual bool IsValidScale(Vec3Arg inScale) const { return !inScale.IsNearZero(); }
399
400#ifdef JPH_DEBUG_RENDERER
403#endif // JPH_DEBUG_RENDERER
404
405protected:
407 virtual void RestoreBinaryState(StreamIn &inStream);
408
409private:
410 uint64 mUserData = 0;
411 EShapeType mShapeType;
412 EShapeSubType mShapeSubType;
413};
414
unsigned int uint
Definition: Core.h:309
#define JPH_NAMESPACE_END
Definition: Core.h:240
uint8_t uint8
Definition: Core.h:310
uint64_t uint64
Definition: Core.h:313
#define JPH_NAMESPACE_BEGIN
Definition: Core.h:234
#define JPH_ASSERT(...)
Definition: IssueReporting.h:33
#define JPH_OVERRIDE_NEW_DELETE
Macro to override the new and delete functions.
Definition: Memory.h:29
Array< RefConst< PhysicsMaterial > > PhysicsMaterialList
Definition: PhysicsMaterial.h:50
std::vector< T, STLAllocator< T > > Array
Definition: STLAllocator.h:81
#define JPH_DECLARE_SERIALIZABLE_ABSTRACT(class_name)
Definition: SerializableObject.h:111
EShapeSubType
This enumerates all shape types, each shape can return its type through Shape::GetSubType.
Definition: Shape.h:71
Array< ShapeRefC > ShapeList
Definition: Shape.h:49
EShapeType
Shapes are categorized in groups, each shape can return which group it belongs to through its Shape::...
Definition: Shape.h:55
@ 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.
Array< PhysicsMaterialRefC > PhysicsMaterialList
Definition: Shape.h:51
std::unordered_map< Key, T, Hash, KeyEqual, STLAllocator< pair< const Key, T > > > UnorderedMap
Definition: UnorderedMap.h:13
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
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:46
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:110
JPH_INLINE Mat44 GetRotation() const
Get rotation part only (note: retains the first 3 values from the bottom row)
Definition: DMat44.h:124
Simple triangle renderer for debugging purposes.
Definition: DebugRenderer.h:25
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:27
Settings to be passed with a ray cast.
Definition: RayCast.h:64
Definition: Reference.h:101
Definition: Reference.h:35
Definition: SerializableObject.h:147
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:153
static ShapeFunctions & sGet(EShapeSubType inSubType)
Get an entry in the registry for a particular sub type.
Definition: Shape.h:162
Base class for all shapes (collision volume of a body). Defines a virtual interface for collision det...
Definition: Shape.h:170
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:357
Shape(EShapeType inType, EShapeSubType inSubType)
Constructor.
Definition: Shape.h:177
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:247
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:184
Array< Ref< Shape > > IDToShapeMap
Definition: Shape.h:364
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:244
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:282
virtual void CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter={ }) const =0
Array< Ref< PhysicsMaterial > > IDToMaterialMap
Definition: Shape.h:365
Shape(EShapeType inType, EShapeSubType inSubType, const ShapeSettings &inSettings, ShapeResult &outResult)
Definition: Shape.h:178
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:192
virtual void RestoreMaterialState(const PhysicsMaterialRefC *inMaterials, uint inNumMaterials)
Restore the material references after calling sRestoreFromBinaryState. Note that the exact same mater...
Definition: Shape.h:354
virtual void SaveMaterialState(PhysicsMaterialList &outMaterials) const
Outputs the material references that this shape has to outMaterials.
Definition: Shape.h:351
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const =0
virtual bool IsValidScale(Vec3Arg inScale) const
Definition: Shape.h:398
uint64 GetUserData() const
User data (to be used freely by the application)
Definition: Shape.h:188
virtual Vec3 GetCenterOfMass() const
All shapes are centered around their center of mass. This function returns the center of mass positio...
Definition: Shape.h:195
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:185
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:206
UnorderedMap< const Shape *, uint32 > ShapeToIDMap
Definition: Shape.h:362
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:360
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:279
void SetUserData(uint64 inUserData)
Definition: Shape.h:189
virtual ~Shape()=default
Destructor.
UnorderedMap< const PhysicsMaterial *, uint32 > MaterialToIDMap
Definition: Shape.h:363
AABox GetWorldSpaceBounds(DMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const
Get world space bounds including convex radius.
Definition: Shape.h:209
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:402
virtual void CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter={ }) const =0
UnorderedSet< const Shape * > VisitedShapes
Definition: Shape.h:387
Definition: Shape.h:135
virtual ShapeResult Create() const =0
Create a shape according to the settings specified by this object.
Result< Ref< Shape > > ShapeResult
Definition: Shape.h:139
ShapeResult mCachedResult
Definition: Shape.h:148
uint64 mUserData
User data (to be used freely by the application)
Definition: Shape.h:145
Simple binary input stream.
Definition: StreamIn.h:11
Simple binary output stream.
Definition: StreamOut.h:11
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:16
JPH_INLINE bool IsNearZero(float inMaxDistSq=1.0e-12f) const
Test if vector is near zero.
Definition: Vec3.inl:347
static JPH_INLINE Vec3 sZero()
Vector with all zeros.
Definition: Vec3.inl:107
Definition: RayCast.h:41
An opaque buffer that holds shape specific information during GetTrianglesStart/Next.
Definition: Shape.h:318
Class that holds information about the shape that can be used for logging / data collection purposes.
Definition: Shape.h:377
uint mNumTriangles
Number of triangles in this shape (when applicable)
Definition: Shape.h:381
Stats(size_t inSizeBytes, uint inNumTriangles)
Definition: Shape.h:378
size_t mSizeBytes
Amount of memory used by this shape (size in bytes)
Definition: Shape.h:380
Definition: ShapeCast.h:69