Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
ContactConstraintManager.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
17#include <Jolt/Math/Vector.h>
18
20#include <atomic>
22
24
25struct PhysicsSettings;
26class PhysicsUpdateContext;
27
32{
33public:
35
37 explicit ContactConstraintManager(const PhysicsSettings &inPhysicsSettings);
39
43 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints);
44
46 void SetContactListener(ContactListener *inListener) { mContactListener = inListener; }
47 ContactListener * GetContactListener() const { return mContactListener; }
48
52 using CombineFunction = float (*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2);
53
56 void SetCombineFriction(CombineFunction inCombineFriction) { mCombineFriction = inCombineFriction; }
57 CombineFunction GetCombineFriction() const { return mCombineFriction; }
58
61 void SetCombineRestitution(CombineFunction inCombineRestitution) { mCombineRestitution = inCombineRestitution; }
62 CombineFunction GetCombineRestitution() const { return mCombineRestitution; }
63
65 uint32 GetMaxConstraints() const { return mMaxConstraints; }
66
68 inline ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) const
69 {
70 if (mContactListener == nullptr)
72
73 return mContactListener->OnContactValidate(inBody1, inBody2, inBaseOffset, inCollisionResult);
74 }
75
77 void PrepareConstraintBuffer(PhysicsUpdateContext *inContext);
78
80 static const int MaxContactPoints = 4;
81
84 {
85 public:
87
88 uint mNumBodyPairs = 0;
89 uint mNumManifolds = 0;
91 };
92
94 ContactAllocator GetContactAllocator() { return mCache[mCacheWriteIdx].GetContactAllocator(); }
95
99 void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated);
100
102 using BodyPairHandle = void *;
103
106 BodyPairHandle AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2);
107
149 bool AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
150
155 void FinalizeContactCacheAndCallContactPointRemovedCallbacks(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
156
159 bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const;
160
162 uint32 GetNumConstraints() const { return min<uint32>(uint32(mNumConstraintsAndNextConstraintOffset.load(memory_order_relaxed)), mMaxConstraints); }
163
165 void ConstraintIdxToConstraintOffset(uint32 *ioConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;
166
168 void SortContacts(uint32 *ioConstraintOffsetBegin, uint32 *inConstraintOffsetEnd) const;
169
171 inline void GetAffectedBodies(uint32 inConstraintOffset, const Body *&outBody1, const Body *&outBody2) const
172 {
173 const ContactConstraintBase &constraint = *reinterpret_cast<const ContactConstraintBase *>(mConstraints + inConstraintOffset);
174 outBody1 = constraint.mBody1;
175 outBody2 = constraint.mBody2;
176 }
177
179 template <class MotionPropertiesCallback>
180 void WarmStartVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback);
181
212 bool SolveVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);
213
215 void StoreAppliedImpulses(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd) const;
216
233 bool SolvePositionConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);
234
236 void RecycleConstraintBuffer();
237
239 void FinishConstraintBuffer();
240
247 void OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings);
248
249#ifdef JPH_DEBUG_RENDERER
250 // Drawing properties
251 static bool sDrawContactPoint;
255#endif // JPH_DEBUG_RENDERER
256
258 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
259
261 bool RestoreState(StateRecorder &inStream, const StateRecorderFilter *inFilter);
262
263private:
265 class CachedContactPoint
266 {
267 public:
269 void SaveState(StateRecorder &inStream) const;
270 void RestoreState(StateRecorder &inStream);
271
274 Float3 mPosition1;
275 Float3 mPosition2;
276
278 float mNonPenetrationLambda;
279 Vector<2> mFrictionLambda;
280 };
281
282 static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");
283 static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");
284
286 class CachedManifold
287 {
288 public:
290 static constexpr int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }
291
293 static constexpr int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }
294
296 void SaveState(StateRecorder &inStream) const;
297 void RestoreState(StateRecorder &inStream);
298
300 uint32 mNextWithSameBodyPair;
301
304 Float3 mContactNormal;
305
307 enum class EFlags : uint16
308 {
309 ContactPersisted = 1,
310 CCDContact = 2
311 };
312
314 mutable atomic<uint16> mFlags { 0 };
315
317 uint16 mNumContactPoints;
318
320 CachedContactPoint mContactPoints[1];
321 };
322
323 static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");
324 static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");
325
328 using MKeyValue = ManifoldMap::KeyValue;
329 using MKVAndCreated = std::pair<MKeyValue *, bool>;
330
332 class CachedBodyPair
333 {
334 public:
336 void SaveState(StateRecorder &inStream) const;
337 void RestoreState(StateRecorder &inStream);
338
341 Float3 mDeltaPosition;
342
345 Float3 mDeltaRotation;
346
348 uint32 mFirstCachedManifold;
349 };
350
351 static_assert(sizeof(CachedBodyPair) == 28, "Unexpected size");
352 static_assert(alignof(CachedBodyPair) == 4, "Assuming 4 byte aligned");
353
356 using BPKeyValue = BodyPairMap::KeyValue;
357
359 class ManifoldCache
360 {
361 public:
363 void Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize);
364
366 void Clear();
367
370 void Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds);
371
373 ContactAllocator GetContactAllocator() { return ContactAllocator(mAllocator, cAllocatorBlockSize); }
374
376 const MKeyValue * Find(const SubShapeIDPair &inKey, uint64 inKeyHash) const;
377 MKeyValue * Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
378 MKVAndCreated FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);
379 uint32 ToHandle(const MKeyValue *inKeyValue) const;
380 const MKeyValue * FromHandle(uint32 inHandle) const;
381
383 const BPKeyValue * Find(const BodyPair &inKey, uint64 inKeyHash) const;
384 BPKeyValue * Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, uint64 inKeyHash);
385 void GetAllBodyPairsSorted(Array<const BPKeyValue *> &outAll) const;
386 void GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, Array<const MKeyValue *> &outAll) const;
387 void GetAllCCDManifoldsSorted(Array<const MKeyValue *> &outAll) const;
388 void ContactPointRemovedCallbacks(ContactListener *inListener);
389
390#ifdef JPH_ENABLE_ASSERTS
392 uint GetNumManifolds() const { return mCachedManifolds.GetNumKeyValues(); }
393
395 uint GetNumBodyPairs() const { return mCachedBodyPairs.GetNumKeyValues(); }
396
398 void Finalize();
399#endif
400
402 void SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;
403 bool RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream, const StateRecorderFilter *inFilter);
404
405 private:
407 static constexpr uint32 cAllocatorBlockSize = 4096;
408
410 LFHMAllocator mAllocator;
411
413 ManifoldMap mCachedManifolds { mAllocator };
414
416 BodyPairMap mCachedBodyPairs { mAllocator };
417
418#ifdef JPH_ENABLE_ASSERTS
419 bool mIsFinalized = false;
420#endif
421 };
422
423 ManifoldCache mCache[2];
424 int mCacheWriteIdx = 0;
425
427 template <EMotionType Type1, EMotionType Type2>
428 class WorldContactPoint
429 {
430 public:
431 using ConstraintPart = ContactConstraintPart<Type1, Type2>;
432
434 JPH_INLINE void CalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution);
435
437 ConstraintPart mNonPenetrationConstraint;
438 ConstraintPart mFrictionConstraint1;
439 ConstraintPart mFrictionConstraint2;
440
442 CachedContactPoint * mContactPoint;
443 };
444
445 class ContactConstraintBase
446 {
447 public:
449 JPH_INLINE Vec3 GetWorldSpaceNormal() const
450 {
451 return Vec3::sLoadFloat3Unsafe(mWorldSpaceNormal);
452 }
453
455 JPH_INLINE void GetTangents(Vec3 &outTangent1, Vec3 &outTangent2) const
456 {
457 Vec3 ws_normal = GetWorldSpaceNormal();
458 outTangent1 = ws_normal.GetNormalizedPerpendicular();
459 outTangent2 = ws_normal.Cross(outTangent1);
460 }
461
462 Body * mBody1;
463 Body * mBody2;
464 uint64 mSortKey;
465 Float3 mWorldSpaceNormal;
466 float mCombinedFriction;
467 float mInvMass1;
468 float mInvInertiaScale1;
469 float mInvMass2;
470 float mInvInertiaScale2;
471 uint32 mNumContactPoints;
472 };
473
475 template <EMotionType Type1, EMotionType Type2>
476 class ContactConstraint : public ContactConstraintBase
477 {
478 public:
479 #ifdef JPH_DEBUG_RENDERER
481 void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;
482 #endif // JPH_DEBUG_RENDERER
483
484 WorldContactPoint<Type1, Type2> mContactPoints[1];
485 };
486
487public:
489 static constexpr uint32 cMaxConstraintSize = sizeof(ContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>) + (MaxContactPoints - 1) * sizeof(WorldContactPoint<EMotionType::Dynamic, EMotionType::Dynamic>);
490
492 static constexpr uint cMaxContactConstraintsLimit = ~uint(0) / cMaxConstraintSize;
493
495 static constexpr uint cMaxBodyPairsLimit = ~uint(0) / sizeof(BodyPairMap::KeyValue);
496
497private:
499 template <EMotionType Type1, EMotionType Type2>
500 JPH_INLINE ContactConstraint<Type1, Type2> *CreateConstraint(Body &inBody1, Body &inBody2, uint64 inSortKey, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, uint32 inNumContactPoints, uint32 &outConstraintIdx);
501
503 template <EMotionType Type1, EMotionType Type2>
504 void TemplatedGetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, const CachedBodyPair &inCachedBodyPair, CachedBodyPair &outCachedBodyPair, bool &outConstraintCreated);
505
507 template <EMotionType Type1, EMotionType Type2>
508 bool TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
509
511 template <EMotionType Type1, EMotionType Type2>
512 static void sWarmStartConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);
513
515 template <EMotionType Type1, EMotionType Type2>
516 static bool sSolveVelocityConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);
517
519 template <EMotionType Type1, EMotionType Type2>
520 static void sStoreAppliedImpulses(ContactConstraintBase &ioConstraint);
521
523 template <EMotionType Type1, EMotionType Type2>
524 static bool sSolvePositionConstraint(ContactConstraintBase &ioConstraint, Body &ioBody1, Body &ioBody2, const PhysicsSettings &inSettings);
525
527 const PhysicsSettings & mPhysicsSettings;
528
530 ContactListener * mContactListener = nullptr;
531
533 CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };
534 CombineFunction mCombineRestitution = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };
535
537 uint8 * mConstraints = nullptr;
538 uint32 * mConstraintIdxToOffset = nullptr;
539 uint32 mMaxConstraints = 0;
540 atomic<uint64> mNumConstraintsAndNextConstraintOffset { 0 }; // Lower 32 bits: number of constraints, upper 32 bits next constraint offset
541
543 PhysicsUpdateContext * mUpdateContext;
544};
545
ValidateResult
Definition ContactListener.h:57
@ AcceptAllContactsForThisBodyPair
Accept this and any further contact points for this body pair.
std::uint8_t uint8
Definition Core.h:506
#define JPH_EXPORT
Definition Core.h:278
#define JPH_SUPPRESS_WARNINGS_STD_BEGIN
Definition Core.h:433
#define JPH_SUPPRESS_WARNINGS_STD_END
Definition Core.h:446
std::uint64_t uint64
Definition Core.h:510
unsigned int uint
Definition Core.h:505
#define JPH_NAMESPACE_END
Definition Core.h:428
std::uint32_t uint32
Definition Core.h:508
#define JPH_NAMESPACE_BEGIN
Definition Core.h:422
std::uint16_t uint16
Definition Core.h:507
EPhysicsUpdateError
Enum used by PhysicsSystem to report error conditions during the PhysicsSystem::Update call....
Definition EPhysicsUpdateError.h:11
#define JPH_OVERRIDE_NEW_DELETE
Macro to override the new and delete functions.
Definition Memory.h:50
Definition Array.h:36
Definition Body.h:39
float GetRestitution() const
Restitution (dimensionless number, usually between 0 and 1, 0 = completely inelastic collision respon...
Definition Body.h:146
float GetFriction() const
Friction (dimensionless number, usually between 0 and 1, 0 = no friction, 1 = friction force equals f...
Definition Body.h:142
ID of a body. This is a way of reasoning about bodies in a multithreaded simulation while avoiding ra...
Definition BodyID.h:13
Class that contains all information of two colliding shapes.
Definition CollideShape.h:19
Class that holds an RGBA color with 8-bits per component.
Definition Color.h:16
Contacts are allocated in a lock free hash map.
Definition ContactConstraintManager.h:84
Definition ContactConstraintManager.h:32
static bool sDrawContactPoint
Definition ContactConstraintManager.h:251
CombineFunction GetCombineFriction() const
Definition ContactConstraintManager.h:57
CombineFunction GetCombineRestitution() const
Definition ContactConstraintManager.h:62
ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, RVec3Arg inBaseOffset, const CollideShapeResult &inCollisionResult) const
Check with the listener if inBody1 and inBody2 could collide, returns false if not.
Definition ContactConstraintManager.h:68
uint32 GetMaxConstraints() const
Get the max number of contact constraints that are allowed.
Definition ContactConstraintManager.h:65
static bool sDrawContactPointReduction
Definition ContactConstraintManager.h:253
void * BodyPairHandle
Handle used to keep track of the current body pair.
Definition ContactConstraintManager.h:102
void GetAffectedBodies(uint32 inConstraintOffset, const Body *&outBody1, const Body *&outBody2) const
Get the affected bodies for a given constraint.
Definition ContactConstraintManager.h:171
ContactListener * GetContactListener() const
Definition ContactConstraintManager.h:47
static bool sDrawSupportingFaces
Definition ContactConstraintManager.h:252
uint32 GetNumConstraints() const
Get the number of contact constraints that were found.
Definition ContactConstraintManager.h:162
void SetCombineFriction(CombineFunction inCombineFriction)
Definition ContactConstraintManager.h:56
void SetContactListener(ContactListener *inListener)
Listener that is notified whenever a contact point between two bodies is added/updated/removed.
Definition ContactConstraintManager.h:46
float(*)(const Body &inBody1, const SubShapeID &inSubShapeID1, const Body &inBody2, const SubShapeID &inSubShapeID2) CombineFunction
Definition ContactConstraintManager.h:52
void SetCombineRestitution(CombineFunction inCombineRestitution)
Definition ContactConstraintManager.h:61
ContactAllocator GetContactAllocator()
Get a new allocator context for storing contacts. Note that you should call this once and then add mu...
Definition ContactConstraintManager.h:94
static bool sDrawContactManifolds
Definition ContactConstraintManager.h:254
Definition ContactConstraintPart.h:94
Definition ContactListener.h:79
Manifold class, describes the contact surface between two bodies.
Definition ContactListener.h:20
Definition ContactListener.h:41
Definition DebugRenderer.h:47
Class that holds 3 floats. Used as a storage class. Convert to Vec3 for calculations.
Definition Float3.h:13
Definition LockFreeHashMap.h:49
LFHMAllocatorContext(LFHMAllocator &inAllocator, uint32 inBlockSize)
Construct a new allocator context.
Definition LockFreeHashMap.inl:88
Allocator for a lock free hash map.
Definition LockFreeHashMap.h:14
Definition LockFreeHashMap.h:72
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition Mat44.h:13
The Body class only keeps track of state for static bodies, the MotionProperties class keeps the addi...
Definition MotionProperties.h:29
Class that makes another class non-copyable. Usage: Inherit from NonCopyable.
Definition NonCopyable.h:11
User callbacks that allow determining which parts of the simulation should be saved by a StateRecorde...
Definition StateRecorder.h:79
Definition StateRecorder.h:110
A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...
Definition SubShapeID.h:23
A pair of bodies and their sub shape ID's. Can be used as a key in a map to find a contact point.
Definition SubShapeIDPair.h:15
Definition Vec3.h:17
JPH_INLINE Vec3 Cross(Vec3Arg inV2) const
Cross product.
Definition Vec3.inl:841
JPH_INLINE Vec3 GetNormalizedPerpendicular() const
Get normalized vector that is perpendicular to this vector.
Definition Vec3.inl:1217
static JPH_INLINE Vec3 sLoadFloat3Unsafe(const Float3 &inV)
Load 3 floats from memory (reads 32 bits extra which it doesn't use)
Definition Vec3.inl:167
Templatized vector class.
Definition Vector.h:12
Structure that holds a body pair.
Definition BodyPair.h:14
Definition PhysicsSettings.h:31