ContactConstraintManager.cpp 70 KB

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