ContactConstraintManager.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/Constraints/ContactConstraintManager.h>
  5. #include <Physics/Body/Body.h>
  6. #include <Physics/PhysicsUpdateContext.h>
  7. #include <Physics/PhysicsSettings.h>
  8. #include <Physics/IslandBuilder.h>
  9. #include <Core/TempAllocator.h>
  10. #ifdef JPH_DEBUG_RENDERER
  11. #include <Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. namespace JPH {
  14. #ifdef JPH_DEBUG_RENDERER
  15. bool ContactConstraintManager::sDrawContactPoint = false;
  16. bool ContactConstraintManager::sDrawSupportingFaces = false;
  17. bool ContactConstraintManager::sDrawContactPointReduction = false;
  18. bool ContactConstraintManager::sDrawContactManifolds = false;
  19. #endif // JPH_DEBUG_RENDERER
  20. //#define JPH_MANIFOLD_CACHE_DEBUG
  21. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  22. // ContactConstraintManager::WorldContactPoint
  23. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  24. void ContactConstraintManager::WorldContactPoint::CalculateNonPenetrationConstraintProperties(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpacePosition1, Vec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal)
  25. {
  26. // Calculate collision points relative to body
  27. Vec3 p = 0.5f * (inWorldSpacePosition1 + inWorldSpacePosition2);
  28. Vec3 r1 = p - inBody1.GetCenterOfMassPosition();
  29. Vec3 r2 = p - inBody2.GetCenterOfMassPosition();
  30. mNonPenetrationConstraint.CalculateConstraintProperties(inDeltaTime, inBody1, r1, inBody2, r2, inWorldSpaceNormal);
  31. }
  32. void ContactConstraintManager::WorldContactPoint::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)
  33. {
  34. // Calculate collision points relative to body
  35. Vec3 p = 0.5f * (inWorldSpacePosition1 + inWorldSpacePosition2);
  36. Vec3 r1 = p - inBody1.GetCenterOfMassPosition();
  37. Vec3 r2 = p - inBody2.GetCenterOfMassPosition();
  38. // Calculate velocity of collision points
  39. Vec3 v1 = inBody1.GetLinearVelocity() + inBody1.GetAngularVelocity().Cross(r1);
  40. Vec3 v2 = inBody2.GetLinearVelocity() + inBody2.GetAngularVelocity().Cross(r2);
  41. Vec3 relative_velocity = v2 - v1;
  42. float normal_velocity = relative_velocity.Dot(inWorldSpaceNormal);
  43. // How much the shapes are penetrating (> 0 if penetrating, < 0 if separated)
  44. float penetration = (inWorldSpacePosition1 - inWorldSpacePosition2).Dot(inWorldSpaceNormal);
  45. // If there is no penetration, this is a speculative contact and we will apply a bias to the contact constraint
  46. // so that the constraint becomes relative_velocity . contact normal > -penetration / delta_time
  47. // instead of relative_velocity . contact normal > 0
  48. // See: GDC 2013: "Physics for Game Programmers; Continuous Collision" - Erin Catto
  49. float speculative_contact_velocity_bias = max(0.0f, -penetration / inDeltaTime);
  50. // Determine if the velocity is big enough for restitution
  51. float normal_velocity_bias;
  52. if (inCombinedRestitution > 0.0f && normal_velocity < -inMinVelocityForRestitution)
  53. {
  54. // We have a velocity that is big enough for restitution. This is where speculative contacts don't work
  55. // great as we have to decide now if we're going to apply the restitution or not. If the relative
  56. // velocity is big enough for a hit, we apply the restitution (in the end, due to other constraints,
  57. // the objects may actually not collide and we will have applied restitution incorrectly). Another
  58. // artifact that occurs because of this approximation is that the object will bounce from its current
  59. // position rather than from a position where it is touching the other object. This causes the object
  60. // to appear to move faster for 1 frame (the opposite of time stealing).
  61. if (normal_velocity < -speculative_contact_velocity_bias)
  62. normal_velocity_bias = inCombinedRestitution * normal_velocity;
  63. else
  64. normal_velocity_bias = 0.0f;
  65. }
  66. else
  67. {
  68. // No restitution. We can safely apply our contact velocity bias.
  69. normal_velocity_bias = speculative_contact_velocity_bias;
  70. }
  71. mNonPenetrationConstraint.CalculateConstraintProperties(inDeltaTime, inBody1, r1, inBody2, r2, inWorldSpaceNormal, normal_velocity_bias);
  72. // Calculate friction part
  73. if (inCombinedFriction > 0.0f)
  74. {
  75. // Implement friction as 2 AxisContraintParts
  76. mFrictionConstraint1.CalculateConstraintProperties(inDeltaTime, inBody1, r1, inBody2, r2, inWorldSpaceTangent1);
  77. mFrictionConstraint2.CalculateConstraintProperties(inDeltaTime, inBody1, r1, inBody2, r2, inWorldSpaceTangent2);
  78. }
  79. else
  80. {
  81. // Turn off friction constraint
  82. mFrictionConstraint1.Deactivate();
  83. mFrictionConstraint2.Deactivate();
  84. }
  85. }
  86. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  87. // ContactConstraintManager::ContactConstraint
  88. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  89. #ifdef JPH_DEBUG_RENDERER
  90. void ContactConstraintManager::ContactConstraint::Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const
  91. {
  92. if (mContactPoints.empty())
  93. return;
  94. // Get body transforms
  95. Mat44 transform_body1 = mBody1->GetCenterOfMassTransform();
  96. Mat44 transform_body2 = mBody2->GetCenterOfMassTransform();
  97. Vec3 prev_point = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints.back().mContactPoint->mPosition1);
  98. for (const WorldContactPoint &wcp : mContactPoints)
  99. {
  100. // Test if any lambda from the previous frame was transferred
  101. float radius = wcp.mNonPenetrationConstraint.GetTotalLambda() == 0.0f
  102. && wcp.mFrictionConstraint1.GetTotalLambda() == 0.0f
  103. && wcp.mFrictionConstraint2.GetTotalLambda() == 0.0f? 0.1f : 0.2f;
  104. Vec3 next_point = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  105. inRenderer->DrawMarker(next_point, Color::sCyan, radius);
  106. inRenderer->DrawMarker(transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2), Color::sPurple, radius);
  107. // Draw edge
  108. inRenderer->DrawArrow(prev_point, next_point, inManifoldColor, 0.05f);
  109. prev_point = next_point;
  110. }
  111. // Draw normal
  112. Vec3 wp = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints[0].mContactPoint->mPosition1);
  113. inRenderer->DrawArrow(wp, wp + mWorldSpaceNormal, Color::sRed, 0.05f);
  114. // Get tangents
  115. Vec3 t1, t2;
  116. GetTangents(t1, t2);
  117. // Draw tangents
  118. inRenderer->DrawLine(wp, wp + t1, Color::sGreen);
  119. inRenderer->DrawLine(wp, wp + t2, Color::sBlue);
  120. }
  121. #endif // JPH_DEBUG_RENDERER
  122. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  123. // ContactConstraintManager::CachedContactPoint
  124. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  125. void ContactConstraintManager::CachedContactPoint::SaveState(StateRecorder &inStream) const
  126. {
  127. inStream.Write(mPosition1);
  128. inStream.Write(mPosition2);
  129. inStream.Write(mNonPenetrationLambda);
  130. inStream.Write(mFrictionLambda);
  131. }
  132. void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &inStream)
  133. {
  134. inStream.Read(mPosition1);
  135. inStream.Read(mPosition2);
  136. inStream.Read(mNonPenetrationLambda);
  137. inStream.Read(mFrictionLambda);
  138. }
  139. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  140. // ContactConstraintManager::CachedManifold
  141. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  142. void ContactConstraintManager::CachedManifold::SaveState(StateRecorder &inStream) const
  143. {
  144. inStream.Write(mContactNormal);
  145. }
  146. void ContactConstraintManager::CachedManifold::RestoreState(StateRecorder &inStream)
  147. {
  148. inStream.Read(mContactNormal);
  149. }
  150. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  151. // ContactConstraintManager::CachedBodyPair
  152. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  153. void ContactConstraintManager::CachedBodyPair::SaveState(StateRecorder &inStream) const
  154. {
  155. inStream.Write(mDeltaPosition);
  156. inStream.Write(mDeltaRotation);
  157. }
  158. void ContactConstraintManager::CachedBodyPair::RestoreState(StateRecorder &inStream)
  159. {
  160. inStream.Read(mDeltaPosition);
  161. inStream.Read(mDeltaRotation);
  162. }
  163. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  164. // ContactConstraintManager::ManifoldCache
  165. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  166. void ContactConstraintManager::ManifoldCache::Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize)
  167. {
  168. mCachedManifolds.Init(inCachedManifoldsSize, GetNextPowerOf2(inMaxContactConstraints));
  169. mCachedBodyPairs.Init(inMaxBodyPairs * sizeof(BodyPairMap::KeyValue), GetNextPowerOf2(inMaxBodyPairs));
  170. }
  171. void ContactConstraintManager::ManifoldCache::Clear()
  172. {
  173. JPH_PROFILE_FUNCTION();
  174. mCachedManifolds.Clear();
  175. mCachedBodyPairs.Clear();
  176. #ifdef JPH_ENABLE_ASSERTS
  177. // Mark as incomplete
  178. mIsFinalized = false;
  179. #endif
  180. }
  181. void ContactConstraintManager::ManifoldCache::Prepare(const ManifoldCache &inReadCache)
  182. {
  183. JPH_ASSERT(this != &inReadCache);
  184. // Minimum amount of buckets to use in the hash map
  185. constexpr uint32 cMinBuckets = 1024;
  186. // 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
  187. mCachedManifolds.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inReadCache.mCachedManifolds.GetNumKeyValues())), mCachedManifolds.GetMaxBuckets()));
  188. mCachedBodyPairs.SetNumBuckets(min(max(cMinBuckets, GetNextPowerOf2(inReadCache.mCachedBodyPairs.GetNumKeyValues())), mCachedBodyPairs.GetMaxBuckets()));
  189. }
  190. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Find(const SubShapeIDPair &inKey, size_t inKeyHash) const
  191. {
  192. JPH_ASSERT(mIsFinalized);
  193. return mCachedManifolds.Find(inKey, inKeyHash);
  194. }
  195. ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::Create(const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints)
  196. {
  197. JPH_ASSERT(!mIsFinalized);
  198. MKeyValue *kv = mCachedManifolds.Create(inKey, inKeyHash, CachedManifold::sGetRequiredExtraSize(inNumContactPoints));
  199. if (kv == nullptr)
  200. {
  201. JPH_ASSERT(false, "Out of cache space for manifold cache");
  202. return nullptr;
  203. }
  204. kv->GetValue().mNumContactPoints = uint16(inNumContactPoints);
  205. return kv;
  206. }
  207. ContactConstraintManager::MKVAndCreated ContactConstraintManager::ManifoldCache::FindOrCreate(const SubShapeIDPair &inKey, size_t inKeyHash, int inNumContactPoints)
  208. {
  209. MKeyValue *kv = const_cast<MKeyValue *>(mCachedManifolds.Find(inKey, inKeyHash));
  210. if (kv != nullptr)
  211. return { kv, false };
  212. return { Create(inKey, inKeyHash, inNumContactPoints), true };
  213. }
  214. uint32 ContactConstraintManager::ManifoldCache::ToHandle(const MKeyValue *inKeyValue) const
  215. {
  216. JPH_ASSERT(!mIsFinalized);
  217. return mCachedManifolds.ToHandle(inKeyValue);
  218. }
  219. const ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::FromHandle(uint32 inHandle) const
  220. {
  221. JPH_ASSERT(mIsFinalized);
  222. return mCachedManifolds.FromHandle(inHandle);
  223. }
  224. const ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Find(const BodyPair &inKey, size_t inKeyHash) const
  225. {
  226. JPH_ASSERT(mIsFinalized);
  227. return mCachedBodyPairs.Find(inKey, inKeyHash);
  228. }
  229. ContactConstraintManager::BPKeyValue *ContactConstraintManager::ManifoldCache::Create(const BodyPair &inKey, size_t inKeyHash)
  230. {
  231. JPH_ASSERT(!mIsFinalized);
  232. BPKeyValue *kv = mCachedBodyPairs.Create(inKey, inKeyHash, 0);
  233. if (kv == nullptr)
  234. {
  235. JPH_ASSERT(false, "Out of cache space for body pair cache");
  236. return nullptr;
  237. }
  238. return kv;
  239. }
  240. void ContactConstraintManager::ManifoldCache::GetAllBodyPairsSorted(vector<const BPKeyValue *> &outAll) const
  241. {
  242. JPH_ASSERT(mIsFinalized);
  243. mCachedBodyPairs.GetAllKeyValues(outAll);
  244. // Sort by key
  245. sort(outAll.begin(), outAll.end(), [](const BPKeyValue *inLHS, const BPKeyValue *inRHS) {
  246. return inLHS->GetKey() < inRHS->GetKey();
  247. });
  248. }
  249. void ContactConstraintManager::ManifoldCache::GetAllManifoldsSorted(const CachedBodyPair &inBodyPair, vector<const MKeyValue *> &outAll) const
  250. {
  251. JPH_ASSERT(mIsFinalized);
  252. // Iterate through the attached manifolds
  253. for (uint32 handle = inBodyPair.mFirstCachedManifold; handle != ManifoldMap::cInvalidHandle; handle = FromHandle(handle)->GetValue().mNextWithSameBodyPair)
  254. {
  255. const MKeyValue *kv = mCachedManifolds.FromHandle(handle);
  256. outAll.push_back(kv);
  257. }
  258. // Sort by key
  259. sort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  260. return inLHS->GetKey() < inRHS->GetKey();
  261. });
  262. }
  263. void ContactConstraintManager::ManifoldCache::GetAllCCDManifoldsSorted(vector<const MKeyValue *> &outAll) const
  264. {
  265. mCachedManifolds.GetAllKeyValues(outAll);
  266. for (int i = (int)outAll.size() - 1; i >= 0; --i)
  267. if ((outAll[i]->GetValue().mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0)
  268. {
  269. outAll[i] = outAll.back();
  270. outAll.pop_back();
  271. }
  272. // Sort by key
  273. sort(outAll.begin(), outAll.end(), [](const MKeyValue *inLHS, const MKeyValue *inRHS) {
  274. return inLHS->GetKey() < inRHS->GetKey();
  275. });
  276. }
  277. void ContactConstraintManager::ManifoldCache::ContactPointRemovedCallbacks(ContactListener *inListener)
  278. {
  279. for (MKeyValue &kv : mCachedManifolds)
  280. if ((kv.GetValue().mFlags & uint16(CachedManifold::EFlags::ContactPersisted)) == 0)
  281. inListener->OnContactRemoved(kv.GetKey());
  282. }
  283. #ifdef JPH_ENABLE_ASSERTS
  284. void ContactConstraintManager::ManifoldCache::Finalize()
  285. {
  286. mIsFinalized = true;
  287. #ifdef JPH_MANIFOLD_CACHE_DEBUG
  288. Trace("ManifoldMap:");
  289. mCachedManifolds.TraceStats();
  290. Trace("BodyPairMap:");
  291. mCachedBodyPairs.TraceStats();
  292. #endif // JPH_MANIFOLD_CACHE_DEBUG
  293. }
  294. #endif
  295. void ContactConstraintManager::ManifoldCache::SaveState(StateRecorder &inStream) const
  296. {
  297. JPH_ASSERT(mIsFinalized);
  298. // Get contents of cache
  299. vector<const BPKeyValue *> all_bp;
  300. GetAllBodyPairsSorted(all_bp);
  301. // Write amount of body pairs
  302. size_t num_body_pairs = all_bp.size();
  303. inStream.Write(num_body_pairs);
  304. // Write all body pairs
  305. for (const BPKeyValue *bp_kv : all_bp)
  306. {
  307. // Write body pair key
  308. inStream.Write(bp_kv->GetKey());
  309. // Write body pair
  310. const CachedBodyPair &bp = bp_kv->GetValue();
  311. bp.SaveState(inStream);
  312. // Get attached manifolds
  313. vector<const MKeyValue *> all_m;
  314. GetAllManifoldsSorted(bp, all_m);
  315. // Write num manifolds
  316. size_t num_manifolds = all_m.size();
  317. inStream.Write(num_manifolds);
  318. // Write all manifolds
  319. for (const MKeyValue *m_kv : all_m)
  320. {
  321. // Write key
  322. inStream.Write(m_kv->GetKey());
  323. const CachedManifold &cm = m_kv->GetValue();
  324. JPH_ASSERT((cm.mFlags & (uint16)CachedManifold::EFlags::CCDContact) == 0);
  325. // Write amount of contacts
  326. inStream.Write(cm.mNumContactPoints);
  327. // Write manifold
  328. cm.SaveState(inStream);
  329. // Write contact points
  330. for (uint32 i = 0; i < cm.mNumContactPoints; ++i)
  331. cm.mContactPoints[i].SaveState(inStream);
  332. }
  333. }
  334. // Get CCD manifolds
  335. vector<const MKeyValue *> all_m;
  336. GetAllCCDManifoldsSorted(all_m);
  337. // Write num CCD manifolds
  338. size_t num_manifolds = all_m.size();
  339. inStream.Write(num_manifolds);
  340. // Write all CCD manifold keys
  341. for (const MKeyValue *m_kv : all_m)
  342. inStream.Write(m_kv->GetKey());
  343. }
  344. bool ContactConstraintManager::ManifoldCache::RestoreState(const ManifoldCache &inReadCache, StateRecorder &inStream)
  345. {
  346. JPH_ASSERT(!mIsFinalized);
  347. bool success = true;
  348. // When validating, get all existing body pairs
  349. vector<const BPKeyValue *> all_bp;
  350. if (inStream.IsValidating())
  351. inReadCache.GetAllBodyPairsSorted(all_bp);
  352. // Read amount of body pairs
  353. size_t num_body_pairs;
  354. if (inStream.IsValidating())
  355. num_body_pairs = all_bp.size();
  356. inStream.Read(num_body_pairs);
  357. // Read entire cache
  358. for (size_t i = 0; i < num_body_pairs; ++i)
  359. {
  360. // Read key
  361. BodyPair body_pair_key;
  362. if (inStream.IsValidating() && i < all_bp.size())
  363. body_pair_key = all_bp[i]->GetKey();
  364. inStream.Read(body_pair_key);
  365. // Create new entry for this body pair
  366. size_t body_pair_hash = BodyPairHash {} (body_pair_key);
  367. BPKeyValue *bp_kv = Create(body_pair_key, body_pair_hash);
  368. if (bp_kv == nullptr)
  369. {
  370. // Out of cache space
  371. success = false;
  372. break;
  373. }
  374. CachedBodyPair &bp = bp_kv->GetValue();
  375. // Read body pair
  376. if (inStream.IsValidating() && i < all_bp.size())
  377. memcpy(&bp, &all_bp[i]->GetValue(), sizeof(CachedBodyPair));
  378. bp.RestoreState(inStream);
  379. // When validating, get all existing manifolds
  380. vector<const MKeyValue *> all_m;
  381. if (inStream.IsValidating())
  382. inReadCache.GetAllManifoldsSorted(all_bp[i]->GetValue(), all_m);
  383. // Read amount of manifolds
  384. size_t num_manifolds;
  385. if (inStream.IsValidating())
  386. num_manifolds = all_m.size();
  387. inStream.Read(num_manifolds);
  388. uint32 handle = ManifoldMap::cInvalidHandle;
  389. for (size_t j = 0; j < num_manifolds; ++j)
  390. {
  391. // Read key
  392. SubShapeIDPair sub_shape_key;
  393. if (inStream.IsValidating() && j < all_m.size())
  394. sub_shape_key = all_m[j]->GetKey();
  395. inStream.Read(sub_shape_key);
  396. size_t sub_shape_key_hash = std::hash<SubShapeIDPair> {} (sub_shape_key);
  397. // Read amount of contact points
  398. uint16 num_contact_points;
  399. if (inStream.IsValidating() && j < all_m.size())
  400. num_contact_points = all_m[j]->GetValue().mNumContactPoints;
  401. inStream.Read(num_contact_points);
  402. // Read manifold
  403. MKeyValue *m_kv = Create(sub_shape_key, sub_shape_key_hash, num_contact_points);
  404. if (m_kv == nullptr)
  405. {
  406. // Out of cache space
  407. success = false;
  408. break;
  409. }
  410. CachedManifold &cm = m_kv->GetValue();
  411. if (inStream.IsValidating() && j < all_m.size())
  412. {
  413. memcpy(&cm, &all_m[j]->GetValue(), CachedManifold::sGetRequiredTotalSize(num_contact_points));
  414. cm.mNumContactPoints = uint16(num_contact_points); // Restore num contact points
  415. }
  416. cm.RestoreState(inStream);
  417. cm.mNextWithSameBodyPair = handle;
  418. handle = ToHandle(m_kv);
  419. // Read contact points
  420. for (uint32 k = 0; k < num_contact_points; ++k)
  421. cm.mContactPoints[k].RestoreState(inStream);
  422. }
  423. bp.mFirstCachedManifold = handle;
  424. }
  425. // When validating, get all existing CCD manifolds
  426. vector<const MKeyValue *> all_m;
  427. if (inStream.IsValidating())
  428. inReadCache.GetAllCCDManifoldsSorted(all_m);
  429. // Read amount of CCD manifolds
  430. size_t num_manifolds;
  431. if (inStream.IsValidating())
  432. num_manifolds = all_m.size();
  433. inStream.Read(num_manifolds);
  434. for (size_t j = 0; j < num_manifolds; ++j)
  435. {
  436. // Read key
  437. SubShapeIDPair sub_shape_key;
  438. if (inStream.IsValidating() && j < all_m.size())
  439. sub_shape_key = all_m[j]->GetKey();
  440. inStream.Read(sub_shape_key);
  441. size_t sub_shape_key_hash = std::hash<SubShapeIDPair> {} (sub_shape_key);
  442. // Create CCD manifold
  443. MKeyValue *m_kv = Create(sub_shape_key, sub_shape_key_hash, 0);
  444. if (m_kv == nullptr)
  445. {
  446. // Out of cache space
  447. success = false;
  448. break;
  449. }
  450. CachedManifold &cm = m_kv->GetValue();
  451. cm.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  452. }
  453. #ifdef JPH_ENABLE_ASSERTS
  454. mIsFinalized = true;
  455. #endif
  456. return success;
  457. }
  458. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  459. // ContactConstraintManager
  460. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  461. ContactConstraintManager::ContactConstraintManager(const PhysicsSettings &inPhysicsSettings) :
  462. mPhysicsSettings(inPhysicsSettings)
  463. {
  464. #ifdef JPH_ENABLE_ASSERTS
  465. // For the first frame mark this empty buffer as finalized
  466. mCache[mCacheWriteIdx ^ 1].Finalize();
  467. #endif
  468. }
  469. ContactConstraintManager::~ContactConstraintManager()
  470. {
  471. JPH_ASSERT(mConstraints == nullptr);
  472. }
  473. void ContactConstraintManager::Init(uint inMaxBodyPairs, uint inMaxContactConstraints)
  474. {
  475. mMaxConstraints = inMaxContactConstraints;
  476. // Calculate worst case cache usage
  477. uint cached_manifolds_size = inMaxContactConstraints * (sizeof(CachedManifold) + (MaxContactPoints - 1) * sizeof(CachedContactPoint));
  478. // Init the caches
  479. mCache[0].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  480. mCache[1].Init(inMaxBodyPairs, inMaxContactConstraints, cached_manifolds_size);
  481. }
  482. void ContactConstraintManager::PrepareConstraintBuffer(PhysicsUpdateContext *inContext)
  483. {
  484. // Store context
  485. mUpdateContext = inContext;
  486. // Allocate temporary constraint buffer
  487. JPH_ASSERT(mConstraints == nullptr);
  488. mConstraints = (ContactConstraint *)inContext->mTempAllocator->Allocate(mMaxConstraints * sizeof(ContactConstraint));
  489. // Use the amount of contacts from the last iteration to determine the amount of buckets to use in the hash map for this frame
  490. mCache[mCacheWriteIdx].Prepare(mCache[mCacheWriteIdx ^ 1]);
  491. }
  492. // Get the orientation of body 2 in local space of body 1
  493. static void sGetRelativeOrientation(const Body &inBody1, const Body &inBody2, Vec3 &outDeltaPosition, Quat &outDeltaRotation)
  494. {
  495. Quat inv_r1 = inBody1.GetRotation().Conjugated();
  496. // Get relative rotation
  497. outDeltaRotation = inv_r1 * inBody2.GetRotation();
  498. // Ensure W > 0, we'll be discarding it to save storage space
  499. if (outDeltaRotation.GetW() < 0.0f)
  500. outDeltaRotation = -outDeltaRotation;
  501. // Get relative translation
  502. outDeltaPosition = inv_r1 * (inBody2.GetCenterOfMassPosition() - inBody1.GetCenterOfMassPosition());
  503. }
  504. void ContactConstraintManager::GetContactsFromCache(Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outContactFound)
  505. {
  506. JPH_PROFILE_FUNCTION();
  507. // Start with nothing found and not handled
  508. outContactFound = false;
  509. outPairHandled = false;
  510. // Swap bodies so that body 1 id < body 2 id
  511. Body *body1, *body2;
  512. if (inBody1.GetID() < inBody2.GetID())
  513. {
  514. body1 = &inBody1;
  515. body2 = &inBody2;
  516. }
  517. else
  518. {
  519. body1 = &inBody2;
  520. body2 = &inBody1;
  521. }
  522. // Find the cached body pair
  523. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  524. size_t body_pair_hash = BodyPairHash {} (body_pair_key);
  525. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  526. const BPKeyValue *kv = read_cache.Find(body_pair_key, body_pair_hash);
  527. if (kv == nullptr)
  528. return;
  529. const CachedBodyPair &input_cbp = kv->GetValue();
  530. // Get old position delta
  531. Vec3 old_delta_position = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaPosition);
  532. // Reconstruct old quaternion delta
  533. Vec3 old_delta_rotation3 = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaRotation);
  534. Quat old_delta_rotation(Vec4(old_delta_rotation3, sqrt(max(0.0f, 1.0f - old_delta_rotation3.LengthSq()))));
  535. // Determine relative orientation
  536. Vec3 delta_position;
  537. Quat delta_rotation;
  538. sGetRelativeOrientation(*body1, *body2, delta_position, delta_rotation);
  539. // Check if bodies are still roughly in the same relative orientation
  540. if ((delta_position - old_delta_position).LengthSq() > mPhysicsSettings.mBodyPairCacheMaxDeltaPositionSq)
  541. return;
  542. if (delta_rotation.Dot(old_delta_rotation) < mPhysicsSettings.mBodyPairCacheCosMaxDeltaRotation)
  543. return;
  544. // The cache is valid, return that we've handled this body pair
  545. outPairHandled = true;
  546. // Copy the cached body pair to this frame
  547. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  548. BPKeyValue *output_bp_kv = write_cache.Create(body_pair_key, body_pair_hash);
  549. if (output_bp_kv == nullptr)
  550. return; // Out of cache space
  551. CachedBodyPair *output_cbp = &output_bp_kv->GetValue();
  552. memcpy(output_cbp, &input_cbp, sizeof(CachedBodyPair));
  553. // If there were no contacts, we have handled the contact
  554. if (input_cbp.mFirstCachedManifold == ManifoldMap::cInvalidHandle)
  555. return;
  556. // A contact is available, start creating constraints
  557. outContactFound = true;
  558. // Get body transforms
  559. Mat44 transform_body1 = body1->GetCenterOfMassTransform();
  560. Mat44 transform_body2 = body2->GetCenterOfMassTransform();
  561. // Get time step
  562. float delta_time = mUpdateContext->mSubStepDeltaTime;
  563. // Copy manifolds
  564. uint32 output_handle = ManifoldMap::cInvalidHandle;
  565. uint32 input_handle = input_cbp.mFirstCachedManifold;
  566. do
  567. {
  568. JPH_PROFILE("Add Constraint From Cached Manifold");
  569. // Find the existing manifold
  570. const MKeyValue *input_kv = read_cache.FromHandle(input_handle);
  571. const SubShapeIDPair &input_key = input_kv->GetKey();
  572. const CachedManifold &input_cm = input_kv->GetValue();
  573. JPH_ASSERT(input_cm.mNumContactPoints > 0); // There should be contact points in this manifold!
  574. // Create room for manifold in write buffer and copy data
  575. size_t input_hash = std::hash<SubShapeIDPair> {} (input_key);
  576. MKeyValue *output_kv = write_cache.Create(input_key, input_hash, input_cm.mNumContactPoints);
  577. if (output_kv == nullptr)
  578. break; // Out of cache space
  579. CachedManifold *output_cm = &output_kv->GetValue();
  580. memcpy(output_cm, &input_cm, CachedManifold::sGetRequiredTotalSize(input_cm.mNumContactPoints));
  581. // Link the object under the body pairs
  582. output_cm->mNextWithSameBodyPair = output_handle;
  583. output_handle = write_cache.ToHandle(output_kv);
  584. // Calculate default contact settings
  585. ContactSettings settings;
  586. settings.mCombinedFriction = mCombineFriction(*body1, *body2);
  587. settings.mCombinedRestitution = mCombineRestitution(*body1, *body2);
  588. // Calculate world space contact normal
  589. Vec3 world_space_normal = transform_body2.Multiply3x3(Vec3::sLoadFloat3Unsafe(output_cm->mContactNormal)).Normalized();
  590. // Call contact listener to update settings
  591. if (mContactListener != nullptr)
  592. {
  593. // Convert constraint to manifold structure for callback
  594. ContactManifold manifold;
  595. manifold.mWorldSpaceNormal = world_space_normal;
  596. manifold.mSubShapeID1 = input_key.GetSubShapeID1();
  597. manifold.mSubShapeID2 = input_key.GetSubShapeID2();
  598. manifold.mWorldSpaceContactPointsOn1.resize(output_cm->mNumContactPoints);
  599. manifold.mWorldSpaceContactPointsOn2.resize(output_cm->mNumContactPoints);
  600. float penetration_depth = -FLT_MAX;
  601. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  602. {
  603. CachedContactPoint &ccp = output_cm->mContactPoints[i];
  604. manifold.mWorldSpaceContactPointsOn1[i] = transform_body1 * Vec3::sLoadFloat3Unsafe(ccp.mPosition1);
  605. manifold.mWorldSpaceContactPointsOn2[i] = transform_body2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2);
  606. penetration_depth = max(penetration_depth, (manifold.mWorldSpaceContactPointsOn1[0] - manifold.mWorldSpaceContactPointsOn2[0]).Dot(world_space_normal));
  607. }
  608. manifold.mPenetrationDepth = penetration_depth; // We don't have the penetration depth anymore, estimate it
  609. // Notify callback
  610. mContactListener->OnContactPersisted(*body1, *body2, manifold, settings);
  611. }
  612. // If one of the bodies is a sensor, don't actually create the constraint
  613. if (!body1->IsSensor() && !body2->IsSensor())
  614. {
  615. // Add contact constraint in world space for the solver
  616. uint32 constraint_idx = mNumConstraints++;
  617. if (constraint_idx >= mMaxConstraints)
  618. {
  619. JPH_ASSERT(false, "Out of contact constraints!");
  620. break;
  621. }
  622. ContactConstraint &constraint = mConstraints[constraint_idx];
  623. new (&constraint) ContactConstraint();
  624. constraint.mBody1 = body1;
  625. constraint.mBody2 = body2;
  626. constraint.mSortKey = input_hash;
  627. constraint.mWorldSpaceNormal = world_space_normal;
  628. constraint.mSettings = settings;
  629. constraint.mContactPoints.resize(output_cm->mNumContactPoints);
  630. for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)
  631. {
  632. CachedContactPoint &ccp = output_cm->mContactPoints[i];
  633. WorldContactPoint &wcp = constraint.mContactPoints[i];
  634. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);
  635. wcp.mFrictionConstraint1.SetTotalLambda(ccp.mFrictionLambda[0]);
  636. wcp.mFrictionConstraint2.SetTotalLambda(ccp.mFrictionLambda[1]);
  637. wcp.mContactPoint = &ccp;
  638. }
  639. // Calculate tangents
  640. Vec3 t1, t2;
  641. constraint.GetTangents(t1, t2);
  642. // Setup velocity constraint with contact settings potentially updated by callback
  643. float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;
  644. for (WorldContactPoint &wcp : constraint.mContactPoints)
  645. {
  646. Vec3 p1 = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  647. Vec3 p2 = transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  648. wcp.CalculateFrictionAndNonPenetrationConstraintProperties(delta_time, *body1, *body2, p1, p2, constraint.mWorldSpaceNormal, t1, t2, settings.mCombinedRestitution, settings.mCombinedFriction, min_velocity_for_restitution);
  649. }
  650. // Notify island builder
  651. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  652. #ifdef JPH_DEBUG_RENDERER
  653. // Draw the manifold
  654. if (sDrawContactManifolds)
  655. constraint.Draw(DebugRenderer::sInstance, Color::sYellow);
  656. #endif // JPH_DEBUG_RENDERER
  657. }
  658. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  659. input_cm.mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  660. // Fetch the next manifold
  661. input_handle = input_cm.mNextWithSameBodyPair;
  662. }
  663. while (input_handle != ManifoldMap::cInvalidHandle);
  664. output_cbp->mFirstCachedManifold = output_handle;
  665. }
  666. ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(const Body &inBody1, const Body &inBody2)
  667. {
  668. JPH_PROFILE_FUNCTION();
  669. // Swap bodies so that body 1 id < body 2 id
  670. const Body *body1, *body2;
  671. if (inBody1.GetID() < inBody2.GetID())
  672. {
  673. body1 = &inBody1;
  674. body2 = &inBody2;
  675. }
  676. else
  677. {
  678. body1 = &inBody2;
  679. body2 = &inBody1;
  680. }
  681. // Add an entry
  682. BodyPair body_pair_key(body1->GetID(), body2->GetID());
  683. size_t body_pair_hash = BodyPairHash {} (body_pair_key);
  684. BPKeyValue *body_pair_kv = mCache[mCacheWriteIdx].Create(body_pair_key, body_pair_hash);
  685. if (body_pair_kv == nullptr)
  686. return nullptr; // Out of cache space
  687. CachedBodyPair *cbp = &body_pair_kv->GetValue();
  688. cbp->mFirstCachedManifold = ManifoldMap::cInvalidHandle;
  689. // Determine relative orientation
  690. Vec3 delta_position;
  691. Quat delta_rotation;
  692. sGetRelativeOrientation(*body1, *body2, delta_position, delta_rotation);
  693. // Store it
  694. delta_position.StoreFloat3(&cbp->mDeltaPosition);
  695. delta_rotation.GetXYZ().StoreFloat3(&cbp->mDeltaRotation);
  696. return cbp;
  697. }
  698. void ContactConstraintManager::AddContactConstraint(BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)
  699. {
  700. JPH_PROFILE_FUNCTION();
  701. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  702. // Swap bodies so that body 1 id < body 2 id
  703. const ContactManifold *manifold;
  704. Body *body1, *body2;
  705. ContactManifold temp;
  706. if (inBody2.GetID() < inBody1.GetID())
  707. {
  708. body1 = &inBody2;
  709. body2 = &inBody1;
  710. temp = inManifold.SwapShapes();
  711. manifold = &temp;
  712. }
  713. else
  714. {
  715. body1 = &inBody1;
  716. body2 = &inBody2;
  717. manifold = &inManifold;
  718. }
  719. // Calculate hash
  720. SubShapeIDPair key { body1->GetID(), manifold->mSubShapeID1, body2->GetID(), manifold->mSubShapeID2 };
  721. size_t key_hash = std::hash<SubShapeIDPair> {} (key);
  722. // Determine number of contact points
  723. int num_contact_points = (int)manifold->mWorldSpaceContactPointsOn1.size();
  724. JPH_ASSERT(num_contact_points <= MaxContactPoints);
  725. JPH_ASSERT(num_contact_points == (int)manifold->mWorldSpaceContactPointsOn2.size());
  726. // Reserve space for new contact cache entry
  727. // Note that for dynamic vs dynamic we always require the first body to have a lower body id to get a consistent key
  728. // under which to look up the contact
  729. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  730. MKeyValue *new_manifold_kv = write_cache.Create(key, key_hash, num_contact_points);
  731. if (new_manifold_kv == nullptr)
  732. return; // Out of cache space
  733. CachedManifold *new_manifold = &new_manifold_kv->GetValue();
  734. // Transform the world space normal to the space of body 2 (this is usually the static body)
  735. Mat44 inverse_transform_body2 = body2->GetInverseCenterOfMassTransform();
  736. inverse_transform_body2.Multiply3x3(manifold->mWorldSpaceNormal).Normalized().StoreFloat3(&new_manifold->mContactNormal);
  737. // Settings object that gets passed to the callback
  738. ContactSettings settings;
  739. settings.mCombinedFriction = mCombineFriction(*body1, *body2);
  740. settings.mCombinedRestitution = mCombineRestitution(*body1, *body2);
  741. // Get the contact points for the old cache entry
  742. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  743. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  744. const CachedContactPoint *ccp_start;
  745. const CachedContactPoint *ccp_end;
  746. if (old_manifold_kv != nullptr)
  747. {
  748. // Call point persisted listener
  749. if (mContactListener != nullptr)
  750. mContactListener->OnContactPersisted(*body1, *body2, *manifold, settings);
  751. // Fetch the contact points from the old manifold
  752. const CachedManifold *old_manifold = &old_manifold_kv->GetValue();
  753. ccp_start = old_manifold->mContactPoints;
  754. ccp_end = ccp_start + old_manifold->mNumContactPoints;
  755. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  756. old_manifold->mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  757. }
  758. else
  759. {
  760. // Call point added listener
  761. if (mContactListener != nullptr)
  762. mContactListener->OnContactAdded(*body1, *body2, *manifold, settings);
  763. // No contact points available from old manifold
  764. ccp_start = nullptr;
  765. ccp_end = nullptr;
  766. }
  767. // Get inverse transform for body 1
  768. Mat44 inverse_transform_body1 = body1->GetInverseCenterOfMassTransform();
  769. // If one of the bodies is a sensor, don't actually create the constraint
  770. if (body1->IsSensor() || body2->IsSensor())
  771. {
  772. // Store the contact manifold in the cache
  773. for (int i = 0; i < num_contact_points; ++i)
  774. {
  775. // Convert to local space to the body
  776. Vec3 p1 = inverse_transform_body1 * manifold->mWorldSpaceContactPointsOn1[i];
  777. Vec3 p2 = inverse_transform_body2 * manifold->mWorldSpaceContactPointsOn2[i];
  778. // Create new contact point
  779. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  780. p1.StoreFloat3(&cp.mPosition1);
  781. p2.StoreFloat3(&cp.mPosition2);
  782. // We don't use this, but reset them anyway for determinism check
  783. cp.mNonPenetrationLambda = 0.0f;
  784. cp.mFrictionLambda[0] = 0.0f;
  785. cp.mFrictionLambda[1] = 0.0f;
  786. }
  787. }
  788. else
  789. {
  790. // Add contact constraint
  791. uint32 constraint_idx = mNumConstraints++;
  792. if (constraint_idx >= mMaxConstraints)
  793. {
  794. JPH_ASSERT(false, "Out of contact constraints!");
  795. // Manifold has been created already, we're not filling it in, so we need to reset the contact number of points.
  796. // 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.
  797. new_manifold->mNumContactPoints = 0;
  798. return;
  799. }
  800. ContactConstraint &constraint = mConstraints[constraint_idx];
  801. new (&constraint) ContactConstraint();
  802. constraint.mWorldSpaceNormal = manifold->mWorldSpaceNormal;
  803. constraint.mBody1 = body1;
  804. constraint.mBody2 = body2;
  805. constraint.mSortKey = key_hash;
  806. constraint.mSettings = settings;
  807. // Notify island builder
  808. mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  809. // Get time step
  810. float delta_time = mUpdateContext->mSubStepDeltaTime;
  811. // Calculate tangents
  812. Vec3 t1, t2;
  813. constraint.GetTangents(t1, t2);
  814. constraint.mContactPoints.resize(num_contact_points);
  815. for (int i = 0; i < num_contact_points; ++i)
  816. {
  817. // Convert to world space and set positions
  818. WorldContactPoint &wcp = constraint.mContactPoints[i];
  819. Vec3 p1_ws = manifold->mWorldSpaceContactPointsOn1[i];
  820. Vec3 p2_ws = manifold->mWorldSpaceContactPointsOn2[i];
  821. // Convert to local space to the body
  822. Vec3 p1_ls = inverse_transform_body1 * p1_ws;
  823. Vec3 p2_ls = inverse_transform_body2 * p2_ws;
  824. // Check if we have a close contact point from last update
  825. bool lambda_set = false;
  826. for (const CachedContactPoint *ccp = ccp_start; ccp < ccp_end; ccp++)
  827. if (Vec3::sLoadFloat3Unsafe(ccp->mPosition1).IsClose(p1_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq)
  828. && Vec3::sLoadFloat3Unsafe(ccp->mPosition2).IsClose(p2_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq))
  829. {
  830. // Get lambdas from previous frame
  831. wcp.mNonPenetrationConstraint.SetTotalLambda(ccp->mNonPenetrationLambda);
  832. wcp.mFrictionConstraint1.SetTotalLambda(ccp->mFrictionLambda[0]);
  833. wcp.mFrictionConstraint2.SetTotalLambda(ccp->mFrictionLambda[1]);
  834. lambda_set = true;
  835. break;
  836. }
  837. if (!lambda_set)
  838. {
  839. wcp.mNonPenetrationConstraint.SetTotalLambda(0.0f);
  840. wcp.mFrictionConstraint1.SetTotalLambda(0.0f);
  841. wcp.mFrictionConstraint2.SetTotalLambda(0.0f);
  842. }
  843. // Create new contact point
  844. CachedContactPoint &cp = new_manifold->mContactPoints[i];
  845. p1_ls.StoreFloat3(&cp.mPosition1);
  846. p2_ls.StoreFloat3(&cp.mPosition2);
  847. wcp.mContactPoint = &cp;
  848. // Setup velocity constraint
  849. wcp.CalculateFrictionAndNonPenetrationConstraintProperties(delta_time, *body1, *body2, p1_ws, p2_ws, manifold->mWorldSpaceNormal, t1, t2, settings.mCombinedRestitution, settings.mCombinedFriction, mPhysicsSettings.mMinVelocityForRestitution);
  850. }
  851. #ifdef JPH_DEBUG_RENDERER
  852. // Draw the manifold
  853. if (sDrawContactManifolds)
  854. constraint.Draw(DebugRenderer::sInstance, Color::sOrange);
  855. #endif // JPH_DEBUG_RENDERER
  856. }
  857. // Store cached contact point in body pair cache
  858. CachedBodyPair *cbp = reinterpret_cast<CachedBodyPair *>(inBodyPairHandle);
  859. new_manifold->mNextWithSameBodyPair = cbp->mFirstCachedManifold;
  860. cbp->mFirstCachedManifold = write_cache.ToHandle(new_manifold_kv);
  861. }
  862. void ContactConstraintManager::OnCCDContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings)
  863. {
  864. JPH_ASSERT(inManifold.mWorldSpaceNormal.IsNormalized());
  865. // Calculate contact settings
  866. outSettings.mCombinedFriction = mCombineFriction(inBody1, inBody2);
  867. outSettings.mCombinedRestitution = mCombineRestitution(inBody1, inBody2);
  868. // 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
  869. if (mContactListener != nullptr)
  870. {
  871. // Swap bodies so that body 1 id < body 2 id
  872. const ContactManifold *manifold;
  873. const Body *body1, *body2;
  874. ContactManifold temp;
  875. if (inBody2.GetID() < inBody1.GetID())
  876. {
  877. body1 = &inBody2;
  878. body2 = &inBody1;
  879. temp = inManifold.SwapShapes();
  880. manifold = &temp;
  881. }
  882. else
  883. {
  884. body1 = &inBody1;
  885. body2 = &inBody2;
  886. manifold = &inManifold;
  887. }
  888. // Calculate hash
  889. SubShapeIDPair key { body1->GetID(), manifold->mSubShapeID1, body2->GetID(), manifold->mSubShapeID2 };
  890. size_t key_hash = std::hash<SubShapeIDPair> {} (key);
  891. // Check if we already created this contact this physics update
  892. ManifoldCache &write_cache = mCache[mCacheWriteIdx];
  893. MKVAndCreated new_manifold_kv = write_cache.FindOrCreate(key, key_hash, 0);
  894. if (new_manifold_kv.second)
  895. {
  896. // This contact is new for this physics update, check if previous update we already had this contact.
  897. const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  898. const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);
  899. if (old_manifold_kv == nullptr)
  900. {
  901. // New contact
  902. mContactListener->OnContactAdded(*body1, *body2, *manifold, outSettings);
  903. }
  904. else
  905. {
  906. // Existing contact
  907. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  908. // Mark contact as persisted so that we won't fire OnContactRemoved callbacks
  909. old_manifold_kv->GetValue().mFlags |= (uint16)CachedManifold::EFlags::ContactPersisted;
  910. }
  911. // Check if the cache is full
  912. if (new_manifold_kv.first != nullptr)
  913. {
  914. // 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
  915. CachedManifold &new_manifold = new_manifold_kv.first->GetValue();
  916. new_manifold.mContactNormal = { 0, 0, 0 };
  917. new_manifold.mFlags |= (uint16)CachedManifold::EFlags::CCDContact;
  918. }
  919. }
  920. else
  921. {
  922. // Already found this contact this physics update.
  923. // Note that we can trigger OnContactPersisted multiple times per physics update, but otherwise we have no way of obtaining the settings
  924. mContactListener->OnContactPersisted(*body1, *body2, *manifold, outSettings);
  925. }
  926. }
  927. }
  928. void ContactConstraintManager::SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const
  929. {
  930. JPH_PROFILE_FUNCTION();
  931. sort(inConstraintIdxBegin, inConstraintIdxEnd, [this](uint32 inLHS, uint32 inRHS) {
  932. const ContactConstraint &lhs = mConstraints[inLHS];
  933. const ContactConstraint &rhs = mConstraints[inRHS];
  934. JPH_ASSERT(lhs.mSortKey != rhs.mSortKey, "Hash collision, ordering will be inconsistent");
  935. return lhs.mSortKey < rhs.mSortKey;
  936. });
  937. }
  938. void ContactConstraintManager::FinalizeContactCache()
  939. {
  940. JPH_PROFILE_FUNCTION();
  941. // Buffers are now complete, make write buffer the read buffer
  942. #ifdef JPH_ENABLE_ASSERTS
  943. mCache[mCacheWriteIdx].Finalize();
  944. #endif
  945. mCacheWriteIdx ^= 1;
  946. }
  947. void ContactConstraintManager::ContactPointRemovedCallbacks()
  948. {
  949. JPH_PROFILE_FUNCTION();
  950. // Get the read cache
  951. ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];
  952. // Call the actual callbacks
  953. if (mContactListener != nullptr)
  954. read_cache.ContactPointRemovedCallbacks(mContactListener);
  955. // We're done with the cache now
  956. read_cache.Clear();
  957. }
  958. void ContactConstraintManager::SetupVelocityConstraints(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd, float inDeltaTime)
  959. {
  960. JPH_PROFILE_FUNCTION();
  961. float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;
  962. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  963. {
  964. ContactConstraint &constraint = mConstraints[*constraint_idx];
  965. // Fetch bodies
  966. Body &body1 = *constraint.mBody1;
  967. Body &body2 = *constraint.mBody2;
  968. // Get body transforms
  969. Mat44 transform_body1 = body1.GetCenterOfMassTransform();
  970. Mat44 transform_body2 = body2.GetCenterOfMassTransform();
  971. // Calculate tangents
  972. Vec3 t1, t2;
  973. constraint.GetTangents(t1, t2);
  974. // Setup velocity constraint
  975. for (WorldContactPoint &wcp : constraint.mContactPoints)
  976. {
  977. Vec3 p1 = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  978. Vec3 p2 = transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  979. wcp.CalculateFrictionAndNonPenetrationConstraintProperties(inDeltaTime, body1, body2, p1, p2, constraint.mWorldSpaceNormal, t1, t2, constraint.mSettings.mCombinedRestitution, constraint.mSettings.mCombinedFriction, min_velocity_for_restitution);
  980. }
  981. }
  982. }
  983. void ContactConstraintManager::WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio)
  984. {
  985. JPH_PROFILE_FUNCTION();
  986. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  987. {
  988. ContactConstraint &constraint = mConstraints[*constraint_idx];
  989. // Fetch bodies
  990. Body &body1 = *constraint.mBody1;
  991. Body &body2 = *constraint.mBody2;
  992. // Calculate tangents
  993. Vec3 t1, t2;
  994. constraint.GetTangents(t1, t2);
  995. for (WorldContactPoint &wcp : constraint.mContactPoints)
  996. {
  997. // Warm starting: Apply impulse from last frame
  998. if (wcp.mFrictionConstraint1.IsActive())
  999. {
  1000. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1001. wcp.mFrictionConstraint1.WarmStart(body1, body2, t1, inWarmStartImpulseRatio);
  1002. wcp.mFrictionConstraint2.WarmStart(body1, body2, t2, inWarmStartImpulseRatio);
  1003. }
  1004. wcp.mNonPenetrationConstraint.WarmStart(body1, body2, constraint.mWorldSpaceNormal, inWarmStartImpulseRatio);
  1005. }
  1006. }
  1007. }
  1008. bool ContactConstraintManager::SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1009. {
  1010. JPH_PROFILE_FUNCTION();
  1011. bool any_impulse_applied = false;
  1012. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1013. {
  1014. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1015. // Fetch bodies
  1016. Body &body1 = *constraint.mBody1;
  1017. Body &body2 = *constraint.mBody2;
  1018. // Calculate tangents
  1019. Vec3 t1, t2;
  1020. constraint.GetTangents(t1, t2);
  1021. // First apply all friction constraints (non-penetration is more important than friction)
  1022. for (WorldContactPoint &wcp : constraint.mContactPoints)
  1023. {
  1024. // Check if friction is enabled
  1025. if (wcp.mFrictionConstraint1.IsActive())
  1026. {
  1027. JPH_ASSERT(wcp.mFrictionConstraint2.IsActive());
  1028. // Calculate max impulse that can be applied. Note that we're using the non-penetration impulse from the previous iteration here.
  1029. // We do this because non-penetration is more important so is solved last (the last things that are solved in an iterative solver
  1030. // contribute the most).
  1031. float max_lambda_f = constraint.mSettings.mCombinedFriction * wcp.mNonPenetrationConstraint.GetTotalLambda();
  1032. // Solve friction velocities
  1033. // Note that what we're doing is not fully correct since the max force we can apply is 2 * max_lambda_f instead of max_lambda_f since we're solving axis independently
  1034. if (wcp.mFrictionConstraint1.SolveVelocityConstraint(body1, body2, t1, -max_lambda_f, max_lambda_f))
  1035. any_impulse_applied = true;
  1036. if (wcp.mFrictionConstraint2.SolveVelocityConstraint(body1, body2, t2, -max_lambda_f, max_lambda_f))
  1037. any_impulse_applied = true;
  1038. }
  1039. }
  1040. // Then apply all non-penetration constraints
  1041. for (WorldContactPoint &wcp : constraint.mContactPoints)
  1042. {
  1043. // Solve non penetration velocities
  1044. if (wcp.mNonPenetrationConstraint.SolveVelocityConstraint(body1, body2, constraint.mWorldSpaceNormal, 0.0f, FLT_MAX))
  1045. any_impulse_applied = true;
  1046. }
  1047. }
  1048. return any_impulse_applied;
  1049. }
  1050. void ContactConstraintManager::StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1051. {
  1052. // Copy back total applied impulse to cache for the next frame
  1053. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1054. {
  1055. const ContactConstraint &constraint = mConstraints[*constraint_idx];
  1056. for (const WorldContactPoint &wcp : constraint.mContactPoints)
  1057. {
  1058. wcp.mContactPoint->mNonPenetrationLambda = wcp.mNonPenetrationConstraint.GetTotalLambda();
  1059. wcp.mContactPoint->mFrictionLambda[0] = wcp.mFrictionConstraint1.GetTotalLambda();
  1060. wcp.mContactPoint->mFrictionLambda[1] = wcp.mFrictionConstraint2.GetTotalLambda();
  1061. }
  1062. }
  1063. }
  1064. bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)
  1065. {
  1066. JPH_PROFILE_FUNCTION();
  1067. bool any_impulse_applied = false;
  1068. float delta_time = mUpdateContext->mSubStepDeltaTime;
  1069. for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)
  1070. {
  1071. ContactConstraint &constraint = mConstraints[*constraint_idx];
  1072. // Fetch bodies
  1073. Body &body1 = *constraint.mBody1;
  1074. Body &body2 = *constraint.mBody2;
  1075. // Get transforms
  1076. Mat44 transform1 = body1.GetCenterOfMassTransform();
  1077. Mat44 transform2 = body2.GetCenterOfMassTransform();
  1078. for (WorldContactPoint &wcp : constraint.mContactPoints)
  1079. {
  1080. // Calculate new contact point positions in world space (the bodies may have moved)
  1081. Vec3 p1 = transform1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);
  1082. Vec3 p2 = transform2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);
  1083. // Calculate separation along the normal (negative if interpenetrating)
  1084. // 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
  1085. // Clamp penetration to a max PhysicsSettings::mMaxPenetrationDistance so that we don't apply a huge impulse if we're penetrating a lot
  1086. float separation = max((p2 - p1).Dot(constraint.mWorldSpaceNormal) + mPhysicsSettings.mPenetrationSlop, -mPhysicsSettings.mMaxPenetrationDistance);
  1087. // Only enforce constraint when separation < 0 (otherwise we're apart)
  1088. if (separation < 0.0f)
  1089. {
  1090. // Update constraint properties (bodies may have moved)
  1091. wcp.CalculateNonPenetrationConstraintProperties(delta_time, body1, body2, p1, p2, constraint.mWorldSpaceNormal);
  1092. // Solve position errors
  1093. if (wcp.mNonPenetrationConstraint.SolvePositionConstraint(body1, body2, constraint.mWorldSpaceNormal, separation, mPhysicsSettings.mBaumgarte))
  1094. any_impulse_applied = true;
  1095. }
  1096. }
  1097. }
  1098. return any_impulse_applied;
  1099. }
  1100. void ContactConstraintManager::RecycleConstraintBuffer()
  1101. {
  1102. // Use the amount of contacts from the last iteration to determine the amount of buckets to use in the hash map for this frame
  1103. mCache[mCacheWriteIdx].Prepare(mCache[mCacheWriteIdx ^ 1]);
  1104. // Reset constraint array
  1105. mNumConstraints = 0;
  1106. }
  1107. void ContactConstraintManager::FinishConstraintBuffer()
  1108. {
  1109. // Free constraints buffer
  1110. mUpdateContext->mTempAllocator->Free(mConstraints, mMaxConstraints * sizeof(ContactConstraint));
  1111. mConstraints = nullptr;
  1112. mNumConstraints = 0;
  1113. // Reset update context
  1114. mUpdateContext = nullptr;
  1115. }
  1116. void ContactConstraintManager::SaveState(StateRecorder &inStream) const
  1117. {
  1118. mCache[mCacheWriteIdx ^ 1].SaveState(inStream);
  1119. }
  1120. bool ContactConstraintManager::RestoreState(StateRecorder &inStream)
  1121. {
  1122. bool success = mCache[mCacheWriteIdx].RestoreState(mCache[mCacheWriteIdx ^ 1], inStream);
  1123. mCacheWriteIdx ^= 1;
  1124. mCache[mCacheWriteIdx].Clear();
  1125. return success;
  1126. }
  1127. } // JPH