ContactConstraintManager.cpp 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Constraints/ContactConstraintManager.h>
  6. #include <Jolt/Physics/Body/Body.h>
  7. #include <Jolt/Physics/PhysicsUpdateContext.h>
  8. #include <Jolt/Physics/PhysicsSettings.h>
  9. #include <Jolt/Physics/IslandBuilder.h>
  10. #include <Jolt/Physics/DeterminismLog.h>
  11. #include <Jolt/Core/TempAllocator.h>
  12. #include <Jolt/Core/QuickSort.h>
  13. #ifdef JPH_DEBUG_RENDERER
  14. #include <Jolt/Renderer/DebugRenderer.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. JPH_NAMESPACE_BEGIN
  17. using namespace literals;
  18. #ifdef JPH_DEBUG_RENDERER
  19. bool ContactConstraintManager::sDrawContactPoint = false;
  20. bool ContactConstraintManager::sDrawSupportingFaces = false;
  21. bool ContactConstraintManager::sDrawContactPointReduction = false;
  22. bool ContactConstraintManager::sDrawContactManifolds = false;
  23. #endif // JPH_DEBUG_RENDERER
  24. //#define JPH_MANIFOLD_CACHE_DEBUG
  25. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  26. // ContactConstraintManager::WorldContactPoint
  27. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  28. void ContactConstraintManager::WorldContactPoint::CalculateNonPenetrationConstraintProperties(const Body &inBody1, const Body &inBody2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal)
  29. {
  30. // Calculate collision points relative to body
  31. RVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);
  32. Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());
  33. Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());
  34. mNonPenetrationConstraint.CalculateConstraintProperties(inBody1, r1, inBody2, r2, inWorldSpaceNormal);
  35. }
  36. template <EMotionType Type1, EMotionType Type2>
  37. JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, float inCombinedRestitution, float inCombinedFriction, float inMinVelocityForRestitution, float inSurfaceVelocity1, float inSurfaceVelocity2)
  38. {
  39. JPH_DET_LOG("TemplatedCalculateFrictionAndNonPenetrationConstraintProperties: p1: " << inWorldSpacePosition1 << " p2: " << inWorldSpacePosition2
  40. << " normal: " << inWorldSpaceNormal << " tangent1: " << inWorldSpaceTangent1 << " tangent2: " << inWorldSpaceTangent2
  41. << " restitution: " << inCombinedRestitution << " friction: " << inCombinedFriction << " minv: " << inMinVelocityForRestitution
  42. << " surf1: " << inSurfaceVelocity1 << " surf2: " << inSurfaceVelocity2);
  43. // Calculate collision points relative to body
  44. RVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);
  45. Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());
  46. Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());
  47. // Calculate velocity of collision points
  48. Vec3 relative_velocity;
  49. if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)
  50. relative_velocity = inBody2.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r2) - inBody1.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r1);
  51. else if constexpr (Type1 != EMotionType::Static)
  52. relative_velocity = -inBody1.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r1);
  53. else if constexpr (Type2 != EMotionType::Static)
  54. relative_velocity = inBody2.GetMotionPropertiesUnchecked()->GetPointVelocityCOM(r2);
  55. else
  56. {
  57. JPH_ASSERT(false); // Static vs static makes no sense
  58. relative_velocity = Vec3::sZero();
  59. }
  60. float normal_velocity = relative_velocity.Dot(inWorldSpaceNormal);
  61. // How much the shapes are penetrating (> 0 if penetrating, < 0 if separated)
  62. float penetration = Vec3(inWorldSpacePosition1 - inWorldSpacePosition2).Dot(inWorldSpaceNormal);
  63. // If there is no penetration, this is a speculative contact and we will apply a bias to the contact constraint
  64. // so that the constraint becomes relative_velocity . contact normal > -penetration / delta_time
  65. // instead of relative_velocity . contact normal > 0
  66. // See: GDC 2013: "Physics for Game Programmers; Continuous Collision" - Erin Catto
  67. float speculative_contact_velocity_bias = max(0.0f, -penetration / inDeltaTime);
  68. // Determine if the velocity is big enough for restitution
  69. float normal_velocity_bias;
  70. if (inCombinedRestitution > 0.0f && normal_velocity < -inMinVelocityForRestitution)
  71. {
  72. // We have a velocity that is big enough for restitution. This is where speculative contacts don't work
  73. // great as we have to decide now if we're going to apply the restitution or not. If the relative
  74. // velocity is big enough for a hit, we apply the restitution (in the end, due to other constraints,
  75. // the objects may actually not collide and we will have applied restitution incorrectly). Another
  76. // artifact that occurs because of this approximation is that the object will bounce from its current
  77. // position rather than from a position where it is touching the other object. This causes the object
  78. // to appear to move faster for 1 frame (the opposite of time stealing).
  79. if (normal_velocity < -speculative_contact_velocity_bias)
  80. normal_velocity_bias = inCombinedRestitution * normal_velocity;
  81. else
  82. // In this case we have predicted that we don't hit the other object, but if we do (due to other constraints changing velocities)
  83. // the speculative contact will prevent penetration but will not apply restitution leading to another artifact.
  84. normal_velocity_bias = speculative_contact_velocity_bias;
  85. }
  86. else
  87. {
  88. // No restitution. We can safely apply our contact velocity bias.
  89. normal_velocity_bias = speculative_contact_velocity_bias;
  90. }
  91. mNonPenetrationConstraint.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceNormal, normal_velocity_bias);
  92. // Calculate friction part
  93. if (inCombinedFriction > 0.0f)
  94. {
  95. // Implement friction as 2 AxisContraintParts
  96. mFrictionConstraint1.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent1, inSurfaceVelocity1);
  97. mFrictionConstraint2.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent2, inSurfaceVelocity2);
  98. }
  99. else
  100. {
  101. // Turn off friction constraint
  102. mFrictionConstraint1.Deactivate();
  103. mFrictionConstraint2.Deactivate();
  104. }
  105. }
  106. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  107. // ContactConstraintManager::ContactConstraint
  108. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  109. #ifdef JPH_DEBUG_RENDERER
  110. void ContactConstraintManager::ContactConstraint::Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const
  111. {
  112. if (mContactPoints.empty())
  113. return;
  114. // Get body transforms
  115. RMat44 transform_body1 = mBody1->GetCenterOfMassTransform();
  116. RMat44 transform_body2 = mBody2->GetCenterOfMassTransform();
  117. RVec3 prev_point = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints.back().mContactPoint->mPosition1);
  118. for (const WorldContactPoint &wcp : mContactPoints)
  119. {
  120. // Test if any lambda from the previous frame was transferred
  121. float radius = wcp.mNonPenetrationConstraint.GetTotalLambda() == 0.0f
  122. && wcp.mFrictionConstraint1.GetTotalLambda() == 0.0f
  123. && wcp.mFrictionConstraint2.GetTotalLambda() == 0.0f? 0.1f : 0.2f;
  124. RVec3 next_point = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  125. inRenderer->DrawMarker(next_point, Color::sCyan, radius);
  126. inRenderer->DrawMarker(transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2), Color::sPurple, radius);
  127. // Draw edge
  128. inRenderer->DrawArrow(prev_point, next_point, inManifoldColor, 0.05f);
  129. prev_point = next_point;
  130. }
  131. // Draw normal
  132. RVec3 wp = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints[0].mContactPoint->mPosition1);
  133. inRenderer->DrawArrow(wp, wp + GetWorldSpaceNormal(), Color::sRed, 0.05f);
  134. // Get tangents
  135. Vec3 t1, t2;
  136. GetTangents(t1, t2);
  137. // Draw tangents
  138. inRenderer->DrawLine(wp, wp + t1, Color::sGreen);
  139. inRenderer->DrawLine(wp, wp + t2, Color::sBlue);
  140. }
  141. #endif // JPH_DEBUG_RENDERER
  142. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  143. // ContactConstraintManager::CachedContactPoint
  144. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  145. void ContactConstraintManager::CachedContactPoint::SaveState(StateRecorder &inStream) const
  146. {
  147. inStream.Write(mPosition1);
  148. inStream.Write(mPosition2);
  149. inStream.Write(mNonPenetrationLambda);
  150. inStream.Write(mFrictionLambda);
  151. }
  152. void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &inStream)
  153. {
  154. inStream.Read(mPosition1);
  155. inStream.Read(mPosition2);
  156. inStream.Read(mNonPenetrationLambda);
  157. inStream.Read(mFrictionLambda);
  158. }
  159. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  160. // ContactConstraintManager::CachedManifold
  161. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  162. void ContactConstraintManager::CachedManifold::SaveState(StateRecorder &inStream) const
  163. {
  164. inStream.Write(mContactNormal);
  165. }
  166. void ContactConstraintManager::CachedManifold::RestoreState(StateRecorder &inStream)
  167. {
  168. inStream.Read(mContactNormal);
  169. }
  170. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  171. // ContactConstraintManager::CachedBodyPair
  172. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  173. void ContactConstraintManager::CachedBodyPair::SaveState(StateRecorder &inStream) const
  174. {
  175. inStream.Write(mDeltaPosition);
  176. inStream.Write(mDeltaRotation);
  177. }
  178. void ContactConstraintManager::CachedBodyPair::RestoreState(StateRecorder &inStream)
  179. {
  180. inStream.Read(mDeltaPosition);
  181. inStream.Read(mDeltaRotation);
  182. }
  183. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  184. // ContactConstraintManager::ManifoldCache
  185. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  186. void ContactConstraintManager::ManifoldCache::Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize)
  187. {
  188. mAllocator.Init(inMaxBodyPairs * sizeof(BodyPairMap::KeyValue) + inCachedManifoldsSize);
  189. mCachedManifolds.Init(GetNextPowerOf2(inMaxContactConstraints));
  190. mCachedBodyPairs.Init(GetNextPowerOf2(inMaxBodyPairs));
  191. }
  192. void ContactConstraintManager::ManifoldCache::Clear()
  193. {
  194. JPH_PROFILE_FUNCTION();
  195. mCachedManifolds.Clear();
  196. mCachedBodyPairs.Clear();
  197. mAllocator.Clear();
  198. #ifdef JPH_ENABLE_ASSERTS
  199. // Mark as incomplete
  200. mIsFinalized = false;
  201. #endif
  202. }
  203. void ContactConstraintManager::ManifoldCache::Prepare(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds)
  204. {
  205. // Minimum amount of buckets to use in the hash map
  206. constexpr uint32 cMinBuckets = 1024;
  207. // Use the next higher power of 2 of amount of objects in the cache from last frame to determine the amount of buckets in this frame
  208. mCachedManifolds.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inExpectedNumManifolds)), mCachedManifolds.GetMaxBuckets()));
  209. mCachedBodyPairs.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inExpectedNumBodyPairs)), mCachedBodyPairs.GetMaxBuckets()));
  210. }
  211. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Find(const SubShapeIDPair &inKey, uint64 inKeyHash) const
  212. {
  213. JPH_ASSERT(mIsFinalized);
  214. return mCachedManifolds.Find(inKey, inKeyHash);
  215. }
  216. ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Create(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints)
  217. {
  218. JPH_ASSERT(!mIsFinalized);
  219. MKeyValue *kv = mCachedManifolds.Create(ioContactAllocator, inKey, inKeyHash, CachedManifold::sGetRequiredExtraSize(inNumContactPoints));
  220. if (kv == nullptr)
  221. {
  222. ioContactAllocator.mErrors |= EPhysicsUpdateError::ManifoldCacheFull;
  223. return nullptr;
  224. }
  225. kv->GetValue().mNumContactPoints = uint16(inNumContactPoints);
  226. ++ioContactAllocator.mNumManifolds;
  227. return kv;
  228. }
  229. ContactConstraintManager::MKVAndCreated ContactConstraintManager::ManifoldCache::FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints)
  230. {
  231. MKeyValue *kv = const_cast<MKeyValue *>(mCachedManifolds.Find(inKey, inKeyHash));
  232. if (kv != nullptr)
  233. return { kv, false };
  234. return { Create(ioContactAllocator, inKey, inKeyHash, inNumContactPoints), true };
  235. }
  236. uint32 ContactConstraintManager::ManifoldCache::ToHandle(const MKeyValue *inKeyValue) const
  237. {
  238. JPH_ASSERT(!mIsFinalized);
  239. return mCachedManifolds.ToHandle(inKeyValue);
  240. }
  241. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::FromHandle(uint32 inHandle) const
  242. {
  243. JPH_ASSERT(mIsFinalized);
  244. return mCachedManifolds.FromHandle(inHandle);
  245. }
  246. const ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Find(const BodyPair &inKey, uint64 inKeyHash) const
  247. {
  248. JPH_ASSERT(mIsFinalized);
  249. return mCachedBodyPairs.Find(inKey, inKeyHash);
  250. }
  251. ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Create(ContactAllocator &ioContactAllocator, const BodyPair &inKey, uint64 inKeyHash)
  252. {
  253. JPH_ASSERT(!mIsFinalized);
  254. BPKeyValue *kv = mCachedBodyPairs.Create(ioContactAllocator, inKey, inKeyHash, 0);
  255. if (kv == nullptr)
  256. {
  257. ioContactAllocator.mErrors |= EPhysicsUpdateError::BodyPairCacheFull;
  258. return nullptr;
  259. }
  260. ++ioContactAllocator.mNumBodyPairs;
  261. return kv;
  262. }
  263. void ContactConstraintManager::ManifoldCache::GetAllBodyPairsSorted(Array<const BPKeyValue *> &outAll) const
  264. {
  265. JPH_ASSERT(mIsFinalized);
  266. mCachedBodyPairs.GetAllKeyValues(outAll);
  267. // Sort by key
  268. QuickSort(outAll.begin(), outAll.end(), [](const BPKeyValue *inLHS, const BPKeyValue *inRHS) {
  269. return inLHS->GetKey() < inRHS->GetKey();
  270. });
  271. }
  272. void ContactConstraintManager::ManifoldCache::GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, Array<const MKeyValue *> &outAll) const
  273. {
  274. JPH_ASSERT(mIsFinalized);
  275. // Iterate through the attached manifolds
  276. for (uint32 handle = inBodyPair.mFirstCachedManifold; handle != ManifoldMap::cInvalidHandle; handle = FromHandle(handle)->GetValue().mNextWithSameBodyPair)
  277. {
  278. const MKeyValue *kv = mCachedManifolds.FromHandle(handle);
  279. outAll.push_back(kv);
  280. }
  281. // Sort by key
  282. QuickSort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  283. return inLHS->GetKey() < inRHS->GetKey();
  284. });
  285. }
  286. void ContactConstraintManager::ManifoldCache::GetAllCCDManifoldsSorted(Array<const MKeyValue *> &outAll) const
  287. {
  288. mCachedManifolds.GetAllKeyValues(outAll);
  289. for (int i = (int)outAll.size() - 1; i >= 0; --i)
  290. if ((outAll[i]->GetValue().mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0)
  291. {
  292. outAll[i] = outAll.back();
  293. outAll.pop_back();
  294. }
  295. // Sort by key
  296. QuickSort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  297. return inLHS->GetKey() < inRHS->GetKey();
  298. });
  299. }
  300. void ContactConstraintManager::ManifoldCache::ContactPointRemovedCallbacks(ContactListener *inListener)
  301. {
  302. JPH_PROFILE_FUNCTION();
  303. for (MKeyValue &kv : mCachedManifolds)
  304. if ((kv.GetValue().mFlags & uint16(CachedManifold::EFlags::ContactPersisted)) == 0)
  305. inListener->OnContactRemoved(kv.GetKey());
  306. }
  307. #ifdef JPH_ENABLE_ASSERTS
  308. void ContactConstraintManager::ManifoldCache::Finalize()
  309. {
  310. mIsFinalized = true;
  311. #ifdef JPH_MANIFOLD_CACHE_DEBUG
  312. Trace("ManifoldMap:");
  313. mCachedManifolds.TraceStats();
  314. Trace("BodyPairMap:");
  315. mCachedBodyPairs.TraceStats();
  316. #endif // JPH_MANIFOLD_CACHE_DEBUG
  317. }
  318. #endif
  319. void ContactConstraintManager::ManifoldCache::SaveState(StateRecorder &inStream) const
  320. {
  321. JPH_ASSERT(mIsFinalized);
  322. // Get contents of cache
  323. Array<const BPKeyValue *> all_bp;
  324. GetAllBodyPairsSorted(all_bp);
  325. // Write amount of body pairs
  326. size_t num_body_pairs = all_bp.size();
  327. inStream.Write(num_body_pairs);
  328. // Write all body pairs
  329. for (const BPKeyValue *bp_kv : all_bp)
  330. {
  331. // Write body pair key
  332. inStream.Write(bp_kv->GetKey());
  333. // Write body pair
  334. const CachedBodyPair &bp = bp_kv->GetValue();
  335. bp.SaveState(inStream);
  336. // Get attached manifolds
  337. Array<const MKeyValue *> all_m;
  338. GetAllManifoldsSorted(bp, all_m);
  339. // Write num manifolds
  340. size_t num_manifolds = all_m.size();
  341. inStream.Write(num_manifolds);
  342. // Write all manifolds
  343. for (const MKeyValue *m_kv : all_m)
  344. {
  345. // Write key
  346. inStream.Write(m_kv->GetKey());
  347. const CachedManifold &cm = m_kv->GetValue();
  348. JPH_ASSERT((cm.mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0);
  349. // Write amount of contacts
  350. inStream.Write(cm.mNumContactPoints);
  351. // Write manifold
  352. cm.SaveState(inStream);
  353. // Write contact points
  354. for (uint32 i = 0; i < cm.mNumContactPoints; ++i)
  355. cm.mContactPoints[i].SaveState(inStream);
  356. }
  357. }
  358. // Get CCD manifolds
  359. Array<const MKeyValue *> all_m;
  360. GetAllCCDManifoldsSorted(all_m);
  361. // Write num CCD manifolds
  362. size_t num_manifolds = all_m.size();
  363. inStream.Write(num_manifolds);
  364. // Write all CCD manifold keys
  365. for (const MKeyValue *m_kv : all_m)
  366. inStream.Write(m_kv->GetKey());
  367. }
  368. bool ContactConstraintManager::ManifoldCache::RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream)
  369. {
  370. JPH_ASSERT(!mIsFinalized);
  371. bool success = true;
  372. // Create a contact allocator for restoring the contact cache
  373. ContactAllocator contact_allocator(GetContactAllocator());
  374. // When validating, get all existing body pairs
  375. Array<const BPKeyValue *> all_bp;
  376. if (inStream.IsValidating())
  377. inReadCache.GetAllBodyPairsSorted(all_bp);
  378. // Read amount of body pairs
  379. size_t num_body_pairs;
  380. if (inStream.IsValidating())
  381. num_body_pairs = all_bp.size();
  382. inStream.Read(num_body_pairs);
  383. // Read entire cache
  384. for (size_t i = 0; i < num_body_pairs; ++i)
  385. {
  386. // Read key
  387. BodyPair body_pair_key;
  388. if (inStream.IsValidating() && i < all_bp.size())
  389. body_pair_key = all_bp[i]->GetKey();
  390. inStream.Read(body_pair_key);
  391. // Create new entry for this body pair
  392. uint64 body_pair_hash = body_pair_key.GetHash();
  393. BPKeyValue *bp_kv = Create(contact_allocator, body_pair_key, body_pair_hash);
  394. if (bp_kv == nullptr)
  395. {
  396. // Out of cache space
  397. success = false;
  398. break;
  399. }
  400. CachedBodyPair &bp = bp_kv->GetValue();
  401. // Read body pair
  402. if (inStream.IsValidating() && i < all_bp.size())
  403. memcpy(&bp, &all_bp[i]->GetValue(), sizeof(CachedBodyPair));
  404. bp.RestoreState(inStream);
  405. // When validating, get all existing manifolds
  406. Array<const MKeyValue *> all_m;
  407. if (inStream.IsValidating())
  408. inReadCache.GetAllManifoldsSorted(all_bp[i]->GetValue(), all_m);
  409. // Read amount of manifolds
  410. size_t num_manifolds;
  411. if (inStream.IsValidating())
  412. num_manifolds = all_m.size();
  413. inStream.Read(num_manifolds);
  414. uint32 handle = ManifoldMap::cInvalidHandle;
  415. for (size_t j = 0; j < num_manifolds; ++j)
  416. {
  417. // Read key
  418. SubShapeIDPair sub_shape_key;
  419. if (inStream.IsValidating() && j < all_m.size())
  420. sub_shape_key = all_m[j]->GetKey();
  421. inStream.Read(sub_shape_key);
  422. uint64 sub_shape_key_hash = sub_shape_key.GetHash();
  423. // Read amount of contact points
  424. uint16 num_contact_points;
  425. if (inStream.IsValidating() && j < all_m.size())
  426. num_contact_points = all_m[j]->GetValue().mNumContactPoints;
  427. inStream.Read(num_contact_points);
  428. // Read manifold
  429. MKeyValue *m_kv = Create(contact_allocator, sub_shape_key, sub_shape_key_hash, num_contact_points);
  430. if (m_kv == nullptr)
  431. {
  432. // Out of cache space
  433. success = false;
  434. break;
  435. }
  436. CachedManifold &cm = m_kv->GetValue();
  437. if (inStream.IsValidating() && j < all_m.size())
  438. {
  439. memcpy(&cm, &all_m[j]->GetValue(), CachedManifold::sGetRequiredTotalSize(num_contact_points));
  440. cm.mNumContactPoints = uint16(num_contact_points); // Restore num contact points
  441. }
  442. cm.RestoreState(inStream);
  443. cm.mNextWithSameBodyPair = handle;
  444. handle = ToHandle(m_kv);
  445. // Read contact points
  446. for (uint32 k = 0; k < num_contact_points; ++k)
  447. cm.mContactPoints[k].RestoreState(inStream);
  448. }
  449. bp.mFirstCachedManifold = handle;
  450. }
  451. // When validating, get all existing CCD manifolds
  452. Array<const MKeyValue *> all_m;
  453. if (inStream.IsValidating())
  454. inReadCache.GetAllCCDManifoldsSorted(all_m);
  455. // Read amount of CCD manifolds
  456. size_t num_manifolds;
  457. if (inStream.IsValidating())
  458. num_manifolds = all_m.size();
  459. inStream.Read(num_manifolds);
  460. for (size_t j = 0; j < num_manifolds; ++j)
  461. {
  462. // Read key
  463. SubShapeIDPair sub_shape_key;
  464. if (inStream.IsValidating() && j < all_m.size())
  465. sub_shape_key = all_m[j]->GetKey();
  466. inStream.Read(sub_shape_key);
  467. uint64 sub_shape_key_hash = sub_shape_key.GetHash();
  468. // Create CCD manifold
  469. MKeyValue *m_kv = Create(contact_allocator, sub_shape_key, sub_shape_key_hash, 0);
  470. if (m_kv == nullptr)
  471. {
  472. // Out of cache space
  473. success = false;
  474. break;
  475. }
  476. CachedManifold &cm = m_kv->GetValue();
  477. cm.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  478. }
  479. #ifdef JPH_ENABLE_ASSERTS
  480. mIsFinalized = true;
  481. #endif
  482. return success;
  483. }
  484. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  485. // ContactConstraintManager
  486. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  487. ContactConstraintManager::ContactConstraintManager(const PhysicsSettings &inPhysicsSettings) :
  488. mPhysicsSettings(inPhysicsSettings)
  489. {
  490. #ifdef JPH_ENABLE_ASSERTS
  491. // For the first frame mark this empty buffer as finalized
  492. mCache[mCacheWriteIdx ^ 1].Finalize();
  493. #endif
  494. }
  495. ContactConstraintManager::~ContactConstraintManager()
  496. {
  497. JPH_ASSERT(mConstraints == nullptr);
  498. }
  499. void ContactConstraintManager::Init(uint inMaxBodyPairs, uint inMaxContactConstraints)
  500. {
  501. mMaxConstraints = inMaxContactConstraints;
  502. // Calculate worst case cache usage
  503. uint cached_manifolds_size = inMaxContactConstraints * (sizeof(CachedManifold) + (MaxContactPoints - 1) * sizeof(CachedContactPoint));
  504. // Init the caches
  505. mCache[0].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  506. mCache[1].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  507. }
  508. void ContactConstraintManager::PrepareConstraintBuffer(PhysicsUpdateContext *inContext)
  509. {
  510. // Store context
  511. mUpdateContext = inContext;
  512. // Allocate temporary constraint buffer
  513. JPH_ASSERT(mConstraints == nullptr);
  514. mConstraints = (ContactConstraint *)inContext->mTempAllocator->Allocate(mMaxConstraints * sizeof(ContactConstraint));
  515. }
  516. template <EMotionType Type1, EMotionType Type2>
  517. JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)
  518. {
  519. // Calculate scaled mass and inertia
  520. float inv_m1;
  521. Mat44 inv_i1;
  522. if constexpr (Type1 == EMotionType::Dynamic)
  523. {
  524. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  525. inv_m1 = inSettings.mInvMassScale1 * mp1->GetInverseMass();
  526. inv_i1 = inSettings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inTransformBody1.GetRotation());
  527. }
  528. else
  529. {
  530. inv_m1 = 0.0f;
  531. inv_i1 = Mat44::sZero();
  532. }
  533. float inv_m2;
  534. Mat44 inv_i2;
  535. if constexpr (Type2 == EMotionType::Dynamic)
  536. {
  537. const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();
  538. inv_m2 = inSettings.mInvMassScale2 * mp2->GetInverseMass();
  539. inv_i2 = inSettings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inTransformBody2.GetRotation());
  540. }
  541. else
  542. {
  543. inv_m2 = 0.0f;
  544. inv_i2 = Mat44::sZero();
  545. }
  546. // Calculate tangents
  547. Vec3 t1, t2;
  548. ioConstraint.GetTangents(t1, t2);
  549. // Get surface velocity relative to tangents
  550. float surface_velocity1 = t1.Dot(inSettings.mRelativeSurfaceVelocity);
  551. float surface_velocity2 = t2.Dot(inSettings.mRelativeSurfaceVelocity);
  552. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  553. // Setup velocity constraint properties
  554. float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;
  555. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  556. {
  557. RVec3 p1 = inTransformBody1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  558. RVec3 p2 = inTransformBody2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  559. wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(inDeltaTime, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1, p2, ws_normal, t1, t2, inSettings.mCombinedRestitution, inSettings.mCombinedFriction, min_velocity_for_restitution, surface_velocity1, surface_velocity2);
  560. }
  561. }
  562. inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)
  563. {
  564. // Dispatch to the correct templated form
  565. switch (inBody1.GetMotionType())
  566. {
  567. case EMotionType::Dynamic:
  568. switch (inBody2.GetMotionType())
  569. {
  570. case EMotionType::Dynamic:
  571. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  572. break;
  573. case EMotionType::Kinematic:
  574. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  575. break;
  576. case EMotionType::Static:
  577. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  578. break;
  579. default:
  580. JPH_ASSERT(false);
  581. break;
  582. }
  583. break;
  584. case EMotionType::Kinematic:
  585. JPH_ASSERT(inBody2.IsDynamic());
  586. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  587. break;
  588. case EMotionType::Static:
  589. JPH_ASSERT(inBody2.IsDynamic());
  590. TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);
  591. break;
  592. default:
  593. JPH_ASSERT(false);
  594. break;
  595. }
  596. }
  597. void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated)
  598. {
  599. JPH_PROFILE_FUNCTION();
  600. // Start with nothing found and not handled
  601. outConstraintCreated = false;
  602. outPairHandled = false;
  603. // Swap bodies so that body 1 id < body 2 id
  604. Body *body1, *body2;
  605. if (inBody1.GetID() < inBody2.GetID())
  606. {
  607. body1 = &inBody1;
  608. body2 = &inBody2;
  609. }
  610. else
  611. {
  612. body1 = &inBody2;
  613. body2 = &inBody1;
  614. }
  615. // Find the cached body pair
  616. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  617. uint64 body_pair_hash = body_pair_key.GetHash();
  618. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  619. const BPKeyValue *kv = read_cache.Find(body_pair_key, body_pair_hash);
  620. if (kv == nullptr)
  621. return;
  622. const CachedBodyPair &input_cbp = kv->GetValue();
  623. // Get relative translation
  624. Quat inv_r1 = body1->GetRotation().Conjugated();
  625. Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());
  626. // Get old position delta
  627. Vec3 old_delta_position = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaPosition);
  628. // Check if bodies are still roughly in the same relative position
  629. if ((delta_position - old_delta_position).LengthSq() > mPhysicsSettings.mBodyPairCacheMaxDeltaPositionSq)
  630. return;
  631. // Determine relative orientation
  632. Quat delta_rotation = inv_r1 * body2->GetRotation();
  633. // Reconstruct old quaternion delta
  634. Quat old_delta_rotation = Quat::sLoadFloat3Unsafe(input_cbp.mDeltaRotation);
  635. // Check if bodies are still roughly in the same relative orientation
  636. // The delta between 2 quaternions p and q is: p q^* = [rotation_axis * sin(angle / 2), cos(angle / 2)]
  637. // From the W component we can extract the angle: cos(angle / 2) = px * qx + py * qy + pz * qz + pw * qw = p . q
  638. // Since we want to abort if the rotation is smaller than -angle or bigger than angle, we can write the comparison as |p . q| < cos(angle / 2)
  639. if (abs(delta_rotation.Dot(old_delta_rotation)) < mPhysicsSettings.mBodyPairCacheCosMaxDeltaRotationDiv2)
  640. return;
  641. // The cache is valid, return that we've handled this body pair
  642. outPairHandled = true;
  643. // Copy the cached body pair to this frame
  644. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  645. BPKeyValue *output_bp_kv = write_cache.Create(ioContactAllocator, body_pair_key, body_pair_hash);
  646. if (output_bp_kv == nullptr)
  647. return; // Out of cache space
  648. CachedBodyPair *output_cbp = &output_bp_kv->GetValue();
  649. memcpy(output_cbp, &input_cbp, sizeof(CachedBodyPair));
  650. // If there were no contacts, we have handled the contact
  651. if (input_cbp.mFirstCachedManifold == ManifoldMap::cInvalidHandle)
  652. return;
  653. // Get body transforms
  654. RMat44 transform_body1 = body1->GetCenterOfMassTransform();
  655. RMat44 transform_body2 = body2->GetCenterOfMassTransform();
  656. // Get time step
  657. float delta_time = mUpdateContext->mStepDeltaTime;
  658. // Copy manifolds
  659. uint32 output_handle = ManifoldMap::cInvalidHandle;
  660. uint32 input_handle = input_cbp.mFirstCachedManifold;
  661. do
  662. {
  663. JPH_PROFILE("Add Constraint From Cached Manifold");
  664. // Find the existing manifold
  665. const MKeyValue *input_kv = read_cache.FromHandle(input_handle);
  666. const SubShapeIDPair &input_key = input_kv->GetKey();
  667. const CachedManifold &input_cm = input_kv->GetValue();
  668. JPH_ASSERT(input_cm.mNumContactPoints > 0); // There should be contact points in this manifold!
  669. // Create room for manifold in write buffer and copy data
  670. uint64 input_hash = input_key.GetHash();
  671. MKeyValue *output_kv = write_cache.Create(ioContactAllocator, input_key, input_hash, input_cm.mNumContactPoints);
  672. if (output_kv == nullptr)
  673. break; // Out of cache space
  674. CachedManifold *output_cm = &output_kv->GetValue();
  675. memcpy(output_cm, &input_cm, CachedManifold::sGetRequiredTotalSize(input_cm.mNumContactPoints));
  676. // Link the object under the body pairs
  677. output_cm->mNextWithSameBodyPair = output_handle;
  678. output_handle = write_cache.ToHandle(output_kv);
  679. // Calculate default contact settings
  680. ContactSettings settings;
  681. settings.mCombinedFriction = mCombineFriction(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());
  682. settings.mCombinedRestitution = mCombineRestitution(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());
  683. settings.mIsSensor = body1->IsSensor() || body2->IsSensor();
  684. // Calculate world space contact normal
  685. Vec3 world_space_normal = transform_body2.Multiply3x3(Vec3::sLoadFloat3Unsafe(output_cm->mContactNormal)).Normalized();
  686. // Call contact listener to update settings
  687. if (mContactListener != nullptr)
  688. {
  689. // Convert constraint to manifold structure for callback
  690. ContactManifold manifold;
  691. manifold.mWorldSpaceNormal = world_space_normal;
  692. manifold.mSubShapeID1 = input_key.GetSubShapeID1();
  693. manifold.mSubShapeID2 = input_key.GetSubShapeID2();
  694. manifold.mBaseOffset = transform_body1.GetTranslation();
  695. manifold.mRelativeContactPointsOn1.resize(output_cm->mNumContactPoints);
  696. manifold.mRelativeContactPointsOn2.resize(output_cm->mNumContactPoints);
  697. Mat44 local_transform_body2 = transform_body2.PostTranslated(-manifold.mBaseOffset).ToMat44();
  698. float penetration_depth = -FLT_MAX;
  699. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  700. {
  701. const CachedContactPoint &ccp = output_cm->mContactPoints[i];
  702. manifold.mRelativeContactPointsOn1[i] = transform_body1.Multiply3x3(Vec3::sLoadFloat3Unsafe(ccp.mPosition1));
  703. manifold.mRelativeContactPointsOn2[i] = local_transform_body2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2);
  704. penetration_depth = max(penetration_depth, (manifold.mRelativeContactPointsOn1[0] - manifold.mRelativeContactPointsOn2[0]).Dot(world_space_normal));
  705. }
  706. manifold.mPenetrationDepth = penetration_depth; // We don't have the penetration depth anymore, estimate it
  707. // Notify callback
  708. mContactListener->OnContactPersisted(*body1, *body2, manifold, settings);
  709. }
  710. JPH_ASSERT(settings.mIsSensor || !(body1->IsSensor() || body2->IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");
  711. if (!settings.mIsSensor // If one of the bodies is a sensor, don't actually create the constraint
  712. && ((body1->IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint
  713. || (body2->IsDynamic() && settings.mInvMassScale2 != 0.0f)))
  714. {
  715. // Add contact constraint in world space for the solver
  716. uint32 constraint_idx = mNumConstraints++;
  717. if (constraint_idx >= mMaxConstraints)
  718. {
  719. ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;
  720. break;
  721. }
  722. // A constraint will be created
  723. outConstraintCreated = true;
  724. ContactConstraint &constraint = mConstraints[constraint_idx];
  725. new (&constraint) ContactConstraint();
  726. constraint.mBody1 = body1;
  727. constraint.mBody2 = body2;
  728. constraint.mSortKey = input_hash;
  729. world_space_normal.StoreFloat3(&constraint.mWorldSpaceNormal);
  730. constraint.mCombinedFriction = settings.mCombinedFriction;
  731. constraint.mContactPoints.resize(output_cm->mNumContactPoints);
  732. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  733. {
  734. CachedContactPoint &ccp = output_cm->mContactPoints[i];
  735. WorldContactPoint &wcp = constraint.mContactPoints[i];
  736. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);
  737. wcp.mFrictionConstraint1.SetTotalLambda(ccp.mFrictionLambda[0]);
  738. wcp.mFrictionConstraint2.SetTotalLambda(ccp.mFrictionLambda[1]);
  739. wcp.mContactPoint = &ccp;
  740. }
  741. JPH_DET_LOG("GetContactsFromCache: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);
  742. // Calculate friction and non-penetration constraint properties for all contact points
  743. CalculateFrictionAndNonPenetrationConstraintProperties(constraint, settings, delta_time, transform_body1, transform_body2, *body1, *body2);
  744. // Notify island builder
  745. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  746. #ifdef JPH_DEBUG_RENDERER
  747. // Draw the manifold
  748. if (sDrawContactManifolds)
  749. constraint.Draw(DebugRenderer::sInstance, Color::sYellow);
  750. #endif // JPH_DEBUG_RENDERER
  751. }
  752. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  753. input_cm.mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  754. // Fetch the next manifold
  755. input_handle = input_cm.mNextWithSameBodyPair;
  756. }
  757. while (input_handle != ManifoldMap::cInvalidHandle);
  758. output_cbp->mFirstCachedManifold = output_handle;
  759. }
  760. ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2)
  761. {
  762. JPH_PROFILE_FUNCTION();
  763. // Swap bodies so that body 1 id < body 2 id
  764. const Body *body1, *body2;
  765. if (inBody1.GetID() < inBody2.GetID())
  766. {
  767. body1 = &inBody1;
  768. body2 = &inBody2;
  769. }
  770. else
  771. {
  772. body1 = &inBody2;
  773. body2 = &inBody1;
  774. }
  775. // Add an entry
  776. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  777. uint64 body_pair_hash = body_pair_key.GetHash();
  778. BPKeyValue *body_pair_kv = mCache[mCacheWriteIdx].Create(ioContactAllocator, body_pair_key, body_pair_hash);
  779. if (body_pair_kv == nullptr)
  780. return nullptr; // Out of cache space
  781. CachedBodyPair *cbp = &body_pair_kv->GetValue();
  782. cbp->mFirstCachedManifold = ManifoldMap::cInvalidHandle;
  783. // Get relative translation
  784. Quat inv_r1 = body1->GetRotation().Conjugated();
  785. Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());
  786. // Store it
  787. delta_position.StoreFloat3(&cbp->mDeltaPosition);
  788. // Determine relative orientation
  789. Quat delta_rotation = inv_r1 * body2->GetRotation();
  790. // Store it
  791. delta_rotation.StoreFloat3(&cbp->mDeltaRotation);
  792. return cbp;
  793. }
  794. template <EMotionType Type1, EMotionType Type2>
  795. bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)
  796. {
  797. // Calculate hash
  798. SubShapeIDPair key { inBody1.GetID(), inManifold.mSubShapeID1, inBody2.GetID(), inManifold.mSubShapeID2 };
  799. uint64 key_hash = key.GetHash();
  800. // Determine number of contact points
  801. int num_contact_points = (int)inManifold.mRelativeContactPointsOn1.size();
  802. JPH_ASSERT(num_contact_points <= MaxContactPoints);
  803. JPH_ASSERT(num_contact_points == (int)inManifold.mRelativeContactPointsOn2.size());
  804. // Reserve space for new contact cache entry
  805. // Note that for dynamic vs dynamic we always require the first body to have a lower body id to get a consistent key
  806. // under which to look up the contact
  807. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  808. MKeyValue *new_manifold_kv = write_cache.Create(ioContactAllocator, key, key_hash, num_contact_points);
  809. if (new_manifold_kv == nullptr)
  810. return false; // Out of cache space
  811. CachedManifold *new_manifold = &new_manifold_kv->GetValue();
  812. // Transform the world space normal to the space of body 2 (this is usually the static body)
  813. RMat44 inverse_transform_body2 = inBody2.GetInverseCenterOfMassTransform();
  814. inverse_transform_body2.Multiply3x3(inManifold.mWorldSpaceNormal).Normalized().StoreFloat3(&new_manifold->mContactNormal);
  815. // Settings object that gets passed to the callback
  816. ContactSettings settings;
  817. settings.mCombinedFriction = mCombineFriction(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  818. settings.mCombinedRestitution = mCombineRestitution(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  819. settings.mIsSensor = inBody1.IsSensor() || inBody2.IsSensor();
  820. // Get the contact points for the old cache entry
  821. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  822. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  823. const CachedContactPoint *ccp_start;
  824. const CachedContactPoint *ccp_end;
  825. if (old_manifold_kv != nullptr)
  826. {
  827. // Call point persisted listener
  828. if (mContactListener != nullptr)
  829. mContactListener->OnContactPersisted(inBody1, inBody2, inManifold, settings);
  830. // Fetch the contact points from the old manifold
  831. const CachedManifold *old_manifold = &old_manifold_kv->GetValue();
  832. ccp_start = old_manifold->mContactPoints;
  833. ccp_end = ccp_start + old_manifold->mNumContactPoints;
  834. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  835. old_manifold->mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  836. }
  837. else
  838. {
  839. // Call point added listener
  840. if (mContactListener != nullptr)
  841. mContactListener->OnContactAdded(inBody1, inBody2, inManifold, settings);
  842. // No contact points available from old manifold
  843. ccp_start = nullptr;
  844. ccp_end = nullptr;
  845. }
  846. // Get inverse transform for body 1
  847. RMat44 inverse_transform_body1 = inBody1.GetInverseCenterOfMassTransform();
  848. bool contact_constraint_created = false;
  849. // If one of the bodies is a sensor, don't actually create the constraint
  850. JPH_ASSERT(settings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");
  851. if (settings.mIsSensor)
  852. {
  853. // Store the contact manifold in the cache
  854. for (int i = 0; i < num_contact_points; ++i)
  855. {
  856. // Convert to local space to the body
  857. Vec3 p1 = Vec3(inverse_transform_body1 * (inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn1[i]));
  858. Vec3 p2 = Vec3(inverse_transform_body2 * (inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn2[i]));
  859. // Create new contact point
  860. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  861. p1.StoreFloat3(&cp.mPosition1);
  862. p2.StoreFloat3(&cp.mPosition2);
  863. // We don't use this, but reset them anyway for determinism check
  864. cp.mNonPenetrationLambda = 0.0f;
  865. cp.mFrictionLambda[0] = 0.0f;
  866. cp.mFrictionLambda[1] = 0.0f;
  867. }
  868. }
  869. else if ((inBody1.IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint
  870. || (inBody2.IsDynamic() && settings.mInvMassScale2 != 0.0f))
  871. {
  872. // Add contact constraint
  873. uint32 constraint_idx = mNumConstraints++;
  874. if (constraint_idx >= mMaxConstraints)
  875. {
  876. ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;
  877. // Manifold has been created already, we're not filling it in, so we need to reset the contact number of points.
  878. // Note that we don't hook it up to the body pair cache so that it won't be used as a cache during the next simulation.
  879. new_manifold->mNumContactPoints = 0;
  880. return false;
  881. }
  882. // We will create a contact constraint
  883. contact_constraint_created = true;
  884. ContactConstraint &constraint = mConstraints[constraint_idx];
  885. new (&constraint) ContactConstraint();
  886. constraint.mBody1 = &inBody1;
  887. constraint.mBody2 = &inBody2;
  888. constraint.mSortKey = key_hash;
  889. inManifold.mWorldSpaceNormal.StoreFloat3(&constraint.mWorldSpaceNormal);
  890. constraint.mCombinedFriction = settings.mCombinedFriction;
  891. JPH_DET_LOG("TemplatedAddContactConstraint: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);
  892. // Notify island builder
  893. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody1.GetIndexInActiveBodiesInternal(), inBody2.GetIndexInActiveBodiesInternal());
  894. // Get time step
  895. float delta_time = mUpdateContext->mStepDeltaTime;
  896. // Calculate scaled mass and inertia
  897. float inv_m1;
  898. Mat44 inv_i1;
  899. if constexpr (Type1 == EMotionType::Dynamic)
  900. {
  901. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  902. inv_m1 = settings.mInvMassScale1 * mp1->GetInverseMass();
  903. inv_i1 = settings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inverse_transform_body1.Transposed3x3());
  904. }
  905. else
  906. {
  907. inv_m1 = 0.0f;
  908. inv_i1 = Mat44::sZero();
  909. }
  910. float inv_m2;
  911. Mat44 inv_i2;
  912. if constexpr (Type2 == EMotionType::Dynamic)
  913. {
  914. const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();
  915. inv_m2 = settings.mInvMassScale2 * mp2->GetInverseMass();
  916. inv_i2 = settings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inverse_transform_body2.Transposed3x3());
  917. }
  918. else
  919. {
  920. inv_m2 = 0.0f;
  921. inv_i2 = Mat44::sZero();
  922. }
  923. // Calculate tangents
  924. Vec3 t1, t2;
  925. constraint.GetTangents(t1, t2);
  926. // Get surface velocity relative to tangents
  927. float surface_velocity1 = t1.Dot(settings.mRelativeSurfaceVelocity);
  928. float surface_velocity2 = t2.Dot(settings.mRelativeSurfaceVelocity);
  929. constraint.mContactPoints.resize(num_contact_points);
  930. for (int i = 0; i < num_contact_points; ++i)
  931. {
  932. // Convert to world space and set positions
  933. WorldContactPoint &wcp = constraint.mContactPoints[i];
  934. RVec3 p1_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn1[i];
  935. RVec3 p2_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn2[i];
  936. // Convert to local space to the body
  937. Vec3 p1_ls = Vec3(inverse_transform_body1 * p1_ws);
  938. Vec3 p2_ls = Vec3(inverse_transform_body2 * p2_ws);
  939. // Check if we have a close contact point from last update
  940. bool lambda_set = false;
  941. for (const CachedContactPoint *ccp = ccp_start; ccp < ccp_end; ccp++)
  942. if (Vec3::sLoadFloat3Unsafe(ccp->mPosition1).IsClose(p1_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq)
  943. && Vec3::sLoadFloat3Unsafe(ccp->mPosition2).IsClose(p2_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq))
  944. {
  945. // Get lambdas from previous frame
  946. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp->mNonPenetrationLambda);
  947. wcp.mFrictionConstraint1.SetTotalLambda(ccp->mFrictionLambda[0]);
  948. wcp.mFrictionConstraint2.SetTotalLambda(ccp->mFrictionLambda[1]);
  949. lambda_set = true;
  950. break;
  951. }
  952. if (!lambda_set)
  953. {
  954. wcp.mNonPenetrationConstraint.SetTotalLambda(0.0f);
  955. wcp.mFrictionConstraint1.SetTotalLambda(0.0f);
  956. wcp.mFrictionConstraint2.SetTotalLambda(0.0f);
  957. }
  958. // Create new contact point
  959. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  960. p1_ls.StoreFloat3(&cp.mPosition1);
  961. p2_ls.StoreFloat3(&cp.mPosition2);
  962. wcp.mContactPoint = &cp;
  963. // Setup velocity constraint
  964. wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(delta_time, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, t1, t2, settings.mCombinedRestitution, settings.mCombinedFriction, mPhysicsSettings.mMinVelocityForRestitution, surface_velocity1, surface_velocity2);
  965. }
  966. #ifdef JPH_DEBUG_RENDERER
  967. // Draw the manifold
  968. if (sDrawContactManifolds)
  969. constraint.Draw(DebugRenderer::sInstance, Color::sOrange);
  970. #endif // JPH_DEBUG_RENDERER
  971. }
  972. // Store cached contact point in body pair cache
  973. CachedBodyPair *cbp = reinterpret_cast<CachedBodyPair *>(inBodyPairHandle);
  974. new_manifold->mNextWithSameBodyPair = cbp->mFirstCachedManifold;
  975. cbp->mFirstCachedManifold = write_cache.ToHandle(new_manifold_kv);
  976. // A contact constraint was added
  977. return contact_constraint_created;
  978. }
  979. bool ContactConstraintManager::AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)
  980. {
  981. JPH_PROFILE_FUNCTION();
  982. JPH_DET_LOG("AddContactConstraint: id1: " << inBody1.GetID() << " id2: " << inBody2.GetID()
  983. << " subshape1: " << inManifold.mSubShapeID1 << " subshape2: " << inManifold.mSubShapeID2
  984. << " normal: " << inManifold.mWorldSpaceNormal << " pendepth: " << inManifold.mPenetrationDepth);
  985. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  986. // Swap bodies so that body 1 id < body 2 id
  987. const ContactManifold *manifold;
  988. Body *body1, *body2;
  989. ContactManifold temp;
  990. if (inBody2.GetID() < inBody1.GetID())
  991. {
  992. body1 = &inBody2;
  993. body2 = &inBody1;
  994. temp = inManifold.SwapShapes();
  995. manifold = &temp;
  996. }
  997. else
  998. {
  999. body1 = &inBody1;
  1000. body2 = &inBody2;
  1001. manifold = &inManifold;
  1002. }
  1003. // Dispatch to the correct templated form
  1004. // Note: Non-dynamic vs non-dynamic can happen in this case due to one body being a sensor, so we need to have an extended switch case here
  1005. switch (body1->GetMotionType())
  1006. {
  1007. case EMotionType::Dynamic:
  1008. {
  1009. switch (body2->GetMotionType())
  1010. {
  1011. case EMotionType::Dynamic:
  1012. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1013. case EMotionType::Kinematic:
  1014. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1015. case EMotionType::Static:
  1016. return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1017. default:
  1018. JPH_ASSERT(false);
  1019. break;
  1020. }
  1021. break;
  1022. }
  1023. case EMotionType::Kinematic:
  1024. switch (body2->GetMotionType())
  1025. {
  1026. case EMotionType::Dynamic:
  1027. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1028. case EMotionType::Kinematic:
  1029. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1030. case EMotionType::Static:
  1031. return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1032. default:
  1033. JPH_ASSERT(false);
  1034. break;
  1035. }
  1036. break;
  1037. case EMotionType::Static:
  1038. switch (body2->GetMotionType())
  1039. {
  1040. case EMotionType::Dynamic:
  1041. return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1042. case EMotionType::Kinematic:
  1043. return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);
  1044. case EMotionType::Static: // Static vs static not possible
  1045. default:
  1046. JPH_ASSERT(false);
  1047. break;
  1048. }
  1049. break;
  1050. default:
  1051. JPH_ASSERT(false);
  1052. break;
  1053. }
  1054. return false;
  1055. }
  1056. void ContactConstraintManager::OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings)
  1057. {
  1058. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  1059. // Calculate contact settings
  1060. outSettings.mCombinedFriction = mCombineFriction(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  1061. outSettings.mCombinedRestitution = mCombineRestitution(inBody1, inManifold.mSubShapeID1, inBody2, inManifold.mSubShapeID2);
  1062. outSettings.mIsSensor = false; // For now, no sensors are supported during CCD
  1063. // The remainder of this function only deals with calling contact callbacks, if there's no contact callback we also don't need to do this work
  1064. if (mContactListener != nullptr)
  1065. {
  1066. // Swap bodies so that body 1 id < body 2 id
  1067. const ContactManifold *manifold;
  1068. const Body *body1, *body2;
  1069. ContactManifold temp;
  1070. if (inBody2.GetID() < inBody1.GetID())
  1071. {
  1072. body1 = &inBody2;
  1073. body2 = &inBody1;
  1074. temp = inManifold.SwapShapes();
  1075. manifold = &temp;
  1076. }
  1077. else
  1078. {
  1079. body1 = &inBody1;
  1080. body2 = &inBody2;
  1081. manifold = &inManifold;
  1082. }
  1083. // Calculate hash
  1084. SubShapeIDPair key { body1->GetID(), manifold->mSubShapeID1, body2->GetID(), manifold->mSubShapeID2 };
  1085. uint64 key_hash = key.GetHash();
  1086. // Check if we already created this contact this physics update
  1087. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  1088. MKVAndCreated new_manifold_kv = write_cache.FindOrCreate(ioContactAllocator, key, key_hash, 0);
  1089. if (new_manifold_kv.second)
  1090. {
  1091. // This contact is new for this physics update, check if previous update we already had this contact.
  1092. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  1093. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  1094. if (old_manifold_kv == nullptr)
  1095. {
  1096. // New contact
  1097. mContactListener->OnContactAdded(*body1, *body2, *manifold, outSettings);
  1098. }
  1099. else
  1100. {
  1101. // Existing contact
  1102. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  1103. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  1104. old_manifold_kv->GetValue().mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  1105. }
  1106. // Check if the cache is full
  1107. if (new_manifold_kv.first != nullptr)
  1108. {
  1109. // We don't store any contact points in this manifold as it is not for caching impulses, we only need to know that the contact was created
  1110. CachedManifold &new_manifold = new_manifold_kv.first->GetValue();
  1111. new_manifold.mContactNormal = { 0, 0, 0 };
  1112. new_manifold.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  1113. }
  1114. }
  1115. else
  1116. {
  1117. // Already found this contact this physics update.
  1118. // Note that we can trigger OnContactPersisted multiple times per physics update, but otherwise we have no way of obtaining the settings
  1119. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  1120. }
  1121. }
  1122. JPH_ASSERT(!outSettings.mIsSensor, "CCD bodies cannot currently act as sensors");
  1123. }
  1124. void ContactConstraintManager::SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const
  1125. {
  1126. JPH_PROFILE_FUNCTION();
  1127. QuickSort(inConstraintIdxBegin, inConstraintIdxEnd, [this](uint32 inLHS, uint32 inRHS) {
  1128. const ContactConstraint &lhs = mConstraints[inLHS];
  1129. const ContactConstraint &rhs = mConstraints[inRHS];
  1130. // Most of the time the sort key will be different so we sort on that
  1131. if (lhs.mSortKey != rhs.mSortKey)
  1132. return lhs.mSortKey < rhs.mSortKey;
  1133. // If they're equal we use the IDs of body 1 to order
  1134. if (lhs.mBody1 != rhs.mBody1)
  1135. return lhs.mBody1->GetID() < rhs.mBody1->GetID();
  1136. // If they're still equal we use the IDs of body 2 to order
  1137. if (lhs.mBody2 != rhs.mBody2)
  1138. return lhs.mBody2->GetID() < rhs.mBody2->GetID();
  1139. JPH_ASSERT(inLHS == inRHS, "Hash collision, ordering will be inconsistent");
  1140. return false;
  1141. });
  1142. }
  1143. void ContactConstraintManager::FinalizeContactCacheAndCallContactPointRemovedCallbacks(uint inExpectedNumBodyPairs, uint inExpectedNumManifolds)
  1144. {
  1145. JPH_PROFILE_FUNCTION();
  1146. #ifdef JPH_ENABLE_ASSERTS
  1147. // Mark cache as finalized
  1148. ManifoldCache &old_write_cache = mCache[mCacheWriteIdx];
  1149. old_write_cache.Finalize();
  1150. // Check that the count of body pairs and manifolds that we tracked outside of the cache (to avoid contention on an atomic) is correct
  1151. JPH_ASSERT(old_write_cache.GetNumBodyPairs() == inExpectedNumBodyPairs);
  1152. JPH_ASSERT(old_write_cache.GetNumManifolds() == inExpectedNumManifolds);
  1153. #endif
  1154. // Buffers are now complete, make write buffer the read buffer
  1155. mCacheWriteIdx ^= 1;
  1156. // Get the old read cache / new write cache
  1157. ManifoldCache &old_read_cache = mCache[mCacheWriteIdx];
  1158. // Call the contact point removal callbacks
  1159. if (mContactListener != nullptr)
  1160. old_read_cache.ContactPointRemovedCallbacks(mContactListener);
  1161. // We're done with the old read cache now
  1162. old_read_cache.Clear();
  1163. // Use the amount of contacts from the last iteration to determine the amount of buckets to use in the hash map for the next iteration
  1164. old_read_cache.Prepare(inExpectedNumBodyPairs, inExpectedNumManifolds);
  1165. }
  1166. bool ContactConstraintManager::WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const
  1167. {
  1168. // The body pair needs to be in the cache and it needs to have a manifold (otherwise it's just a record indicating that there are no collisions)
  1169. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  1170. BodyPair key;
  1171. if (inBody1ID < inBody2ID)
  1172. key = BodyPair(inBody1ID, inBody2ID);
  1173. else
  1174. key = BodyPair(inBody2ID, inBody1ID);
  1175. uint64 key_hash = key.GetHash();
  1176. const BPKeyValue *kv = read_cache.Find(key, key_hash);
  1177. return kv != nullptr && kv->GetValue().mFirstCachedManifold != ManifoldMap::cInvalidHandle;
  1178. }
  1179. template <EMotionType Type1, EMotionType Type2>
  1180. JPH_INLINE void ContactConstraintManager::sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio)
  1181. {
  1182. // Calculate tangents
  1183. Vec3 t1, t2;
  1184. ioConstraint.GetTangents(t1, t2);
  1185. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  1186. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1187. {
  1188. // Warm starting: Apply impulse from last frame
  1189. if (wcp.mFrictionConstraint1.IsActive())
  1190. {
  1191. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1192. wcp.mFrictionConstraint1.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1, inWarmStartImpulseRatio);
  1193. wcp.mFrictionConstraint2.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2, inWarmStartImpulseRatio);
  1194. }
  1195. wcp.mNonPenetrationConstraint.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, ws_normal, inWarmStartImpulseRatio);
  1196. }
  1197. }
  1198. void ContactConstraintManager::WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio)
  1199. {
  1200. JPH_PROFILE_FUNCTION();
  1201. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1202. {
  1203. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1204. // Fetch bodies
  1205. Body &body1 = *constraint.mBody1;
  1206. EMotionType motion_type1 = body1.GetMotionType();
  1207. MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();
  1208. Body &body2 = *constraint.mBody2;
  1209. EMotionType motion_type2 = body2.GetMotionType();
  1210. MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();
  1211. // Dispatch to the correct templated form
  1212. // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies
  1213. if (motion_type1 == EMotionType::Dynamic)
  1214. {
  1215. if (motion_type2 == EMotionType::Dynamic)
  1216. sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1217. else
  1218. sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1219. }
  1220. else
  1221. {
  1222. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1223. sWarmStartConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);
  1224. }
  1225. }
  1226. }
  1227. template <EMotionType Type1, EMotionType Type2>
  1228. JPH_INLINE bool ContactConstraintManager::sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2)
  1229. {
  1230. bool any_impulse_applied = false;
  1231. // Calculate tangents
  1232. Vec3 t1, t2;
  1233. ioConstraint.GetTangents(t1, t2);
  1234. // First apply all friction constraints (non-penetration is more important than friction)
  1235. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1236. {
  1237. // Check if friction is enabled
  1238. if (wcp.mFrictionConstraint1.IsActive())
  1239. {
  1240. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1241. // Calculate impulse to stop motion in tangential direction
  1242. float lambda1 = wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1);
  1243. float lambda2 = wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2);
  1244. float total_lambda_sq = Square(lambda1) + Square(lambda2);
  1245. // Calculate max impulse that can be applied. Note that we're using the non-penetration impulse from the previous iteration here.
  1246. // We do this because non-penetration is more important so is solved last (the last things that are solved in an iterative solver
  1247. // contribute the most).
  1248. float max_lambda_f = ioConstraint.mCombinedFriction * wcp.mNonPenetrationConstraint.GetTotalLambda();
  1249. // If the total lambda that we will apply is too large, scale it back
  1250. if (total_lambda_sq > Square(max_lambda_f))
  1251. {
  1252. float scale = max_lambda_f / sqrt(total_lambda_sq);
  1253. lambda1 *= scale;
  1254. lambda2 *= scale;
  1255. }
  1256. // Apply the friction impulse
  1257. if (wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1, lambda1))
  1258. any_impulse_applied = true;
  1259. if (wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2, lambda2))
  1260. any_impulse_applied = true;
  1261. }
  1262. }
  1263. Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();
  1264. // Then apply all non-penetration constraints
  1265. for (WorldContactPoint &wcp : ioConstraint.mContactPoints)
  1266. {
  1267. // Solve non penetration velocities
  1268. if (wcp.mNonPenetrationConstraint.TemplatedSolveVelocityConstraint<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, ws_normal, 0.0f, FLT_MAX))
  1269. any_impulse_applied = true;
  1270. }
  1271. return any_impulse_applied;
  1272. }
  1273. bool ContactConstraintManager::SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1274. {
  1275. JPH_PROFILE_FUNCTION();
  1276. bool any_impulse_applied = false;
  1277. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1278. {
  1279. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1280. // Fetch bodies
  1281. Body &body1 = *constraint.mBody1;
  1282. EMotionType motion_type1 = body1.GetMotionType();
  1283. MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();
  1284. Body &body2 = *constraint.mBody2;
  1285. EMotionType motion_type2 = body2.GetMotionType();
  1286. MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();
  1287. // Dispatch to the correct templated form
  1288. switch (motion_type1)
  1289. {
  1290. case EMotionType::Dynamic:
  1291. switch (motion_type2)
  1292. {
  1293. case EMotionType::Dynamic:
  1294. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1295. break;
  1296. case EMotionType::Kinematic:
  1297. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(constraint, motion_properties1, motion_properties2);
  1298. break;
  1299. case EMotionType::Static:
  1300. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2);
  1301. break;
  1302. default:
  1303. JPH_ASSERT(false);
  1304. break;
  1305. }
  1306. break;
  1307. case EMotionType::Kinematic:
  1308. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1309. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1310. break;
  1311. case EMotionType::Static:
  1312. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  1313. any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);
  1314. break;
  1315. default:
  1316. JPH_ASSERT(false);
  1317. break;
  1318. }
  1319. }
  1320. return any_impulse_applied;
  1321. }
  1322. void ContactConstraintManager::StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const
  1323. {
  1324. // Copy back total applied impulse to cache for the next frame
  1325. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1326. {
  1327. const ContactConstraint &constraint = mConstraints[*constraint_idx];
  1328. for (const WorldContactPoint &wcp : constraint.mContactPoints)
  1329. {
  1330. wcp.mContactPoint->mNonPenetrationLambda = wcp.mNonPenetrationConstraint.GetTotalLambda();
  1331. wcp.mContactPoint->mFrictionLambda[0] = wcp.mFrictionConstraint1.GetTotalLambda();
  1332. wcp.mContactPoint->mFrictionLambda[1] = wcp.mFrictionConstraint2.GetTotalLambda();
  1333. }
  1334. }
  1335. }
  1336. bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1337. {
  1338. JPH_PROFILE_FUNCTION();
  1339. bool any_impulse_applied = false;
  1340. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1341. {
  1342. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1343. // Fetch bodies
  1344. Body &body1 = *constraint.mBody1;
  1345. Body &body2 = *constraint.mBody2;
  1346. // Get transforms
  1347. RMat44 transform1 = body1.GetCenterOfMassTransform();
  1348. RMat44 transform2 = body2.GetCenterOfMassTransform();
  1349. Vec3 ws_normal = constraint.GetWorldSpaceNormal();
  1350. for (WorldContactPoint &wcp : constraint.mContactPoints)
  1351. {
  1352. // Calculate new contact point positions in world space (the bodies may have moved)
  1353. RVec3 p1 = transform1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  1354. RVec3 p2 = transform2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  1355. // Calculate separation along the normal (negative if interpenetrating)
  1356. // Allow a little penetration by default (PhysicsSettings::mPenetrationSlop) to avoid jittering between contact/no-contact which wipes out the contact cache and warm start impulses
  1357. // Clamp penetration to a max PhysicsSettings::mMaxPenetrationDistance so that we don't apply a huge impulse if we're penetrating a lot
  1358. float separation = max(Vec3(p2 - p1).Dot(ws_normal) + mPhysicsSettings.mPenetrationSlop, -mPhysicsSettings.mMaxPenetrationDistance);
  1359. // Only enforce constraint when separation < 0 (otherwise we're apart)
  1360. if (separation < 0.0f)
  1361. {
  1362. // Update constraint properties (bodies may have moved)
  1363. wcp.CalculateNonPenetrationConstraintProperties(body1, body2, p1, p2, ws_normal);
  1364. // Solve position errors
  1365. if (wcp.mNonPenetrationConstraint.SolvePositionConstraint(body1, body2, ws_normal, separation, mPhysicsSettings.mBaumgarte))
  1366. any_impulse_applied = true;
  1367. }
  1368. }
  1369. }
  1370. return any_impulse_applied;
  1371. }
  1372. void ContactConstraintManager::RecycleConstraintBuffer()
  1373. {
  1374. // Reset constraint array
  1375. mNumConstraints = 0;
  1376. }
  1377. void ContactConstraintManager::FinishConstraintBuffer()
  1378. {
  1379. // Free constraints buffer
  1380. mUpdateContext->mTempAllocator->Free(mConstraints, mMaxConstraints * sizeof(ContactConstraint));
  1381. mConstraints = nullptr;
  1382. mNumConstraints = 0;
  1383. // Reset update context
  1384. mUpdateContext = nullptr;
  1385. }
  1386. void ContactConstraintManager::SaveState(StateRecorder &inStream) const
  1387. {
  1388. mCache[mCacheWriteIdx ^ 1].SaveState(inStream);
  1389. }
  1390. bool ContactConstraintManager::RestoreState(StateRecorder &inStream)
  1391. {
  1392. bool success = mCache[mCacheWriteIdx].RestoreState(mCache[mCacheWriteIdx ^ 1], inStream);
  1393. mCacheWriteIdx ^= 1;
  1394. mCache[mCacheWriteIdx].Clear();
  1395. return success;
  1396. }
  1397. JPH_NAMESPACE_END