ContactConstraintManager.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Core/StaticArray.h>
  5. #include <Core/LockFreeHashMap.h>
  6. #include <Physics/Body/BodyPair.h>
  7. #include <Physics/Collision/Shape/SubShapeIDPair.h>
  8. #include <Physics/Collision/ManifoldBetweenTwoFaces.h>
  9. #include <Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  10. #include <Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h>
  11. #include <Core/HashCombine.h>
  12. #include <Core/NonCopyable.h>
  13. #include <atomic>
  14. namespace JPH {
  15. class PhysicsUpdateContext;
  16. class ContactConstraintManager : public NonCopyable
  17. {
  18. public:
  19. /// Constructor
  20. explicit ContactConstraintManager(const PhysicsSettings &inPhysicsSettings);
  21. ~ContactConstraintManager();
  22. /// Initialize the system.
  23. /// @param inMaxBodyPairs Maximum amount of body pairs to process (anything else will fall through the world), this number should generally be much higher than the max amount of contact points as there will be lots of bodies close that are not actually touching
  24. /// @param inMaxContactConstraints Maximum amount of contact constraints to process (anything else will fall through the world)
  25. void Init(uint inMaxBodyPairs, uint inMaxContactConstraints);
  26. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  27. void SetContactListener(ContactListener *inListener) { mContactListener = inListener; }
  28. ContactListener * GetContactListener() const { return mContactListener; }
  29. /// Callback function to combine the restitution or friction of two bodies
  30. using CombineFunction = float (*)(const Body &inBody1, const Body &inBody2);
  31. /// Set the function that combines the friction of two bodies and returns it
  32. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  33. void SetCombineFriction(CombineFunction inCombineFriction) { mCombineFriction = inCombineFriction; }
  34. /// Set the function that combines the restitution of two bodies and returns it
  35. /// Default method is max(restitution1, restitution1)
  36. void SetCombineRestitution(CombineFunction inCombineRestitution) { mCombineRestitution = inCombineRestitution; }
  37. /// Get the max number of contact constraints that are allowed
  38. uint32 GetMaxConstraints() const { return mMaxConstraints; }
  39. /// Check with the listener if inBody1 and inBody2 could collide, returns false if not
  40. inline ValidateResult ValidateContactPoint(const Body &inBody1, const Body &inBody2, const CollideShapeResult &inCollisionResult) const
  41. {
  42. if (mContactListener == nullptr)
  43. return ValidateResult::AcceptAllContactsForThisBodyPair;
  44. return mContactListener->OnContactValidate(inBody1, inBody2, inCollisionResult);
  45. }
  46. /// Sets up the constraint buffer. Should be called before starting collision detection.
  47. void PrepareConstraintBuffer(PhysicsUpdateContext *inContext);
  48. /// Max 4 contact points are needed for a stable manifold
  49. static const int MaxContactPoints = 4;
  50. /// Check if the contact points from the previous frame are reusable and if so copy them.
  51. /// When the cache was usable and the pair has been handled: outPairHandled = true.
  52. /// When a contact was produced: outContactFound = true.
  53. void GetContactsFromCache(Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outContactFound);
  54. /// Handle used to keep track of the current body pair
  55. using BodyPairHandle = void *;
  56. /// Create a handle for a colliding body pair so that contact constraints can be added between them.
  57. /// Needs to be called once per body pair per frame before calling AddContactConstraint.
  58. BodyPairHandle AddBodyPair(const Body &inBody1, const Body &inBody2);
  59. /// Add a contact constraint for this frame.
  60. ///
  61. /// @param inBodyPair The handle for the contact cache for this body pair
  62. /// @param inBody1 The first body that is colliding
  63. /// @param inBody2 The second body that is colliding
  64. /// @param inManifold The manifold that describes the collision
  65. ///
  66. /// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2009 (and later years with slight modifications).
  67. /// We're using the formulas from slide 50 - 53 combined.
  68. ///
  69. /// Euler velocity integration:
  70. ///
  71. /// v1' = v1 + M^-1 P
  72. ///
  73. /// Impulse:
  74. ///
  75. /// P = J^T lambda
  76. ///
  77. /// Constraint force:
  78. ///
  79. /// lambda = -K^-1 J v1
  80. ///
  81. /// Inverse effective mass:
  82. ///
  83. /// K = J M^-1 J^T
  84. ///
  85. /// Constraint equation (limits movement in 1 axis):
  86. ///
  87. /// C = (p2 - p1) . n
  88. ///
  89. /// Jacobian (for position constraint)
  90. ///
  91. /// J = [-n, -r1 x n, n, r2 x n]
  92. ///
  93. /// n = contact normal (pointing away from body 1).
  94. /// p1, p2 = positions of collision on body 1 and 2.
  95. /// r1, r2 = contact point relative to center of mass of body 1 and body 2 (r1 = p1 - x1, r2 = p2 - x2).
  96. /// v1, v2 = (linear velocity, angular velocity): 6 vectors containing linear and angular velocity for body 1 and 2.
  97. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].
  98. void AddContactConstraint(BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);
  99. /// Finalizes the contact cache, the contact cache that was generated during the calls to AddContactConstraint in this update
  100. /// will be used from now on to read from
  101. void FinalizeContactCache();
  102. /// Notifies the listener of any contact points that were removed. Needs to be callsed after FinalizeContactCache().
  103. void ContactPointRemovedCallbacks();
  104. /// Get the number of contact constraints that were found
  105. uint32 GetNumConstraints() const { return min<uint32>(mNumConstraints, mMaxConstraints); }
  106. /// Sort contact constraints deterministically
  107. void SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const;
  108. /// AddContactConstraint will also setup the velocity constraints for the first sub step. For subsequent sub steps this function must be called prior to warm starting the constraint.
  109. void SetupVelocityConstraints(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd, float inDeltaTime);
  110. /// Apply last frame's impulses as an initial guess for this frame's impulses
  111. void WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio);
  112. /// Solve velocity constraints, when almost nothing changes this should only apply very small impulses
  113. /// since we're warm starting with the total impulse applied in the last frame above.
  114. ///
  115. /// Friction wise we're using the Coulomb friction model which says that:
  116. ///
  117. /// |F_T| <= mu |F_N|
  118. ///
  119. /// Where F_T is the tangential force, F_N is the normal force and mu is the friction coefficient
  120. ///
  121. /// In impulse terms this becomes:
  122. ///
  123. /// |lambda_T| <= mu |lambda_N|
  124. ///
  125. /// And the constraint that needs to be applied is exactly the same as a non penetration constraint
  126. /// except that we use a tangent instead of a normal. The tangent should point in the direction of the
  127. /// tangential velocity of the point:
  128. ///
  129. /// J = [-T, -r1 x T, T, r2 x T]
  130. ///
  131. /// Where T is the tangent.
  132. ///
  133. /// See slide 42 and 43.
  134. ///
  135. /// Restitution is implemented as a velocity bias (see slide 41):
  136. ///
  137. /// b = e v_n^-
  138. ///
  139. /// e = the restitution coefficient, v_n^- is the normal velocity prior to the collision
  140. ///
  141. /// Restitution is only applied when v_n^- is large enough and the points are moving towards collision
  142. bool SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
  143. /// Save back the lambdas to the contact cache for the next warm start
  144. void StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
  145. /// Solve position constraints.
  146. /// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2007.
  147. /// On slide 78 it is suggested to split up the Baumgarte stabilization for positional drift so that it does not
  148. /// actually add to the momentum. We combine an Euler velocity integrate + a position integrate and then discard the velocity
  149. /// change.
  150. ///
  151. /// Constraint force:
  152. ///
  153. /// lambda = -K^-1 b
  154. ///
  155. /// Baumgarte stabilization:
  156. ///
  157. /// b = beta / dt C
  158. ///
  159. /// beta = baumgarte stabilization factor.
  160. /// dt = delta time.
  161. bool SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);
  162. /// Recycle the constraint buffer. Should be called between collision simulation steps.
  163. void RecycleConstraintBuffer();
  164. /// Terminate the constraint buffer. Should be called after simulation ends.
  165. void FinishConstraintBuffer();
  166. /// Called by continuous collision detection to notify the contact listener that a contact was added
  167. /// @param inBody1 The first body that is colliding
  168. /// @param inBody2 The second body that is colliding
  169. /// @param inManifold The manifold that describes the collision
  170. /// @param outSettings The calculated contact settings (may be overridden by the contact listener)
  171. void OnCCDContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings);
  172. #ifdef JPH_DEBUG_RENDERER
  173. // Drawing properties
  174. static bool sDrawContactPoint;
  175. static bool sDrawSupportingFaces;
  176. static bool sDrawContactPointReduction;
  177. static bool sDrawContactManifolds;
  178. #endif // JPH_DEBUG_RENDERER
  179. /// Saving state for replay
  180. void SaveState(StateRecorder &inStream) const;
  181. /// Restoring state for replay. Returns false when failed.
  182. bool RestoreState(StateRecorder &inStream);
  183. private:
  184. /// Local space contact point, used for caching impulses
  185. class CachedContactPoint
  186. {
  187. public:
  188. /// Saving / restoring state for replay
  189. void SaveState(StateRecorder &inStream) const;
  190. void RestoreState(StateRecorder &inStream);
  191. /// Local space positions on body 1 and 2.
  192. /// Note: these values are read through sLoadFloat3Unsafe.
  193. Float3 mPosition1;
  194. Float3 mPosition2;
  195. /// Total applied impulse during the last update that it was used
  196. float mNonPenetrationLambda;
  197. Vector<2> mFrictionLambda;
  198. };
  199. static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");
  200. static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");
  201. /// A single cached manifold
  202. class CachedManifold
  203. {
  204. public:
  205. /// Calculate size in bytes needed beyond the size of the class to store inNumContactPoints
  206. static int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }
  207. /// Calculate total class size needed for storing inNumContactPoints
  208. static int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }
  209. /// Saving / restoring state for replay
  210. void SaveState(StateRecorder &inStream) const;
  211. void RestoreState(StateRecorder &inStream);
  212. /// Handle to next cached contact points in ManifoldCache::mCachedManifolds for the same body pair
  213. uint32 mNextWithSameBodyPair;
  214. /// Contact normal in the space of 2.
  215. /// Note: this value is read through sLoadFloat3Unsafe.
  216. Float3 mContactNormal;
  217. /// Flags for this cached manifold
  218. enum class EFlags : uint16
  219. {
  220. ContactPersisted = 1, ///< If this cache entry was reused in the next simulation update
  221. CCDContact = 2 ///< This is a cached manifold reported by continuous collision detection and was only used to create a contact callback
  222. };
  223. /// @see EFlags
  224. mutable atomic<uint16> mFlags { 0 };
  225. /// Number of contact points in the array below
  226. uint16 mNumContactPoints;
  227. /// Contact points that this manifold consists of
  228. CachedContactPoint mContactPoints[1];
  229. };
  230. static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");
  231. static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");
  232. /// Define a map that maps SubShapeIDPair -> manifold
  233. using ManifoldMap = LockFreeHashMap<SubShapeIDPair, CachedManifold>;
  234. using MKeyValue = ManifoldMap::KeyValue;
  235. using MKVAndCreated = pair<MKeyValue *, bool>;
  236. /// Start of list of contact points for a particular pair of bodies
  237. class CachedBodyPair
  238. {
  239. public:
  240. /// Saving / restoring state for replay
  241. void SaveState(StateRecorder &inStream) const;
  242. void RestoreState(StateRecorder &inStream);
  243. /// Local space position difference from Body A to Body B.
  244. /// Note: this value is read through sLoadFloat3Unsafe
  245. Float3 mDeltaPosition;
  246. /// Local space rotation difference from Body A to Body B, fourth component of quaternion is not stored but is guaranteed >= 0.
  247. /// Note: this value is read through sLoadFloat3Unsafe
  248. Float3 mDeltaRotation;
  249. /// Handle to first manifold in ManifoldCache::mCachedManifolds
  250. uint32 mFirstCachedManifold;
  251. };
  252. static_assert(sizeof(CachedBodyPair) == 28, "Unexpected size");
  253. static_assert(alignof(CachedBodyPair) == 4, "Assuming 4 byte aligned");
  254. /// Define a map that maps BodyPair -> CachedBodyPair
  255. using BodyPairMap = LockFreeHashMap<BodyPair, CachedBodyPair>;
  256. using BPKeyValue = BodyPairMap::KeyValue;
  257. /// Holds all caches that are needed to quickly find cached body pairs / manifolds
  258. class ManifoldCache
  259. {
  260. public:
  261. /// Initialize the cache
  262. void Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize);
  263. /// Reset all entries from the cache
  264. void Clear();
  265. /// Prepare cache before creating new contacts. Uses previous frame to determine amount of buckets in the hash map.
  266. void Prepare(const ManifoldCache &inReadCache);
  267. /// Find / create cached entry for SubShapeIDPair -> CachedManifold
  268. const MKeyValue * Find(const SubShapeIDPair &inKey, size_t inKeyHash) const;
  269. MKeyValue * Create(const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints);
  270. MKVAndCreated FindOrCreate(const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints);
  271. uint32 ToHandle(const MKeyValue *inKeyValue) const;
  272. const MKeyValue * FromHandle(uint32 inHandle) const;
  273. /// Find / create entry for BodyPair -> CachedBodyPair
  274. const BPKeyValue * Find(const BodyPair &inKey, size_t inKeyHash) const;
  275. BPKeyValue * Create(const BodyPair &inKey, size_t inKeyHash);
  276. void GetAllBodyPairsSorted(vector<const BPKeyValue *> &outAll) const;
  277. void GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, vector<const MKeyValue *> &outAll) const;
  278. void GetAllCCDManifoldsSorted(vector<const MKeyValue *> &outAll) const;
  279. void ContactPointRemovedCallbacks(ContactListener *inListener);
  280. #ifdef JPH_ENABLE_ASSERTS
  281. /// Before a cache is finalized you can only do Create(), after only Find() or Clear()
  282. void Finalize();
  283. #endif
  284. /// Saving / restoring state for replay
  285. void SaveState(StateRecorder &inStream) const;
  286. bool RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream);
  287. private:
  288. /// Simple hash map for SubShapeIDPair -> CachedManifold
  289. ManifoldMap mCachedManifolds;
  290. /// Simple hash map for BodyPair -> CachedBodyPair
  291. BodyPairMap mCachedBodyPairs;
  292. #ifdef JPH_ENABLE_ASSERTS
  293. bool mIsFinalized = false; ///< Marks if this buffer is complete
  294. #endif
  295. };
  296. ManifoldCache mCache[2]; ///< We have one cache to read from and one to write to
  297. int mCacheWriteIdx = 0; ///< Which cache we're currently writing to
  298. /// World space contact point, used for solving penetrations
  299. class WorldContactPoint
  300. {
  301. public:
  302. /// Calculate constraint properties below
  303. void CalculateNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpacePosition1, Vec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal);
  304. void CalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpacePosition1, Vec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, float inCombinedRestitution, float inCombinedFriction, float inMinVelocityForRestitution);
  305. /// The constraint parts
  306. AxisConstraintPart mNonPenetrationConstraint;
  307. AxisConstraintPart mFrictionConstraint1;
  308. AxisConstraintPart mFrictionConstraint2;
  309. /// Contact cache
  310. CachedContactPoint * mContactPoint;
  311. };
  312. using WorldContactPoints = StaticArray<WorldContactPoint, MaxContactPoints>;
  313. /// Contact constraint class, used for solving penetrations
  314. class ContactConstraint
  315. {
  316. public:
  317. #ifdef JPH_DEBUG_RENDERER
  318. /// Draw the state of the contact constraint
  319. void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;
  320. #endif // JPH_DEBUG_RENDERER
  321. /// Get the tangents for this contact constraint
  322. JPH_INLINE void GetTangents(Vec3 &outTangent1, Vec3 &outTangent2) const
  323. {
  324. outTangent1 = mWorldSpaceNormal.GetNormalizedPerpendicular();
  325. outTangent2 = mWorldSpaceNormal.Cross(outTangent1);
  326. }
  327. Vec3 mWorldSpaceNormal;
  328. Body * mBody1;
  329. Body * mBody2;
  330. size_t mSortKey;
  331. ContactSettings mSettings;
  332. WorldContactPoints mContactPoints;
  333. };
  334. /// The main physics settings instance
  335. const PhysicsSettings & mPhysicsSettings;
  336. /// Listener that is notified whenever a contact point between two bodies is added/updated/removed
  337. ContactListener * mContactListener = nullptr;
  338. /// Functions that are used to combine friction and restitution of 2 bodies
  339. CombineFunction mCombineFriction = [](const Body &inBody1, const Body &inBody2) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };
  340. CombineFunction mCombineRestitution = [](const Body &inBody1, const Body &inBody2) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };
  341. /// The constraints that were added this frame
  342. ContactConstraint * mConstraints = nullptr;
  343. uint32 mMaxConstraints = 0;
  344. atomic<uint32> mNumConstraints { 0 };
  345. /// Context used for this physics update
  346. PhysicsUpdateContext * mUpdateContext;
  347. };
  348. } // JPH