BodyManager.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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/Body/BodyManager.h>
  6. #include <Jolt/Physics/PhysicsSettings.h>
  7. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  8. #include <Jolt/Physics/Body/BodyLock.h>
  9. #include <Jolt/Physics/Body/BodyActivationListener.h>
  10. #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
  11. #include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>
  12. #include <Jolt/Physics/SoftBody/SoftBodyShape.h>
  13. #include <Jolt/Physics/StateRecorder.h>
  14. #include <Jolt/Core/StringTools.h>
  15. #include <Jolt/Core/QuickSort.h>
  16. #ifdef JPH_DEBUG_RENDERER
  17. #include <Jolt/Renderer/DebugRenderer.h>
  18. #include <Jolt/Physics/Body/BodyFilter.h>
  19. #endif // JPH_DEBUG_RENDERER
  20. JPH_NAMESPACE_BEGIN
  21. #ifdef JPH_ENABLE_ASSERTS
  22. static thread_local bool sOverrideAllowActivation = false;
  23. static thread_local bool sOverrideAllowDeactivation = false;
  24. bool BodyManager::sGetOverrideAllowActivation()
  25. {
  26. return sOverrideAllowActivation;
  27. }
  28. void BodyManager::sSetOverrideAllowActivation(bool inValue)
  29. {
  30. sOverrideAllowActivation = inValue;
  31. }
  32. bool BodyManager::sGetOverrideAllowDeactivation()
  33. {
  34. return sOverrideAllowDeactivation;
  35. }
  36. void BodyManager::sSetOverrideAllowDeactivation(bool inValue)
  37. {
  38. sOverrideAllowDeactivation = inValue;
  39. }
  40. #endif
  41. // Helper class that combines a body and its motion properties
  42. class BodyWithMotionProperties : public Body
  43. {
  44. public:
  45. JPH_OVERRIDE_NEW_DELETE
  46. MotionProperties mMotionProperties;
  47. };
  48. // Helper class that combines a soft body its motion properties and shape
  49. class SoftBodyWithMotionPropertiesAndShape : public Body
  50. {
  51. public:
  52. SoftBodyWithMotionPropertiesAndShape()
  53. {
  54. mShape.SetEmbedded();
  55. }
  56. SoftBodyMotionProperties mMotionProperties;
  57. SoftBodyShape mShape;
  58. };
  59. inline void BodyManager::sDeleteBody(Body *inBody)
  60. {
  61. if (inBody->mMotionProperties != nullptr)
  62. {
  63. JPH_IF_ENABLE_ASSERTS(inBody->mMotionProperties = nullptr;)
  64. if (inBody->IsSoftBody())
  65. {
  66. inBody->mShape = nullptr; // Release the shape to avoid assertion on shape destruction because of embedded object with refcount > 0
  67. delete static_cast<SoftBodyWithMotionPropertiesAndShape *>(inBody);
  68. }
  69. else
  70. delete static_cast<BodyWithMotionProperties *>(inBody);
  71. }
  72. else
  73. delete inBody;
  74. }
  75. BodyManager::~BodyManager()
  76. {
  77. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  78. // Destroy any bodies that are still alive
  79. for (Body *b : mBodies)
  80. if (sIsValidBodyPointer(b))
  81. sDeleteBody(b);
  82. for (BodyID *active_bodies : mActiveBodies)
  83. delete [] active_bodies;
  84. }
  85. void BodyManager::Init(uint inMaxBodies, uint inNumBodyMutexes, const BroadPhaseLayerInterface &inLayerInterface)
  86. {
  87. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  88. // Num body mutexes must be a power of two and not bigger than our MutexMask
  89. uint num_body_mutexes = Clamp<uint>(GetNextPowerOf2(inNumBodyMutexes == 0? 2 * thread::hardware_concurrency() : inNumBodyMutexes), 1, sizeof(MutexMask) * 8);
  90. #ifdef JPH_TSAN_ENABLED
  91. num_body_mutexes = min(num_body_mutexes, 32U); // TSAN errors out when locking too many mutexes on the same thread, see: https://github.com/google/sanitizers/issues/950
  92. #endif
  93. // Allocate the body mutexes
  94. mBodyMutexes.Init(num_body_mutexes);
  95. // Allocate space for bodies
  96. mBodies.reserve(inMaxBodies);
  97. // Allocate space for active bodies
  98. for (BodyID *&active_bodies : mActiveBodies)
  99. {
  100. JPH_ASSERT(active_bodies == nullptr);
  101. active_bodies = new BodyID [inMaxBodies];
  102. }
  103. // Allocate space for sequence numbers
  104. mBodySequenceNumbers.resize(inMaxBodies, 0);
  105. // Keep layer interface
  106. mBroadPhaseLayerInterface = &inLayerInterface;
  107. }
  108. uint BodyManager::GetNumBodies() const
  109. {
  110. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  111. return mNumBodies;
  112. }
  113. BodyManager::BodyStats BodyManager::GetBodyStats() const
  114. {
  115. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  116. BodyStats stats;
  117. stats.mNumBodies = mNumBodies;
  118. stats.mMaxBodies = uint(mBodies.capacity());
  119. for (const Body *body : mBodies)
  120. if (sIsValidBodyPointer(body))
  121. {
  122. if (body->IsSoftBody())
  123. {
  124. stats.mNumSoftBodies++;
  125. if (body->IsActive())
  126. stats.mNumActiveSoftBodies++;
  127. }
  128. else
  129. {
  130. switch (body->GetMotionType())
  131. {
  132. case EMotionType::Static:
  133. stats.mNumBodiesStatic++;
  134. break;
  135. case EMotionType::Dynamic:
  136. stats.mNumBodiesDynamic++;
  137. if (body->IsActive())
  138. stats.mNumActiveBodiesDynamic++;
  139. break;
  140. case EMotionType::Kinematic:
  141. stats.mNumBodiesKinematic++;
  142. if (body->IsActive())
  143. stats.mNumActiveBodiesKinematic++;
  144. break;
  145. }
  146. }
  147. }
  148. return stats;
  149. }
  150. Body *BodyManager::AllocateBody(const BodyCreationSettings &inBodyCreationSettings) const
  151. {
  152. // Fill in basic properties
  153. Body *body;
  154. if (inBodyCreationSettings.HasMassProperties())
  155. {
  156. BodyWithMotionProperties *bmp = new BodyWithMotionProperties;
  157. body = bmp;
  158. body->mMotionProperties = &bmp->mMotionProperties;
  159. }
  160. else
  161. {
  162. body = new Body;
  163. }
  164. body->mBodyType = EBodyType::RigidBody;
  165. body->mShape = inBodyCreationSettings.GetShape();
  166. body->mUserData = inBodyCreationSettings.mUserData;
  167. body->SetFriction(inBodyCreationSettings.mFriction);
  168. body->SetRestitution(inBodyCreationSettings.mRestitution);
  169. body->mMotionType = inBodyCreationSettings.mMotionType;
  170. if (inBodyCreationSettings.mIsSensor)
  171. body->SetIsSensor(true);
  172. if (inBodyCreationSettings.mCollideKinematicVsNonDynamic)
  173. body->SetCollideKinematicVsNonDynamic(true);
  174. if (inBodyCreationSettings.mUseManifoldReduction)
  175. body->SetUseManifoldReduction(true);
  176. if (inBodyCreationSettings.mApplyGyroscopicForce)
  177. body->SetApplyGyroscopicForce(true);
  178. if (inBodyCreationSettings.mEnhancedInternalEdgeRemoval)
  179. body->SetEnhancedInternalEdgeRemoval(true);
  180. SetBodyObjectLayerInternal(*body, inBodyCreationSettings.mObjectLayer);
  181. body->mObjectLayer = inBodyCreationSettings.mObjectLayer;
  182. body->mCollisionGroup = inBodyCreationSettings.mCollisionGroup;
  183. if (inBodyCreationSettings.HasMassProperties())
  184. {
  185. MotionProperties *mp = body->mMotionProperties;
  186. mp->SetLinearDamping(inBodyCreationSettings.mLinearDamping);
  187. mp->SetAngularDamping(inBodyCreationSettings.mAngularDamping);
  188. mp->SetMaxLinearVelocity(inBodyCreationSettings.mMaxLinearVelocity);
  189. mp->SetMaxAngularVelocity(inBodyCreationSettings.mMaxAngularVelocity);
  190. mp->SetMassProperties(inBodyCreationSettings.mAllowedDOFs, inBodyCreationSettings.GetMassProperties());
  191. mp->SetLinearVelocity(inBodyCreationSettings.mLinearVelocity); // Needs to happen after setting the max linear/angular velocity and setting allowed DOFs
  192. mp->SetAngularVelocity(inBodyCreationSettings.mAngularVelocity);
  193. mp->SetGravityFactor(inBodyCreationSettings.mGravityFactor);
  194. mp->SetNumVelocityStepsOverride(inBodyCreationSettings.mNumVelocityStepsOverride);
  195. mp->SetNumPositionStepsOverride(inBodyCreationSettings.mNumPositionStepsOverride);
  196. mp->mMotionQuality = inBodyCreationSettings.mMotionQuality;
  197. mp->mAllowSleeping = inBodyCreationSettings.mAllowSleeping;
  198. JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)
  199. JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)
  200. }
  201. // Position body
  202. body->SetPositionAndRotationInternal(inBodyCreationSettings.mPosition, inBodyCreationSettings.mRotation);
  203. return body;
  204. }
  205. /// Create a soft body using creation settings. The returned body will not be part of the body manager yet.
  206. Body *BodyManager::AllocateSoftBody(const SoftBodyCreationSettings &inSoftBodyCreationSettings) const
  207. {
  208. // Fill in basic properties
  209. SoftBodyWithMotionPropertiesAndShape *bmp = new SoftBodyWithMotionPropertiesAndShape;
  210. SoftBodyMotionProperties *mp = &bmp->mMotionProperties;
  211. SoftBodyShape *shape = &bmp->mShape;
  212. Body *body = bmp;
  213. shape->mSoftBodyMotionProperties = mp;
  214. body->mBodyType = EBodyType::SoftBody;
  215. body->mMotionProperties = mp;
  216. body->mShape = shape;
  217. body->mUserData = inSoftBodyCreationSettings.mUserData;
  218. body->SetFriction(inSoftBodyCreationSettings.mFriction);
  219. body->SetRestitution(inSoftBodyCreationSettings.mRestitution);
  220. body->mMotionType = EMotionType::Dynamic;
  221. SetBodyObjectLayerInternal(*body, inSoftBodyCreationSettings.mObjectLayer);
  222. body->mObjectLayer = inSoftBodyCreationSettings.mObjectLayer;
  223. body->mCollisionGroup = inSoftBodyCreationSettings.mCollisionGroup;
  224. mp->SetLinearDamping(inSoftBodyCreationSettings.mLinearDamping);
  225. mp->SetAngularDamping(0);
  226. mp->SetMaxLinearVelocity(inSoftBodyCreationSettings.mMaxLinearVelocity);
  227. mp->SetMaxAngularVelocity(FLT_MAX);
  228. mp->SetLinearVelocity(Vec3::sZero());
  229. mp->SetAngularVelocity(Vec3::sZero());
  230. mp->SetGravityFactor(inSoftBodyCreationSettings.mGravityFactor);
  231. mp->mMotionQuality = EMotionQuality::Discrete;
  232. mp->mAllowSleeping = inSoftBodyCreationSettings.mAllowSleeping;
  233. JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)
  234. JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)
  235. mp->Initialize(inSoftBodyCreationSettings);
  236. body->SetPositionAndRotationInternal(inSoftBodyCreationSettings.mPosition, inSoftBodyCreationSettings.mMakeRotationIdentity? Quat::sIdentity() : inSoftBodyCreationSettings.mRotation);
  237. return body;
  238. }
  239. void BodyManager::FreeBody(Body *inBody) const
  240. {
  241. JPH_ASSERT(inBody->GetID().IsInvalid(), "This function should only be called on a body that doesn't have an ID yet, use DestroyBody otherwise");
  242. sDeleteBody(inBody);
  243. }
  244. bool BodyManager::AddBody(Body *ioBody)
  245. {
  246. // Return error when body was already added
  247. if (!ioBody->GetID().IsInvalid())
  248. return false;
  249. // Determine next free index
  250. uint32 idx;
  251. {
  252. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  253. if (mBodyIDFreeListStart != cBodyIDFreeListEnd)
  254. {
  255. // Pop an item from the freelist
  256. JPH_ASSERT(mBodyIDFreeListStart & cIsFreedBody);
  257. idx = uint32(mBodyIDFreeListStart >> cFreedBodyIndexShift);
  258. JPH_ASSERT(!sIsValidBodyPointer(mBodies[idx]));
  259. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  260. mBodies[idx] = ioBody;
  261. }
  262. else
  263. {
  264. if (mBodies.size() < mBodies.capacity())
  265. {
  266. // Allocate a new entry, note that the array should not actually resize since we've reserved it at init time
  267. idx = uint32(mBodies.size());
  268. mBodies.push_back(ioBody);
  269. }
  270. else
  271. {
  272. // Out of bodies
  273. return false;
  274. }
  275. }
  276. // Update cached number of bodies
  277. mNumBodies++;
  278. }
  279. // Get next sequence number and assign the ID
  280. uint8 seq_no = GetNextSequenceNumber(idx);
  281. ioBody->mID = BodyID(idx, seq_no);
  282. return true;
  283. }
  284. bool BodyManager::AddBodyWithCustomID(Body *ioBody, const BodyID &inBodyID)
  285. {
  286. // Return error when body was already added
  287. if (!ioBody->GetID().IsInvalid())
  288. return false;
  289. {
  290. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  291. // Check if index is beyond the max body ID
  292. uint32 idx = inBodyID.GetIndex();
  293. if (idx >= mBodies.capacity())
  294. return false; // Return error
  295. if (idx < mBodies.size())
  296. {
  297. // Body array entry has already been allocated, check if there's a free body here
  298. if (sIsValidBodyPointer(mBodies[idx]))
  299. return false; // Return error
  300. // Remove the entry from the freelist
  301. uintptr_t idx_start = mBodyIDFreeListStart >> cFreedBodyIndexShift;
  302. if (idx == idx_start)
  303. {
  304. // First entry, easy to remove, the start of the list is our next
  305. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  306. }
  307. else
  308. {
  309. // Loop over the freelist and find the entry in the freelist pointing to our index
  310. // TODO: This is O(N), see if this becomes a performance problem (don't want to put the freed bodies in a double linked list)
  311. uintptr_t cur, next;
  312. for (cur = idx_start; cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift; cur = next)
  313. {
  314. next = uintptr_t(mBodies[cur]) >> cFreedBodyIndexShift;
  315. if (next == idx)
  316. {
  317. mBodies[cur] = mBodies[idx];
  318. break;
  319. }
  320. }
  321. JPH_ASSERT(cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift);
  322. }
  323. // Put the body in the slot
  324. mBodies[idx] = ioBody;
  325. }
  326. else
  327. {
  328. // Ensure that all body IDs up to this body ID have been allocated and added to the free list
  329. while (idx > mBodies.size())
  330. {
  331. // Push the id onto the freelist
  332. mBodies.push_back((Body *)mBodyIDFreeListStart);
  333. mBodyIDFreeListStart = (uintptr_t(mBodies.size() - 1) << cFreedBodyIndexShift) | cIsFreedBody;
  334. }
  335. // Add the element to the list
  336. mBodies.push_back(ioBody);
  337. }
  338. // Update cached number of bodies
  339. mNumBodies++;
  340. }
  341. // Assign the ID
  342. ioBody->mID = inBodyID;
  343. return true;
  344. }
  345. Body *BodyManager::RemoveBodyInternal(const BodyID &inBodyID)
  346. {
  347. // Get body
  348. uint32 idx = inBodyID.GetIndex();
  349. Body *body = mBodies[idx];
  350. // Validate that it can be removed
  351. JPH_ASSERT(body->GetID() == inBodyID);
  352. JPH_ASSERT(!body->IsActive());
  353. JPH_ASSERT(!body->IsInBroadPhase(), "Use BodyInterface::RemoveBody to remove this body first!");
  354. // Push the id onto the freelist
  355. mBodies[idx] = (Body *)mBodyIDFreeListStart;
  356. mBodyIDFreeListStart = (uintptr_t(idx) << cFreedBodyIndexShift) | cIsFreedBody;
  357. return body;
  358. }
  359. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  360. void BodyManager::ValidateFreeList() const
  361. {
  362. // Check that the freelist is correct
  363. size_t num_freed = 0;
  364. for (uintptr_t start = mBodyIDFreeListStart; start != cBodyIDFreeListEnd; start = uintptr_t(mBodies[start >> cFreedBodyIndexShift]))
  365. {
  366. JPH_ASSERT(start & cIsFreedBody);
  367. num_freed++;
  368. }
  369. JPH_ASSERT(mNumBodies == mBodies.size() - num_freed);
  370. }
  371. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  372. void BodyManager::RemoveBodies(const BodyID *inBodyIDs, int inNumber, Body **outBodies)
  373. {
  374. // Don't take lock if no bodies are to be destroyed
  375. if (inNumber <= 0)
  376. return;
  377. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  378. // Update cached number of bodies
  379. JPH_ASSERT(mNumBodies >= (uint)inNumber);
  380. mNumBodies -= inNumber;
  381. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  382. {
  383. // Remove body
  384. Body *body = RemoveBodyInternal(*b);
  385. // Clear the ID
  386. body->mID = BodyID();
  387. // Return the body to the caller
  388. if (outBodies != nullptr)
  389. {
  390. *outBodies = body;
  391. ++outBodies;
  392. }
  393. }
  394. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  395. ValidateFreeList();
  396. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  397. }
  398. void BodyManager::DestroyBodies(const BodyID *inBodyIDs, int inNumber)
  399. {
  400. // Don't take lock if no bodies are to be destroyed
  401. if (inNumber <= 0)
  402. return;
  403. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  404. // Update cached number of bodies
  405. JPH_ASSERT(mNumBodies >= (uint)inNumber);
  406. mNumBodies -= inNumber;
  407. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  408. {
  409. // Remove body
  410. Body *body = RemoveBodyInternal(*b);
  411. // Free the body
  412. sDeleteBody(body);
  413. }
  414. #if defined(JPH_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  415. ValidateFreeList();
  416. #endif // defined(JPH_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  417. }
  418. void BodyManager::AddBodyToActiveBodies(Body &ioBody)
  419. {
  420. // Select the correct array to use
  421. int type = (int)ioBody.GetBodyType();
  422. atomic<uint32> &num_active_bodies = mNumActiveBodies[type];
  423. BodyID *active_bodies = mActiveBodies[type];
  424. MotionProperties *mp = ioBody.mMotionProperties;
  425. uint32 num_active_bodies_val = num_active_bodies.load(memory_order_relaxed);
  426. mp->mIndexInActiveBodies = num_active_bodies_val;
  427. JPH_ASSERT(num_active_bodies_val < GetMaxBodies());
  428. active_bodies[num_active_bodies_val] = ioBody.GetID();
  429. num_active_bodies.fetch_add(1, memory_order_release); // Increment atomic after setting the body ID so that PhysicsSystem::JobFindCollisions (which doesn't lock the mActiveBodiesMutex) will only read valid IDs
  430. // Count CCD bodies
  431. if (mp->GetMotionQuality() == EMotionQuality::LinearCast)
  432. mNumActiveCCDBodies++;
  433. }
  434. void BodyManager::RemoveBodyFromActiveBodies(Body &ioBody)
  435. {
  436. // Select the correct array to use
  437. int type = (int)ioBody.GetBodyType();
  438. atomic<uint32> &num_active_bodies = mNumActiveBodies[type];
  439. BodyID *active_bodies = mActiveBodies[type];
  440. uint32 last_body_index = num_active_bodies.load(memory_order_relaxed) - 1;
  441. MotionProperties *mp = ioBody.mMotionProperties;
  442. if (mp->mIndexInActiveBodies != last_body_index)
  443. {
  444. // This is not the last body, use the last body to fill the hole
  445. BodyID last_body_id = active_bodies[last_body_index];
  446. active_bodies[mp->mIndexInActiveBodies] = last_body_id;
  447. // Update that body's index in the active list
  448. Body &last_body = *mBodies[last_body_id.GetIndex()];
  449. JPH_ASSERT(last_body.mMotionProperties->mIndexInActiveBodies == last_body_index);
  450. last_body.mMotionProperties->mIndexInActiveBodies = mp->mIndexInActiveBodies;
  451. }
  452. // Mark this body as no longer active
  453. mp->mIndexInActiveBodies = Body::cInactiveIndex;
  454. // Remove unused element from active bodies list
  455. num_active_bodies.fetch_sub(1, memory_order_release);
  456. // Count CCD bodies
  457. if (mp->GetMotionQuality() == EMotionQuality::LinearCast)
  458. mNumActiveCCDBodies--;
  459. }
  460. void BodyManager::ActivateBodies(const BodyID *inBodyIDs, int inNumber)
  461. {
  462. // Don't take lock if no bodies are to be activated
  463. if (inNumber <= 0)
  464. return;
  465. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  466. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowActivation);
  467. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  468. if (!b->IsInvalid())
  469. {
  470. BodyID body_id = *b;
  471. Body &body = *mBodies[body_id.GetIndex()];
  472. JPH_ASSERT(body.GetID() == body_id);
  473. JPH_ASSERT(body.IsInBroadPhase(), "Use BodyInterface::AddBody to add the body first!");
  474. if (!body.IsStatic())
  475. {
  476. // Reset sleeping timer so that we don't immediately go to sleep again
  477. body.ResetSleepTimer();
  478. // Check if we're sleeping
  479. if (body.mMotionProperties->mIndexInActiveBodies == Body::cInactiveIndex)
  480. {
  481. AddBodyToActiveBodies(body);
  482. // Call activation listener
  483. if (mActivationListener != nullptr)
  484. mActivationListener->OnBodyActivated(body_id, body.GetUserData());
  485. }
  486. }
  487. }
  488. }
  489. void BodyManager::DeactivateBodies(const BodyID *inBodyIDs, int inNumber)
  490. {
  491. // Don't take lock if no bodies are to be deactivated
  492. if (inNumber <= 0)
  493. return;
  494. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  495. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowDeactivation);
  496. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  497. if (!b->IsInvalid())
  498. {
  499. BodyID body_id = *b;
  500. Body &body = *mBodies[body_id.GetIndex()];
  501. JPH_ASSERT(body.GetID() == body_id);
  502. JPH_ASSERT(body.IsInBroadPhase(), "Use BodyInterface::AddBody to add the body first!");
  503. if (body.mMotionProperties != nullptr
  504. && body.mMotionProperties->mIndexInActiveBodies != Body::cInactiveIndex)
  505. {
  506. // Remove the body from the active bodies list
  507. RemoveBodyFromActiveBodies(body);
  508. // Mark this body as no longer active
  509. body.mMotionProperties->mIslandIndex = Body::cInactiveIndex;
  510. // Reset velocity
  511. body.mMotionProperties->mLinearVelocity = Vec3::sZero();
  512. body.mMotionProperties->mAngularVelocity = Vec3::sZero();
  513. // Call activation listener
  514. if (mActivationListener != nullptr)
  515. mActivationListener->OnBodyDeactivated(body_id, body.GetUserData());
  516. }
  517. }
  518. }
  519. void BodyManager::SetMotionQuality(Body &ioBody, EMotionQuality inMotionQuality)
  520. {
  521. MotionProperties *mp = ioBody.GetMotionPropertiesUnchecked();
  522. if (mp != nullptr && mp->GetMotionQuality() != inMotionQuality)
  523. {
  524. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  525. JPH_ASSERT(!mActiveBodiesLocked);
  526. bool is_active = ioBody.IsActive();
  527. if (is_active && mp->GetMotionQuality() == EMotionQuality::LinearCast)
  528. --mNumActiveCCDBodies;
  529. mp->mMotionQuality = inMotionQuality;
  530. if (is_active && mp->GetMotionQuality() == EMotionQuality::LinearCast)
  531. ++mNumActiveCCDBodies;
  532. }
  533. }
  534. void BodyManager::GetActiveBodies(EBodyType inType, BodyIDVector &outBodyIDs) const
  535. {
  536. JPH_PROFILE_FUNCTION();
  537. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  538. const BodyID *active_bodies = mActiveBodies[(int)inType];
  539. outBodyIDs.assign(active_bodies, active_bodies + mNumActiveBodies[(int)inType].load(memory_order_relaxed));
  540. }
  541. void BodyManager::GetBodyIDs(BodyIDVector &outBodies) const
  542. {
  543. JPH_PROFILE_FUNCTION();
  544. UniqueLock lock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  545. // Reserve space for all bodies
  546. outBodies.clear();
  547. outBodies.reserve(mNumBodies);
  548. // Iterate the list and find the bodies that are not null
  549. for (const Body *b : mBodies)
  550. if (sIsValidBodyPointer(b))
  551. outBodies.push_back(b->GetID());
  552. // Validate that our reservation was correct
  553. JPH_ASSERT(outBodies.size() == mNumBodies);
  554. }
  555. void BodyManager::SetBodyActivationListener(BodyActivationListener *inListener)
  556. {
  557. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  558. mActivationListener = inListener;
  559. }
  560. BodyManager::MutexMask BodyManager::GetMutexMask(const BodyID *inBodies, int inNumber) const
  561. {
  562. JPH_ASSERT(sizeof(MutexMask) * 8 >= mBodyMutexes.GetNumMutexes(), "MutexMask must have enough bits");
  563. if (inNumber >= (int)mBodyMutexes.GetNumMutexes())
  564. {
  565. // Just lock everything if there are too many bodies
  566. return GetAllBodiesMutexMask();
  567. }
  568. else
  569. {
  570. MutexMask mask = 0;
  571. for (const BodyID *b = inBodies, *b_end = inBodies + inNumber; b < b_end; ++b)
  572. if (!b->IsInvalid())
  573. {
  574. uint32 index = mBodyMutexes.GetMutexIndex(b->GetIndex());
  575. mask |= (MutexMask(1) << index);
  576. }
  577. return mask;
  578. }
  579. }
  580. void BodyManager::LockRead(MutexMask inMutexMask) const
  581. {
  582. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  583. int index = 0;
  584. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  585. if (mask & 1)
  586. mBodyMutexes.GetMutexByIndex(index).lock_shared();
  587. }
  588. void BodyManager::UnlockRead(MutexMask inMutexMask) const
  589. {
  590. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  591. int index = 0;
  592. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  593. if (mask & 1)
  594. mBodyMutexes.GetMutexByIndex(index).unlock_shared();
  595. }
  596. void BodyManager::LockWrite(MutexMask inMutexMask) const
  597. {
  598. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  599. int index = 0;
  600. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  601. if (mask & 1)
  602. mBodyMutexes.GetMutexByIndex(index).lock();
  603. }
  604. void BodyManager::UnlockWrite(MutexMask inMutexMask) const
  605. {
  606. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  607. int index = 0;
  608. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  609. if (mask & 1)
  610. mBodyMutexes.GetMutexByIndex(index).unlock();
  611. }
  612. void BodyManager::LockAllBodies() const
  613. {
  614. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(this, EPhysicsLockTypes::PerBody));
  615. mBodyMutexes.LockAll();
  616. PhysicsLock::sLock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  617. }
  618. void BodyManager::UnlockAllBodies() const
  619. {
  620. PhysicsLock::sUnlock(mBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::BodiesList));
  621. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(this, EPhysicsLockTypes::PerBody));
  622. mBodyMutexes.UnlockAll();
  623. }
  624. void BodyManager::SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const
  625. {
  626. {
  627. LockAllBodies();
  628. // Determine which bodies to save
  629. Array<const Body *> bodies;
  630. bodies.reserve(mNumBodies);
  631. for (const Body *b : mBodies)
  632. if (sIsValidBodyPointer(b) && b->IsInBroadPhase() && (inFilter == nullptr || inFilter->ShouldSaveBody(*b)))
  633. bodies.push_back(b);
  634. // Write state of bodies
  635. uint32 num_bodies = (uint32)bodies.size();
  636. inStream.Write(num_bodies);
  637. for (const Body *b : bodies)
  638. {
  639. inStream.Write(b->GetID());
  640. inStream.Write(b->IsActive());
  641. b->SaveState(inStream);
  642. }
  643. UnlockAllBodies();
  644. }
  645. }
  646. bool BodyManager::RestoreState(StateRecorder &inStream)
  647. {
  648. BodyIDVector bodies_to_activate, bodies_to_deactivate;
  649. {
  650. LockAllBodies();
  651. if (inStream.IsValidating())
  652. {
  653. // Read state of bodies, note this reads it in a way to be consistent with validation
  654. uint32 old_num_bodies = 0;
  655. for (const Body *b : mBodies)
  656. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  657. ++old_num_bodies;
  658. uint32 num_bodies = old_num_bodies; // Initialize to current value for validation
  659. inStream.Read(num_bodies);
  660. if (num_bodies != old_num_bodies)
  661. {
  662. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  663. UnlockAllBodies();
  664. return false;
  665. }
  666. for (Body *b : mBodies)
  667. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  668. {
  669. BodyID body_id = b->GetID(); // Initialize to current value for validation
  670. inStream.Read(body_id);
  671. if (body_id != b->GetID())
  672. {
  673. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  674. UnlockAllBodies();
  675. return false;
  676. }
  677. bool is_active = b->IsActive(); // Initialize to current value for validation
  678. inStream.Read(is_active);
  679. if (is_active != b->IsActive())
  680. {
  681. if (is_active)
  682. bodies_to_activate.push_back(body_id);
  683. else
  684. bodies_to_deactivate.push_back(body_id);
  685. }
  686. b->RestoreState(inStream);
  687. }
  688. }
  689. else
  690. {
  691. // Not validating, we can be a bit more loose, read number of bodies
  692. uint32 num_bodies = 0;
  693. inStream.Read(num_bodies);
  694. // Iterate over the stored bodies and restore their state
  695. for (uint32 idx = 0; idx < num_bodies; ++idx)
  696. {
  697. BodyID body_id;
  698. inStream.Read(body_id);
  699. Body *b = TryGetBody(body_id);
  700. if (b == nullptr)
  701. {
  702. JPH_ASSERT(false, "Restoring state for non-existing body");
  703. UnlockAllBodies();
  704. return false;
  705. }
  706. bool is_active;
  707. inStream.Read(is_active);
  708. if (is_active != b->IsActive())
  709. {
  710. if (is_active)
  711. bodies_to_activate.push_back(body_id);
  712. else
  713. bodies_to_deactivate.push_back(body_id);
  714. }
  715. b->RestoreState(inStream);
  716. }
  717. }
  718. UnlockAllBodies();
  719. }
  720. {
  721. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  722. for (BodyID body_id : bodies_to_activate)
  723. {
  724. Body *body = TryGetBody(body_id);
  725. AddBodyToActiveBodies(*body);
  726. }
  727. for (BodyID body_id : bodies_to_deactivate)
  728. {
  729. Body *body = TryGetBody(body_id);
  730. RemoveBodyFromActiveBodies(*body);
  731. }
  732. }
  733. return true;
  734. }
  735. void BodyManager::SaveBodyState(const Body &inBody, StateRecorder &inStream) const
  736. {
  737. inStream.Write(inBody.IsActive());
  738. inBody.SaveState(inStream);
  739. }
  740. void BodyManager::RestoreBodyState(Body &ioBody, StateRecorder &inStream)
  741. {
  742. bool is_active = ioBody.IsActive();
  743. inStream.Read(is_active);
  744. ioBody.RestoreState(inStream);
  745. if (is_active != ioBody.IsActive())
  746. {
  747. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  748. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowActivation);
  749. if (is_active)
  750. AddBodyToActiveBodies(ioBody);
  751. else
  752. RemoveBodyFromActiveBodies(ioBody);
  753. }
  754. }
  755. #ifdef JPH_DEBUG_RENDERER
  756. void BodyManager::Draw(const DrawSettings &inDrawSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter)
  757. {
  758. JPH_PROFILE_FUNCTION();
  759. LockAllBodies();
  760. for (const Body *body : mBodies)
  761. if (sIsValidBodyPointer(body) && body->IsInBroadPhase() && (!inBodyFilter || inBodyFilter->ShouldDraw(*body)))
  762. {
  763. JPH_ASSERT(mBodies[body->GetID().GetIndex()] == body);
  764. bool is_sensor = body->IsSensor();
  765. // Determine drawing mode
  766. Color color;
  767. if (is_sensor)
  768. color = Color::sYellow;
  769. else
  770. switch (inDrawSettings.mDrawShapeColor)
  771. {
  772. case EShapeColor::InstanceColor:
  773. // Each instance has own color
  774. color = Color::sGetDistinctColor(body->mID.GetIndex());
  775. break;
  776. case EShapeColor::ShapeTypeColor:
  777. color = ShapeFunctions::sGet(body->GetShape()->GetSubType()).mColor;
  778. break;
  779. case EShapeColor::MotionTypeColor:
  780. // Determine color based on motion type
  781. switch (body->mMotionType)
  782. {
  783. case EMotionType::Static:
  784. color = Color::sGrey;
  785. break;
  786. case EMotionType::Kinematic:
  787. color = Color::sGreen;
  788. break;
  789. case EMotionType::Dynamic:
  790. color = Color::sGetDistinctColor(body->mID.GetIndex());
  791. break;
  792. default:
  793. JPH_ASSERT(false);
  794. color = Color::sBlack;
  795. break;
  796. }
  797. break;
  798. case EShapeColor::SleepColor:
  799. // Determine color based on motion type
  800. switch (body->mMotionType)
  801. {
  802. case EMotionType::Static:
  803. color = Color::sGrey;
  804. break;
  805. case EMotionType::Kinematic:
  806. color = body->IsActive()? Color::sGreen : Color::sRed;
  807. break;
  808. case EMotionType::Dynamic:
  809. color = body->IsActive()? Color::sYellow : Color::sRed;
  810. break;
  811. default:
  812. JPH_ASSERT(false);
  813. color = Color::sBlack;
  814. break;
  815. }
  816. break;
  817. case EShapeColor::IslandColor:
  818. // Determine color based on motion type
  819. switch (body->mMotionType)
  820. {
  821. case EMotionType::Static:
  822. color = Color::sGrey;
  823. break;
  824. case EMotionType::Kinematic:
  825. case EMotionType::Dynamic:
  826. {
  827. uint32 idx = body->GetMotionProperties()->GetIslandIndexInternal();
  828. color = idx != Body::cInactiveIndex? Color::sGetDistinctColor(idx) : Color::sLightGrey;
  829. }
  830. break;
  831. default:
  832. JPH_ASSERT(false);
  833. color = Color::sBlack;
  834. break;
  835. }
  836. break;
  837. case EShapeColor::MaterialColor:
  838. color = Color::sWhite;
  839. break;
  840. default:
  841. JPH_ASSERT(false);
  842. color = Color::sBlack;
  843. break;
  844. }
  845. // Draw the results of GetSupportFunction
  846. if (inDrawSettings.mDrawGetSupportFunction)
  847. body->mShape->DrawGetSupportFunction(inRenderer, body->GetCenterOfMassTransform(), Vec3::sOne(), color, inDrawSettings.mDrawSupportDirection);
  848. // Draw the results of GetSupportingFace
  849. if (inDrawSettings.mDrawGetSupportingFace)
  850. body->mShape->DrawGetSupportingFace(inRenderer, body->GetCenterOfMassTransform(), Vec3::sOne());
  851. // Draw the shape
  852. if (inDrawSettings.mDrawShape)
  853. body->mShape->Draw(inRenderer, body->GetCenterOfMassTransform(), Vec3::sOne(), color, inDrawSettings.mDrawShapeColor == EShapeColor::MaterialColor, inDrawSettings.mDrawShapeWireframe || is_sensor);
  854. // Draw bounding box
  855. if (inDrawSettings.mDrawBoundingBox)
  856. inRenderer->DrawWireBox(body->mBounds, color);
  857. // Draw center of mass transform
  858. if (inDrawSettings.mDrawCenterOfMassTransform)
  859. inRenderer->DrawCoordinateSystem(body->GetCenterOfMassTransform(), 0.2f);
  860. // Draw world transform
  861. if (inDrawSettings.mDrawWorldTransform)
  862. inRenderer->DrawCoordinateSystem(body->GetWorldTransform(), 0.2f);
  863. // Draw world space linear and angular velocity
  864. if (inDrawSettings.mDrawVelocity)
  865. {
  866. RVec3 pos = body->GetCenterOfMassPosition();
  867. inRenderer->DrawArrow(pos, pos + body->GetLinearVelocity(), Color::sGreen, 0.1f);
  868. inRenderer->DrawArrow(pos, pos + body->GetAngularVelocity(), Color::sRed, 0.1f);
  869. }
  870. if (inDrawSettings.mDrawMassAndInertia && body->IsDynamic())
  871. {
  872. const MotionProperties *mp = body->GetMotionProperties();
  873. if (mp->GetInverseMass() > 0.0f
  874. && !Vec3::sEquals(mp->GetInverseInertiaDiagonal(), Vec3::sZero()).TestAnyXYZTrue())
  875. {
  876. // Invert mass again
  877. float mass = 1.0f / mp->GetInverseMass();
  878. // Invert diagonal again
  879. Vec3 diagonal = mp->GetInverseInertiaDiagonal().Reciprocal();
  880. // Determine how big of a box has the equivalent inertia
  881. Vec3 box_size = MassProperties::sGetEquivalentSolidBoxSize(mass, diagonal);
  882. // Draw box with equivalent inertia
  883. inRenderer->DrawWireBox(body->GetCenterOfMassTransform() * Mat44::sRotation(mp->GetInertiaRotation()), AABox(-0.5f * box_size, 0.5f * box_size), Color::sOrange);
  884. // Draw mass
  885. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), StringFormat("%.2f", (double)mass), Color::sOrange, 0.2f);
  886. }
  887. }
  888. if (inDrawSettings.mDrawSleepStats && body->IsDynamic() && body->IsActive())
  889. {
  890. // Draw stats to know which bodies could go to sleep
  891. String text = StringFormat("t: %.1f", (double)body->mMotionProperties->mSleepTestTimer);
  892. uint8 g = uint8(Clamp(255.0f * body->mMotionProperties->mSleepTestTimer / inPhysicsSettings.mTimeBeforeSleep, 0.0f, 255.0f));
  893. Color sleep_color = Color(0, 255 - g, g);
  894. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), text, sleep_color, 0.2f);
  895. for (int i = 0; i < 3; ++i)
  896. inRenderer->DrawWireSphere(JPH_IF_DOUBLE_PRECISION(body->mMotionProperties->GetSleepTestOffset() +) body->mMotionProperties->mSleepTestSpheres[i].GetCenter(), body->mMotionProperties->mSleepTestSpheres[i].GetRadius(), sleep_color);
  897. }
  898. if (body->IsSoftBody())
  899. {
  900. const SoftBodyMotionProperties *mp = static_cast<const SoftBodyMotionProperties *>(body->GetMotionProperties());
  901. RMat44 com = body->GetCenterOfMassTransform();
  902. if (inDrawSettings.mDrawSoftBodyVertices)
  903. mp->DrawVertices(inRenderer, com);
  904. if (inDrawSettings.mDrawSoftBodyVertexVelocities)
  905. mp->DrawVertexVelocities(inRenderer, com);
  906. if (inDrawSettings.mDrawSoftBodyEdgeConstraints)
  907. mp->DrawEdgeConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  908. if (inDrawSettings.mDrawSoftBodyRods)
  909. mp->DrawRods(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  910. if (inDrawSettings.mDrawSoftBodyRodStates)
  911. mp->DrawRodStates(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  912. if (inDrawSettings.mDrawSoftBodyRodBendTwistConstraints)
  913. mp->DrawRodBendTwistConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  914. if (inDrawSettings.mDrawSoftBodyBendConstraints)
  915. mp->DrawBendConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  916. if (inDrawSettings.mDrawSoftBodyVolumeConstraints)
  917. mp->DrawVolumeConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  918. if (inDrawSettings.mDrawSoftBodySkinConstraints)
  919. mp->DrawSkinConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  920. if (inDrawSettings.mDrawSoftBodyLRAConstraints)
  921. mp->DrawLRAConstraints(inRenderer, com, inDrawSettings.mDrawSoftBodyConstraintColor);
  922. if (inDrawSettings.mDrawSoftBodyPredictedBounds)
  923. mp->DrawPredictedBounds(inRenderer, com);
  924. }
  925. }
  926. UnlockAllBodies();
  927. }
  928. #endif // JPH_DEBUG_RENDERER
  929. void BodyManager::InvalidateContactCacheForBody(Body &ioBody)
  930. {
  931. // If this is the first time we flip the collision cache invalid flag, we need to add it to an internal list to ensure we reset the flag at the end of the physics update
  932. if (ioBody.InvalidateContactCacheInternal())
  933. {
  934. lock_guard lock(mBodiesCacheInvalidMutex);
  935. mBodiesCacheInvalid.push_back(ioBody.GetID());
  936. }
  937. }
  938. void BodyManager::ValidateContactCacheForAllBodies()
  939. {
  940. lock_guard lock(mBodiesCacheInvalidMutex);
  941. for (const BodyID &b : mBodiesCacheInvalid)
  942. {
  943. // The body may have been removed between the call to InvalidateContactCacheForBody and this call, so check if it still exists
  944. Body *body = TryGetBody(b);
  945. if (body != nullptr)
  946. body->ValidateContactCacheInternal();
  947. }
  948. mBodiesCacheInvalid.clear();
  949. }
  950. #ifdef JPH_DEBUG
  951. void BodyManager::ValidateActiveBodyBounds()
  952. {
  953. UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));
  954. for (uint type = 0; type < cBodyTypeCount; ++type)
  955. for (BodyID *id = mActiveBodies[type], *id_end = mActiveBodies[type] + mNumActiveBodies[type].load(memory_order_relaxed); id < id_end; ++id)
  956. {
  957. const Body *body = mBodies[id->GetIndex()];
  958. body->ValidateCachedBounds();
  959. }
  960. }
  961. #endif // JPH_DEBUG
  962. JPH_NAMESPACE_END