Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CompoundShape.h
9913 views
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
7
#include <Jolt/Physics/Collision/Shape/Shape.h>
8
#include <Jolt/Physics/Collision/Shape/ScaleHelpers.h>
9
#include <Jolt/Physics/Collision/Shape/SubShapeID.h>
10
11
JPH_NAMESPACE_BEGIN
12
13
class CollideShapeSettings;
14
class OrientedBox;
15
16
/// Base class settings to construct a compound shape
17
class JPH_EXPORT CompoundShapeSettings : public ShapeSettings
18
{
19
JPH_DECLARE_SERIALIZABLE_ABSTRACT(JPH_EXPORT, CompoundShapeSettings)
20
21
public:
22
/// Constructor. Use AddShape to add the parts.
23
CompoundShapeSettings() = default;
24
25
/// Add a shape to the compound.
26
void AddShape(Vec3Arg inPosition, QuatArg inRotation, const ShapeSettings *inShape, uint32 inUserData = 0);
27
28
/// Add a shape to the compound. Variant that uses a concrete shape, which means this object cannot be serialized.
29
void AddShape(Vec3Arg inPosition, QuatArg inRotation, const Shape *inShape, uint32 inUserData = 0);
30
31
struct SubShapeSettings
32
{
33
JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(JPH_EXPORT, SubShapeSettings)
34
35
RefConst<ShapeSettings> mShape; ///< Sub shape (either this or mShapePtr needs to be filled up)
36
RefConst<Shape> mShapePtr; ///< Sub shape (either this or mShape needs to be filled up)
37
Vec3 mPosition; ///< Position of the sub shape
38
Quat mRotation; ///< Rotation of the sub shape
39
40
/// User data value (can be used by the application for any purpose).
41
/// Note this value can be retrieved through GetSubShape(...).mUserData, not through GetSubShapeUserData(...) as that returns Shape::GetUserData() of the leaf shape.
42
/// Use GetSubShapeIndexFromID get a shape index from a SubShapeID to pass to GetSubShape.
43
uint32 mUserData = 0;
44
};
45
46
using SubShapes = Array<SubShapeSettings>;
47
48
SubShapes mSubShapes;
49
};
50
51
/// Base class for a compound shape
52
class JPH_EXPORT CompoundShape : public Shape
53
{
54
public:
55
JPH_OVERRIDE_NEW_DELETE
56
57
/// Constructor
58
explicit CompoundShape(EShapeSubType inSubType) : Shape(EShapeType::Compound, inSubType) { }
59
CompoundShape(EShapeSubType inSubType, const ShapeSettings &inSettings, ShapeResult &outResult) : Shape(EShapeType::Compound, inSubType, inSettings, outResult) { }
60
61
// See Shape::GetCenterOfMass
62
virtual Vec3 GetCenterOfMass() const override { return mCenterOfMass; }
63
64
// See Shape::MustBeStatic
65
virtual bool MustBeStatic() const override;
66
67
// See Shape::GetLocalBounds
68
virtual AABox GetLocalBounds() const override { return mLocalBounds; }
69
70
// See Shape::GetSubShapeIDBitsRecursive
71
virtual uint GetSubShapeIDBitsRecursive() const override;
72
73
// See Shape::GetWorldSpaceBounds
74
virtual AABox GetWorldSpaceBounds(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
75
using Shape::GetWorldSpaceBounds;
76
77
// See Shape::GetInnerRadius
78
virtual float GetInnerRadius() const override { return mInnerRadius; }
79
80
// See Shape::GetMassProperties
81
virtual MassProperties GetMassProperties() const override;
82
83
// See Shape::GetMaterial
84
virtual const PhysicsMaterial * GetMaterial(const SubShapeID &inSubShapeID) const override;
85
86
// See Shape::GetLeafShape
87
virtual const Shape * GetLeafShape(const SubShapeID &inSubShapeID, SubShapeID &outRemainder) const override;
88
89
// See Shape::GetSubShapeUserData
90
virtual uint64 GetSubShapeUserData(const SubShapeID &inSubShapeID) const override;
91
92
// See Shape::GetSubShapeTransformedShape
93
virtual TransformedShape GetSubShapeTransformedShape(const SubShapeID &inSubShapeID, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale, SubShapeID &outRemainder) const override;
94
95
// See Shape::GetSurfaceNormal
96
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const override;
97
98
// See Shape::GetSupportingFace
99
virtual void GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inDirection, Vec3Arg inScale, Mat44Arg inCenterOfMassTransform, SupportingFace &outVertices) const override;
100
101
// See Shape::GetSubmergedVolume
102
virtual void GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const Plane &inSurface, float &outTotalVolume, float &outSubmergedVolume, Vec3 &outCenterOfBuoyancy JPH_IF_DEBUG_RENDERER(, RVec3Arg inBaseOffset)) const override;
103
104
#ifdef JPH_DEBUG_RENDERER
105
// See Shape::Draw
106
virtual void Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inUseMaterialColors, bool inDrawWireframe) const override;
107
108
// See Shape::DrawGetSupportFunction
109
virtual void DrawGetSupportFunction(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale, ColorArg inColor, bool inDrawSupportDirection) const override;
110
111
// See Shape::DrawGetSupportingFace
112
virtual void DrawGetSupportingFace(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransform, Vec3Arg inScale) const override;
113
#endif // JPH_DEBUG_RENDERER
114
115
// See: Shape::CollideSoftBodyVertices
116
virtual void CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const override;
117
118
// See Shape::TransformShape
119
virtual void TransformShape(Mat44Arg inCenterOfMassTransform, TransformedShapeCollector &ioCollector) const override;
120
121
// See Shape::GetTrianglesStart
122
virtual void GetTrianglesStart(GetTrianglesContext &ioContext, const AABox &inBox, Vec3Arg inPositionCOM, QuatArg inRotation, Vec3Arg inScale) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); }
123
124
// See Shape::GetTrianglesNext
125
virtual int GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTrianglesRequested, Float3 *outTriangleVertices, const PhysicsMaterial **outMaterials = nullptr) const override { JPH_ASSERT(false, "Cannot call on non-leaf shapes, use CollectTransformedShapes to collect the leaves first!"); return 0; }
126
127
/// Get which sub shape's bounding boxes overlap with an axis aligned box
128
/// @param inBox The axis aligned box to test against (relative to the center of mass of this shape)
129
/// @param outSubShapeIndices Buffer where to place the indices of the sub shapes that intersect
130
/// @param inMaxSubShapeIndices How many indices will fit in the buffer (normally you'd provide a buffer of GetNumSubShapes() indices)
131
/// @return How many indices were placed in outSubShapeIndices
132
virtual int GetIntersectingSubShapes(const AABox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const = 0;
133
134
/// Get which sub shape's bounding boxes overlap with an axis aligned box
135
/// @param inBox The axis aligned box to test against (relative to the center of mass of this shape)
136
/// @param outSubShapeIndices Buffer where to place the indices of the sub shapes that intersect
137
/// @param inMaxSubShapeIndices How many indices will fit in the buffer (normally you'd provide a buffer of GetNumSubShapes() indices)
138
/// @return How many indices were placed in outSubShapeIndices
139
virtual int GetIntersectingSubShapes(const OrientedBox &inBox, uint *outSubShapeIndices, int inMaxSubShapeIndices) const = 0;
140
141
struct SubShape
142
{
143
/// Initialize sub shape from sub shape settings
144
/// @param inSettings Settings object
145
/// @param outResult Result object, only used in case of error
146
/// @return True on success, false on failure
147
bool FromSettings(const CompoundShapeSettings::SubShapeSettings &inSettings, ShapeResult &outResult)
148
{
149
if (inSettings.mShapePtr != nullptr)
150
{
151
// Use provided shape
152
mShape = inSettings.mShapePtr;
153
}
154
else
155
{
156
// Create child shape
157
ShapeResult child_result = inSettings.mShape->Create();
158
if (!child_result.IsValid())
159
{
160
outResult = child_result;
161
return false;
162
}
163
mShape = child_result.Get();
164
}
165
166
// Copy user data
167
mUserData = inSettings.mUserData;
168
169
SetTransform(inSettings.mPosition, inSettings.mRotation, Vec3::sZero() /* Center of mass not yet calculated */);
170
return true;
171
}
172
173
/// Update the transform of this sub shape
174
/// @param inPosition New position
175
/// @param inRotation New orientation
176
/// @param inCenterOfMass The center of mass of the compound shape
177
JPH_INLINE void SetTransform(Vec3Arg inPosition, QuatArg inRotation, Vec3Arg inCenterOfMass)
178
{
179
SetPositionCOM(inPosition - inCenterOfMass + inRotation * mShape->GetCenterOfMass());
180
181
mIsRotationIdentity = inRotation.IsClose(Quat::sIdentity()) || inRotation.IsClose(-Quat::sIdentity());
182
SetRotation(mIsRotationIdentity? Quat::sIdentity() : inRotation);
183
}
184
185
/// Get the local transform for this shape given the scale of the child shape
186
/// The total transform of the child shape will be GetLocalTransformNoScale(inScale) * Mat44::sScaling(TransformScale(inScale))
187
/// @param inScale The scale of the child shape (in local space of this shape)
188
JPH_INLINE Mat44 GetLocalTransformNoScale(Vec3Arg inScale) const
189
{
190
JPH_ASSERT(IsValidScale(inScale));
191
return Mat44::sRotationTranslation(GetRotation(), inScale * GetPositionCOM());
192
}
193
194
/// Test if inScale is valid for this sub shape
195
inline bool IsValidScale(Vec3Arg inScale) const
196
{
197
// We can always handle uniform scale or identity rotations
198
if (mIsRotationIdentity || ScaleHelpers::IsUniformScale(inScale))
199
return true;
200
201
return ScaleHelpers::CanScaleBeRotated(GetRotation(), inScale);
202
}
203
204
/// Transform the scale to the local space of the child shape
205
inline Vec3 TransformScale(Vec3Arg inScale) const
206
{
207
// We don't need to transform uniform scale or if the rotation is identity
208
if (mIsRotationIdentity || ScaleHelpers::IsUniformScale(inScale))
209
return inScale;
210
211
return ScaleHelpers::RotateScale(GetRotation(), inScale);
212
}
213
214
/// Compress the center of mass position
215
JPH_INLINE void SetPositionCOM(Vec3Arg inPositionCOM)
216
{
217
inPositionCOM.StoreFloat3(&mPositionCOM);
218
}
219
220
/// Uncompress the center of mass position
221
JPH_INLINE Vec3 GetPositionCOM() const
222
{
223
return Vec3::sLoadFloat3Unsafe(mPositionCOM);
224
}
225
226
/// Compress the rotation
227
JPH_INLINE void SetRotation(QuatArg inRotation)
228
{
229
inRotation.StoreFloat3(&mRotation);
230
}
231
232
/// Uncompress the rotation
233
JPH_INLINE Quat GetRotation() const
234
{
235
return mIsRotationIdentity? Quat::sIdentity() : Quat::sLoadFloat3Unsafe(mRotation);
236
}
237
238
RefConst<Shape> mShape;
239
Float3 mPositionCOM; ///< Note: Position of center of mass of sub shape!
240
Float3 mRotation; ///< Note: X, Y, Z of rotation quaternion - note we read 4 bytes beyond this so make sure there's something there
241
uint32 mUserData; ///< User data value (put here because it falls in padding bytes)
242
bool mIsRotationIdentity; ///< If mRotation is close to identity (put here because it falls in padding bytes)
243
// 3 padding bytes left
244
};
245
246
static_assert(sizeof(SubShape) == (JPH_CPU_ADDRESS_BITS == 64? 40 : 36), "Compiler added unexpected padding");
247
248
using SubShapes = Array<SubShape>;
249
250
/// Access to the sub shapes of this compound
251
const SubShapes & GetSubShapes() const { return mSubShapes; }
252
253
/// Get the total number of sub shapes
254
uint GetNumSubShapes() const { return uint(mSubShapes.size()); }
255
256
/// Access to a particular sub shape
257
const SubShape & GetSubShape(uint inIdx) const { return mSubShapes[inIdx]; }
258
259
/// Get the user data associated with a shape in this compound
260
uint32 GetCompoundUserData(uint inIdx) const { return mSubShapes[inIdx].mUserData; }
261
262
/// Set the user data associated with a shape in this compound
263
void SetCompoundUserData(uint inIdx, uint32 inUserData) { mSubShapes[inIdx].mUserData = inUserData; }
264
265
/// Check if a sub shape ID is still valid for this shape
266
/// @param inSubShapeID Sub shape id that indicates the leaf shape relative to this shape
267
/// @return True if the ID is valid, false if not
268
inline bool IsSubShapeIDValid(SubShapeID inSubShapeID) const
269
{
270
SubShapeID remainder;
271
return inSubShapeID.PopID(GetSubShapeIDBits(), remainder) < mSubShapes.size();
272
}
273
274
/// Convert SubShapeID to sub shape index
275
/// @param inSubShapeID Sub shape id that indicates the leaf shape relative to this shape
276
/// @param outRemainder This is the sub shape ID for the sub shape of the compound after popping off the index
277
/// @return The index of the sub shape of this compound
278
inline uint32 GetSubShapeIndexFromID(SubShapeID inSubShapeID, SubShapeID &outRemainder) const
279
{
280
uint32 idx = inSubShapeID.PopID(GetSubShapeIDBits(), outRemainder);
281
JPH_ASSERT(idx < mSubShapes.size(), "Invalid SubShapeID");
282
return idx;
283
}
284
285
/// @brief Convert a sub shape index to a sub shape ID
286
/// @param inIdx Index of the sub shape of this compound
287
/// @param inParentSubShapeID Parent SubShapeID (describing the path to the compound shape)
288
/// @return A sub shape ID creator that contains the full path to the sub shape with index inIdx
289
inline SubShapeIDCreator GetSubShapeIDFromIndex(int inIdx, const SubShapeIDCreator &inParentSubShapeID) const
290
{
291
return inParentSubShapeID.PushID(inIdx, GetSubShapeIDBits());
292
}
293
294
// See Shape
295
virtual void SaveBinaryState(StreamOut &inStream) const override;
296
virtual void SaveSubShapeState(ShapeList &outSubShapes) const override;
297
virtual void RestoreSubShapeState(const ShapeRefC *inSubShapes, uint inNumShapes) override;
298
299
// See Shape::GetStatsRecursive
300
virtual Stats GetStatsRecursive(VisitedShapes &ioVisitedShapes) const override;
301
302
// See Shape::GetVolume
303
virtual float GetVolume() const override;
304
305
// See Shape::IsValidScale
306
virtual bool IsValidScale(Vec3Arg inScale) const override;
307
308
// See Shape::MakeScaleValid
309
virtual Vec3 MakeScaleValid(Vec3Arg inScale) const override;
310
311
// Register shape functions with the registry
312
static void sRegister();
313
314
protected:
315
// See: Shape::RestoreBinaryState
316
virtual void RestoreBinaryState(StreamIn &inStream) override;
317
318
// Visitors for collision detection
319
struct CastRayVisitor;
320
struct CastRayVisitorCollector;
321
struct CollidePointVisitor;
322
struct CastShapeVisitor;
323
struct CollectTransformedShapesVisitor;
324
struct CollideCompoundVsShapeVisitor;
325
struct CollideShapeVsCompoundVisitor;
326
template <class BoxType> struct GetIntersectingSubShapesVisitor;
327
328
/// Determine amount of bits needed to encode sub shape id
329
inline uint GetSubShapeIDBits() const
330
{
331
// Ensure we have enough bits to encode our shape [0, n - 1]
332
uint32 n = uint32(mSubShapes.size()) - 1;
333
return 32 - CountLeadingZeros(n);
334
}
335
336
/// Determine the inner radius of this shape
337
inline void CalculateInnerRadius()
338
{
339
mInnerRadius = FLT_MAX;
340
for (const SubShape &s : mSubShapes)
341
mInnerRadius = min(mInnerRadius, s.mShape->GetInnerRadius());
342
}
343
344
Vec3 mCenterOfMass { Vec3::sZero() }; ///< Center of mass of the compound
345
AABox mLocalBounds { Vec3::sZero(), Vec3::sZero() };
346
SubShapes mSubShapes;
347
float mInnerRadius = FLT_MAX; ///< Smallest radius of GetInnerRadius() of child shapes
348
349
private:
350
// Helper functions called by CollisionDispatch
351
static void sCastCompoundVsShape(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector);
352
};
353
354
JPH_NAMESPACE_END
355
356