BodyManager.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/PhysicsSettings.h>
  5. #include <Jolt/Physics/Body/BodyManager.h>
  6. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  7. #include <Jolt/Physics/Body/BodyLock.h>
  8. #include <Jolt/Physics/Body/BodyActivationListener.h>
  9. #include <Jolt/Physics/StateRecorder.h>
  10. #include <Jolt/Core/StringTools.h>
  11. #include <Jolt/Core/QuickSort.h>
  12. #ifdef JPH_DEBUG_RENDERER
  13. #include <Jolt/Renderer/DebugRenderer.h>
  14. #include <Jolt/Physics/Body/BodyFilter.h>
  15. #endif // JPH_DEBUG_RENDERER
  16. JPH_NAMESPACE_BEGIN
  17. #ifdef JPH_ENABLE_ASSERTS
  18. thread_local bool BodyManager::sOverrideAllowActivation = false;
  19. thread_local bool BodyManager::sOverrideAllowDeactivation = false;
  20. #endif
  21. // Helper class that combines a body and its motion properties
  22. class BodyWithMotionProperties : public Body
  23. {
  24. public:
  25. JPH_OVERRIDE_NEW_DELETE
  26. MotionProperties mMotionProperties;
  27. };
  28. inline void BodyManager::sDeleteBody(Body *inBody)
  29. {
  30. if (inBody->mMotionProperties != nullptr)
  31. {
  32. JPH_IF_ENABLE_ASSERTS(inBody->mMotionProperties = nullptr;)
  33. delete static_cast<BodyWithMotionProperties *>(inBody);
  34. }
  35. else
  36. delete inBody;
  37. }
  38. BodyManager::~BodyManager()
  39. {
  40. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  41. // Destroy any bodies that are still alive
  42. for (Body *b : mBodies)
  43. if (sIsValidBodyPointer(b))
  44. sDeleteBody(b);
  45. delete [] mActiveBodies;
  46. }
  47. void BodyManager::Init(uint inMaxBodies, uint inNumBodyMutexes, const BroadPhaseLayerInterface &inLayerInterface)
  48. {
  49. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  50. // Num body mutexes must be a power of two and not bigger than our MutexMask
  51. uint num_body_mutexes = Clamp<uint>(GetNextPowerOf2(inNumBodyMutexes == 0? 2 * thread::hardware_concurrency() : inNumBodyMutexes), 1, sizeof(MutexMask) * 8);
  52. // Allocate the body mutexes
  53. mBodyMutexes.Init(num_body_mutexes);
  54. // Allocate space for bodies
  55. mBodies.reserve(inMaxBodies);
  56. // Allocate space for active bodies
  57. JPH_ASSERT(mActiveBodies == nullptr);
  58. mActiveBodies = new BodyID [inMaxBodies];
  59. // Allocate space for sequence numbers
  60. mBodySequenceNumbers.resize(inMaxBodies);
  61. // Keep layer interface
  62. mBroadPhaseLayerInterface = &inLayerInterface;
  63. }
  64. uint BodyManager::GetNumBodies() const
  65. {
  66. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  67. return mNumBodies;
  68. }
  69. BodyManager::BodyStats BodyManager::GetBodyStats() const
  70. {
  71. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  72. BodyStats stats;
  73. stats.mNumBodies = mNumBodies;
  74. stats.mMaxBodies = uint(mBodies.capacity());
  75. for (const Body *body : mBodies)
  76. if (sIsValidBodyPointer(body))
  77. {
  78. switch (body->GetMotionType())
  79. {
  80. case EMotionType::Static:
  81. stats.mNumBodiesStatic++;
  82. break;
  83. case EMotionType::Dynamic:
  84. stats.mNumBodiesDynamic++;
  85. if (body->IsActive())
  86. stats.mNumActiveBodiesDynamic++;
  87. break;
  88. case EMotionType::Kinematic:
  89. stats.mNumBodiesKinematic++;
  90. if (body->IsActive())
  91. stats.mNumActiveBodiesKinematic++;
  92. break;
  93. }
  94. }
  95. return stats;
  96. }
  97. Body *BodyManager::CreateBody(const BodyCreationSettings &inBodyCreationSettings)
  98. {
  99. // Determine next free index
  100. uint32 idx;
  101. {
  102. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  103. if (mBodyIDFreeListStart != cBodyIDFreeListEnd)
  104. {
  105. // Pop an item from the freelist
  106. JPH_ASSERT(mBodyIDFreeListStart & cIsFreedBody);
  107. idx = uint32(mBodyIDFreeListStart >> cFreedBodyIndexShift);
  108. JPH_ASSERT(!sIsValidBodyPointer(mBodies[idx]));
  109. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  110. }
  111. else
  112. {
  113. if (mBodies.size() < mBodies.capacity())
  114. {
  115. // Allocate a new entry, note that the array should not actually resize since we've reserved it at init time
  116. idx = uint32(mBodies.size());
  117. mBodies.push_back((Body *)cBodyIDFreeListEnd);
  118. }
  119. else
  120. {
  121. // Out of bodies
  122. return nullptr;
  123. }
  124. }
  125. // Update cached number of bodies
  126. mNumBodies++;
  127. }
  128. // Get next sequence number
  129. uint8 seq_no = GetNextSequenceNumber(idx);
  130. // Do actual creation
  131. return CreateBodyWithIDInternal(BodyID(idx, seq_no), inBodyCreationSettings);
  132. }
  133. Body *BodyManager::CreateBodyWithID(const BodyID &inBodyID, const BodyCreationSettings &inBodyCreationSettings)
  134. {
  135. {
  136. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  137. // Check if index is beyond the max body ID
  138. uint32 idx = inBodyID.GetIndex();
  139. if (idx >= mBodies.capacity())
  140. return nullptr; // Return error
  141. if (idx < mBodies.size())
  142. {
  143. // Body array entry has already been allocated, check if there's a free body here
  144. if (sIsValidBodyPointer(mBodies[idx]))
  145. return nullptr; // Return error
  146. // Remove the entry from the freelist
  147. uintptr_t idx_start = mBodyIDFreeListStart >> cFreedBodyIndexShift;
  148. if (idx == idx_start)
  149. {
  150. // First entry, easy to remove, the start of the list is our next
  151. mBodyIDFreeListStart = uintptr_t(mBodies[idx]);
  152. }
  153. else
  154. {
  155. // Loop over the freelist and find the entry in the freelist pointing to our index
  156. // 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)
  157. uintptr_t cur, next;
  158. for (cur = idx_start; cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift; cur = next)
  159. {
  160. next = uintptr_t(mBodies[cur]) >> cFreedBodyIndexShift;
  161. if (next == idx)
  162. {
  163. mBodies[cur] = mBodies[idx];
  164. break;
  165. }
  166. }
  167. JPH_ASSERT(cur != cBodyIDFreeListEnd >> cFreedBodyIndexShift);
  168. // We're leaving the lock, ensure that we've overwritten this entry (although it's not strictly needed)
  169. mBodies[idx] = (Body *)cBodyIDFreeListEnd;
  170. }
  171. }
  172. else
  173. {
  174. // Ensure that all body IDs up to this body ID have been allocated and added to the free list
  175. while (idx > mBodies.size())
  176. {
  177. // Push the id onto the freelist
  178. mBodies.push_back((Body *)mBodyIDFreeListStart);
  179. mBodyIDFreeListStart = (uintptr_t(mBodies.size() - 1) << cFreedBodyIndexShift) | cIsFreedBody;
  180. }
  181. // Add the element that we're going to overwrite to the list
  182. mBodies.push_back((Body *)cBodyIDFreeListEnd);
  183. }
  184. // Update cached number of bodies
  185. mNumBodies++;
  186. }
  187. // Do actual creation
  188. return CreateBodyWithIDInternal(inBodyID, inBodyCreationSettings);
  189. }
  190. Body *BodyManager::CreateBodyWithIDInternal(const BodyID &inBodyID, const BodyCreationSettings &inBodyCreationSettings)
  191. {
  192. // Fill in basic properties
  193. Body *body;
  194. if (inBodyCreationSettings.HasMassProperties())
  195. {
  196. BodyWithMotionProperties *bmp = new BodyWithMotionProperties;
  197. body = bmp;
  198. body->mMotionProperties = &bmp->mMotionProperties;
  199. }
  200. else
  201. {
  202. body = new Body;
  203. }
  204. body->mID = inBodyID;
  205. body->mShape = inBodyCreationSettings.GetShape();
  206. body->mUserData = inBodyCreationSettings.mUserData;
  207. body->SetFriction(inBodyCreationSettings.mFriction);
  208. body->SetRestitution(inBodyCreationSettings.mRestitution);
  209. body->mMotionType = inBodyCreationSettings.mMotionType;
  210. if (inBodyCreationSettings.mIsSensor)
  211. body->SetIsSensor(true);
  212. SetBodyObjectLayerInternal(*body, inBodyCreationSettings.mObjectLayer);
  213. body->mObjectLayer = inBodyCreationSettings.mObjectLayer;
  214. body->mCollisionGroup = inBodyCreationSettings.mCollisionGroup;
  215. if (inBodyCreationSettings.HasMassProperties())
  216. {
  217. MotionProperties *mp = body->mMotionProperties;
  218. mp->SetLinearDamping(inBodyCreationSettings.mLinearDamping);
  219. mp->SetAngularDamping(inBodyCreationSettings.mAngularDamping);
  220. mp->SetMaxLinearVelocity(inBodyCreationSettings.mMaxLinearVelocity);
  221. mp->SetMaxAngularVelocity(inBodyCreationSettings.mMaxAngularVelocity);
  222. mp->SetLinearVelocity(inBodyCreationSettings.mLinearVelocity); // Needs to happen after setting the max linear/angular velocity
  223. mp->SetAngularVelocity(inBodyCreationSettings.mAngularVelocity);
  224. mp->SetGravityFactor(inBodyCreationSettings.mGravityFactor);
  225. mp->SetMotionQuality(inBodyCreationSettings.mMotionQuality);
  226. mp->mAllowSleeping = inBodyCreationSettings.mAllowSleeping;
  227. mp->mIndexInActiveBodies = Body::cInactiveIndex;
  228. mp->mIslandIndex = Body::cInactiveIndex;
  229. JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)
  230. mp->SetMassProperties(inBodyCreationSettings.GetMassProperties());
  231. }
  232. // Position body
  233. body->SetPositionAndRotationInternal(inBodyCreationSettings.mPosition, inBodyCreationSettings.mRotation);
  234. // Add body
  235. mBodies[inBodyID.GetIndex()] = body;
  236. return body;
  237. }
  238. void BodyManager::DestroyBodies(const BodyID *inBodyIDs, int inNumber)
  239. {
  240. // Don't take lock if no bodies are to be destroyed
  241. if (inNumber <= 0)
  242. return;
  243. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  244. // Update cached number of bodies
  245. JPH_ASSERT(mNumBodies >= (uint)inNumber);
  246. mNumBodies -= inNumber;
  247. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  248. {
  249. // Get body
  250. BodyID body_id = *b;
  251. uint32 idx = body_id.GetIndex();
  252. Body *body = mBodies[idx];
  253. // Validate that it can be removed
  254. JPH_ASSERT(body->GetID() == body_id);
  255. JPH_ASSERT(!body->IsActive());
  256. JPH_ASSERT(!body->IsInBroadPhase());
  257. // Push the id onto the freelist
  258. mBodies[idx] = (Body *)mBodyIDFreeListStart;
  259. mBodyIDFreeListStart = (uintptr_t(idx) << cFreedBodyIndexShift) | cIsFreedBody;
  260. // Free the body
  261. sDeleteBody(body);
  262. }
  263. #if defined(_DEBUG) && defined(JPH_ENABLE_ASSERTS)
  264. // Check that the freelist is correct
  265. size_t num_freed = 0;
  266. for (uintptr_t start = mBodyIDFreeListStart; start != cBodyIDFreeListEnd; start = uintptr_t(mBodies[start >> cFreedBodyIndexShift]))
  267. {
  268. JPH_ASSERT(start & cIsFreedBody);
  269. num_freed++;
  270. }
  271. JPH_ASSERT(mNumBodies == mBodies.size() - num_freed);
  272. #endif // defined(_DEBUG) && _defined(JPH_ENABLE_ASSERTS)
  273. }
  274. void BodyManager::ActivateBodies(const BodyID *inBodyIDs, int inNumber)
  275. {
  276. // Don't take lock if no bodies are to be activated
  277. if (inNumber <= 0)
  278. return;
  279. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  280. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowActivation);
  281. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  282. if (!b->IsInvalid())
  283. {
  284. BodyID body_id = *b;
  285. Body &body = *mBodies[body_id.GetIndex()];
  286. JPH_ASSERT(GetMutexForBody(body_id).is_locked(), "Assuming that body has been locked!");
  287. JPH_ASSERT(body.GetID() == body_id);
  288. JPH_ASSERT(body.IsInBroadPhase());
  289. if (!body.IsStatic()
  290. && body.mMotionProperties->mIndexInActiveBodies == Body::cInactiveIndex)
  291. {
  292. body.mMotionProperties->mIndexInActiveBodies = mNumActiveBodies;
  293. body.ResetSleepTestSpheres();
  294. JPH_ASSERT(mNumActiveBodies < GetMaxBodies());
  295. mActiveBodies[mNumActiveBodies] = body_id;
  296. mNumActiveBodies++; // Increment atomic after setting the body ID so that PhysicsSystem::JobFindCollisions (which doesn't lock the mActiveBodiesMutex) will only read valid IDs
  297. // Count CCD bodies
  298. if (body.mMotionProperties->GetMotionQuality() == EMotionQuality::LinearCast)
  299. mNumActiveCCDBodies++;
  300. // Call activation listener
  301. if (mActivationListener != nullptr)
  302. mActivationListener->OnBodyActivated(body_id, body.GetUserData());
  303. }
  304. }
  305. }
  306. void BodyManager::DeactivateBodies(const BodyID *inBodyIDs, int inNumber)
  307. {
  308. // Don't take lock if no bodies are to be deactivated
  309. if (inNumber <= 0)
  310. return;
  311. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  312. JPH_ASSERT(!mActiveBodiesLocked || sOverrideAllowDeactivation);
  313. for (const BodyID *b = inBodyIDs, *b_end = inBodyIDs + inNumber; b < b_end; b++)
  314. if (!b->IsInvalid())
  315. {
  316. BodyID body_id = *b;
  317. Body &body = *mBodies[body_id.GetIndex()];
  318. JPH_ASSERT(GetMutexForBody(body_id).is_locked(), "Assuming that body has been locked!");
  319. JPH_ASSERT(body.GetID() == body_id);
  320. JPH_ASSERT(body.IsInBroadPhase());
  321. if (body.mMotionProperties != nullptr
  322. && body.mMotionProperties->mIndexInActiveBodies != Body::cInactiveIndex)
  323. {
  324. uint32 last_body_index = mNumActiveBodies - 1;
  325. if (body.mMotionProperties->mIndexInActiveBodies != last_body_index)
  326. {
  327. // This is not the last body, use the last body to fill the hole
  328. BodyID last_body_id = mActiveBodies[last_body_index];
  329. mActiveBodies[body.mMotionProperties->mIndexInActiveBodies] = last_body_id;
  330. // Update that body's index in the active list
  331. Body &last_body = *mBodies[last_body_id.GetIndex()];
  332. JPH_ASSERT(last_body.mMotionProperties->mIndexInActiveBodies == last_body_index);
  333. last_body.mMotionProperties->mIndexInActiveBodies = body.mMotionProperties->mIndexInActiveBodies;
  334. }
  335. // Mark this body as no longer active
  336. body.mMotionProperties->mIndexInActiveBodies = Body::cInactiveIndex;
  337. body.mMotionProperties->mIslandIndex = Body::cInactiveIndex;
  338. // Reset velocity
  339. body.mMotionProperties->mLinearVelocity = Vec3::sZero();
  340. body.mMotionProperties->mAngularVelocity = Vec3::sZero();
  341. // Remove unused element from active bodies list
  342. --mNumActiveBodies;
  343. // Count CCD bodies
  344. if (body.mMotionProperties->GetMotionQuality() == EMotionQuality::LinearCast)
  345. mNumActiveCCDBodies--;
  346. // Call activation listener
  347. if (mActivationListener != nullptr)
  348. mActivationListener->OnBodyDeactivated(body_id, body.GetUserData());
  349. }
  350. }
  351. }
  352. void BodyManager::GetActiveBodies(BodyIDVector &outBodyIDs) const
  353. {
  354. JPH_PROFILE_FUNCTION();
  355. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  356. outBodyIDs.assign(mActiveBodies, mActiveBodies + mNumActiveBodies);
  357. }
  358. void BodyManager::GetBodyIDs(BodyIDVector &outBodies) const
  359. {
  360. JPH_PROFILE_FUNCTION();
  361. UniqueLock lock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  362. // Reserve space for all bodies
  363. outBodies.clear();
  364. outBodies.reserve(mNumBodies);
  365. // Iterate the list and find the bodies that are not null
  366. for (const Body *b : mBodies)
  367. if (sIsValidBodyPointer(b))
  368. outBodies.push_back(b->GetID());
  369. // Validate that our reservation was correct
  370. JPH_ASSERT(outBodies.size() == mNumBodies);
  371. }
  372. void BodyManager::SetBodyActivationListener(BodyActivationListener *inListener)
  373. {
  374. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  375. mActivationListener = inListener;
  376. }
  377. BodyManager::MutexMask BodyManager::GetMutexMask(const BodyID *inBodies, int inNumber) const
  378. {
  379. JPH_ASSERT(sizeof(MutexMask) * 8 >= mBodyMutexes.GetNumMutexes(), "MutexMask must have enough bits");
  380. if (inNumber >= (int)mBodyMutexes.GetNumMutexes())
  381. {
  382. // Just lock everything if there are too many bodies
  383. return GetAllBodiesMutexMask();
  384. }
  385. else
  386. {
  387. MutexMask mask = 0;
  388. for (const BodyID *b = inBodies, *b_end = inBodies + inNumber; b < b_end; ++b)
  389. if (!b->IsInvalid())
  390. {
  391. uint32 index = mBodyMutexes.GetMutexIndex(b->GetIndex());
  392. mask |= (MutexMask(1) << index);
  393. }
  394. return mask;
  395. }
  396. }
  397. void BodyManager::LockRead(MutexMask inMutexMask) const
  398. {
  399. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(EPhysicsLockTypes::PerBody));
  400. int index = 0;
  401. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  402. if (mask & 1)
  403. mBodyMutexes.GetMutexByIndex(index).lock_shared();
  404. }
  405. void BodyManager::UnlockRead(MutexMask inMutexMask) const
  406. {
  407. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(EPhysicsLockTypes::PerBody));
  408. int index = 0;
  409. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  410. if (mask & 1)
  411. mBodyMutexes.GetMutexByIndex(index).unlock_shared();
  412. }
  413. void BodyManager::LockWrite(MutexMask inMutexMask) const
  414. {
  415. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(EPhysicsLockTypes::PerBody));
  416. int index = 0;
  417. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  418. if (mask & 1)
  419. mBodyMutexes.GetMutexByIndex(index).lock();
  420. }
  421. void BodyManager::UnlockWrite(MutexMask inMutexMask) const
  422. {
  423. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(EPhysicsLockTypes::PerBody));
  424. int index = 0;
  425. for (MutexMask mask = inMutexMask; mask != 0; mask >>= 1, index++)
  426. if (mask & 1)
  427. mBodyMutexes.GetMutexByIndex(index).unlock();
  428. }
  429. void BodyManager::LockAllBodies() const
  430. {
  431. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckLock(EPhysicsLockTypes::PerBody));
  432. mBodyMutexes.LockAll();
  433. PhysicsLock::sLock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  434. }
  435. void BodyManager::UnlockAllBodies() const
  436. {
  437. PhysicsLock::sUnlock(mBodiesMutex, EPhysicsLockTypes::BodiesList);
  438. JPH_IF_ENABLE_ASSERTS(PhysicsLock::sCheckUnlock(EPhysicsLockTypes::PerBody));
  439. mBodyMutexes.UnlockAll();
  440. }
  441. void BodyManager::SaveState(StateRecorder &inStream) const
  442. {
  443. {
  444. LockAllBodies();
  445. // Count number of bodies
  446. size_t num_bodies = 0;
  447. for (const Body *b : mBodies)
  448. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  449. ++num_bodies;
  450. inStream.Write(num_bodies);
  451. // Write state of bodies
  452. for (const Body *b : mBodies)
  453. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  454. {
  455. inStream.Write(b->GetID());
  456. b->SaveState(inStream);
  457. }
  458. UnlockAllBodies();
  459. }
  460. {
  461. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  462. // Write active bodies, sort because activation can come from multiple threads, so order is not deterministic
  463. inStream.Write(mNumActiveBodies);
  464. BodyIDVector sorted_active_bodies(mActiveBodies, mActiveBodies + mNumActiveBodies);
  465. QuickSort(sorted_active_bodies.begin(), sorted_active_bodies.end());
  466. for (const BodyID &id : sorted_active_bodies)
  467. inStream.Write(id);
  468. inStream.Write(mNumActiveCCDBodies);
  469. }
  470. }
  471. bool BodyManager::RestoreState(StateRecorder &inStream)
  472. {
  473. {
  474. LockAllBodies();
  475. // Read state of bodies, note this reads it in a way to be consistent with validation
  476. size_t old_num_bodies = 0;
  477. for (const Body *b : mBodies)
  478. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  479. ++old_num_bodies;
  480. size_t num_bodies = old_num_bodies; // Initialize to current value for validation
  481. inStream.Read(num_bodies);
  482. if (num_bodies != old_num_bodies)
  483. {
  484. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  485. UnlockAllBodies();
  486. return false;
  487. }
  488. for (Body *b : mBodies)
  489. if (sIsValidBodyPointer(b) && b->IsInBroadPhase())
  490. {
  491. BodyID body_id = b->GetID(); // Initialize to current value for validation
  492. inStream.Read(body_id);
  493. if (body_id != b->GetID())
  494. {
  495. JPH_ASSERT(false, "Cannot handle adding/removing bodies");
  496. UnlockAllBodies();
  497. return false;
  498. }
  499. b->RestoreState(inStream);
  500. }
  501. UnlockAllBodies();
  502. }
  503. {
  504. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  505. // Mark current active bodies as deactivated
  506. for (const BodyID *id = mActiveBodies, *id_end = mActiveBodies + mNumActiveBodies; id < id_end; ++id)
  507. mBodies[id->GetIndex()]->mMotionProperties->mIndexInActiveBodies = Body::cInactiveIndex;
  508. QuickSort(mActiveBodies, mActiveBodies + mNumActiveBodies); // Sort for validation
  509. // Read active bodies
  510. inStream.Read(mNumActiveBodies);
  511. for (BodyID *id = mActiveBodies, *id_end = mActiveBodies + mNumActiveBodies; id < id_end; ++id)
  512. {
  513. inStream.Read(*id);
  514. mBodies[id->GetIndex()]->mMotionProperties->mIndexInActiveBodies = uint32(id - mActiveBodies);
  515. }
  516. inStream.Read(mNumActiveCCDBodies);
  517. }
  518. return true;
  519. }
  520. #ifdef JPH_DEBUG_RENDERER
  521. void BodyManager::Draw(const DrawSettings &inDrawSettings, const PhysicsSettings &inPhysicsSettings, DebugRenderer *inRenderer, const BodyDrawFilter *inBodyFilter)
  522. {
  523. JPH_PROFILE_FUNCTION();
  524. LockAllBodies();
  525. for (const Body *body : mBodies)
  526. if (sIsValidBodyPointer(body) && body->IsInBroadPhase() && (!inBodyFilter || inBodyFilter->ShouldDraw(*body)))
  527. {
  528. JPH_ASSERT(mBodies[body->GetID().GetIndex()] == body);
  529. bool is_sensor = body->IsSensor();
  530. // Determine drawing mode
  531. Color color;
  532. if (is_sensor)
  533. color = Color::sYellow;
  534. else
  535. switch (inDrawSettings.mDrawShapeColor)
  536. {
  537. case EShapeColor::InstanceColor:
  538. // Each instance has own color
  539. color = Color::sGetDistinctColor(body->mID.GetIndex());
  540. break;
  541. case EShapeColor::ShapeTypeColor:
  542. color = ShapeFunctions::sGet(body->GetShape()->GetSubType()).mColor;
  543. break;
  544. case EShapeColor::MotionTypeColor:
  545. // Determine color based on motion type
  546. switch (body->mMotionType)
  547. {
  548. case EMotionType::Static:
  549. color = Color::sGrey;
  550. break;
  551. case EMotionType::Kinematic:
  552. color = Color::sGreen;
  553. break;
  554. case EMotionType::Dynamic:
  555. color = Color::sGetDistinctColor(body->mID.GetIndex());
  556. break;
  557. default:
  558. JPH_ASSERT(false);
  559. color = Color::sBlack;
  560. break;
  561. }
  562. break;
  563. case EShapeColor::SleepColor:
  564. // Determine color based on motion type
  565. switch (body->mMotionType)
  566. {
  567. case EMotionType::Static:
  568. color = Color::sGrey;
  569. break;
  570. case EMotionType::Kinematic:
  571. color = body->IsActive()? Color::sGreen : Color::sRed;
  572. break;
  573. case EMotionType::Dynamic:
  574. color = body->IsActive()? Color::sYellow : Color::sRed;
  575. break;
  576. default:
  577. JPH_ASSERT(false);
  578. color = Color::sBlack;
  579. break;
  580. }
  581. break;
  582. case EShapeColor::IslandColor:
  583. // Determine color based on motion type
  584. switch (body->mMotionType)
  585. {
  586. case EMotionType::Static:
  587. color = Color::sGrey;
  588. break;
  589. case EMotionType::Kinematic:
  590. case EMotionType::Dynamic:
  591. {
  592. uint32 idx = body->GetMotionProperties()->GetIslandIndexInternal();
  593. color = idx != Body::cInactiveIndex? Color::sGetDistinctColor(idx) : Color::sLightGrey;
  594. }
  595. break;
  596. default:
  597. JPH_ASSERT(false);
  598. color = Color::sBlack;
  599. break;
  600. }
  601. break;
  602. case EShapeColor::MaterialColor:
  603. color = Color::sWhite;
  604. break;
  605. default:
  606. JPH_ASSERT(false);
  607. color = Color::sBlack;
  608. break;
  609. }
  610. // Draw the results of GetSupportFunction
  611. if (inDrawSettings.mDrawGetSupportFunction)
  612. body->mShape->DrawGetSupportFunction(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), color, inDrawSettings.mDrawSupportDirection);
  613. // Draw the results of GetSupportingFace
  614. if (inDrawSettings.mDrawGetSupportingFace)
  615. body->mShape->DrawGetSupportingFace(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  616. // Draw the shape
  617. if (inDrawSettings.mDrawShape)
  618. body->mShape->Draw(inRenderer, body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), color, inDrawSettings.mDrawShapeColor == EShapeColor::MaterialColor, inDrawSettings.mDrawShapeWireframe || is_sensor);
  619. // Draw bounding box
  620. if (inDrawSettings.mDrawBoundingBox)
  621. inRenderer->DrawWireBox(body->mBounds, color);
  622. // Draw center of mass transform
  623. if (inDrawSettings.mDrawCenterOfMassTransform)
  624. inRenderer->DrawCoordinateSystem(body->GetCenterOfMassTransform(), 0.2f);
  625. // Draw world transform
  626. if (inDrawSettings.mDrawWorldTransform)
  627. inRenderer->DrawCoordinateSystem(body->GetWorldTransform(), 0.2f);
  628. // Draw world space linear and angular velocity
  629. if (inDrawSettings.mDrawVelocity)
  630. {
  631. Vec3 pos = body->GetCenterOfMassPosition();
  632. inRenderer->DrawArrow(pos, pos + body->GetLinearVelocity(), Color::sGreen, 0.1f);
  633. inRenderer->DrawArrow(pos, pos + body->GetAngularVelocity(), Color::sRed, 0.1f);
  634. }
  635. if (inDrawSettings.mDrawMassAndInertia && body->IsDynamic())
  636. {
  637. const MotionProperties *mp = body->GetMotionProperties();
  638. // Invert mass again
  639. float mass = 1.0f / mp->GetInverseMass();
  640. // Invert diagonal again
  641. Vec3 diagonal = mp->GetInverseInertiaDiagonal().Reciprocal();
  642. // Determine how big of a box has the equivalent inertia
  643. Vec3 box_size = MassProperties::sGetEquivalentSolidBoxSize(mass, diagonal);
  644. // Draw box with equivalent inertia
  645. inRenderer->DrawWireBox(body->GetCenterOfMassTransform() * Mat44::sRotation(mp->GetInertiaRotation()), AABox(-0.5f * box_size, 0.5f * box_size), Color::sOrange);
  646. // Draw mass
  647. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), StringFormat("%.2f", (double)mass), Color::sOrange, 0.2f);
  648. }
  649. if (inDrawSettings.mDrawSleepStats && body->IsDynamic() && body->IsActive())
  650. {
  651. // Draw stats to know which bodies could go to sleep
  652. String text = StringFormat("t: %.1f", (double)body->mMotionProperties->mSleepTestTimer);
  653. uint8 g = uint8(Clamp(255.0f * body->mMotionProperties->mSleepTestTimer / inPhysicsSettings.mTimeBeforeSleep, 0.0f, 255.0f));
  654. Color sleep_color = Color(0, 255 - g, g);
  655. inRenderer->DrawText3D(body->GetCenterOfMassPosition(), text, sleep_color, 0.2f);
  656. for (int i = 0; i < 3; ++i)
  657. inRenderer->DrawWireSphere(body->mMotionProperties->mSleepTestSpheres[i].GetCenter(), body->mMotionProperties->mSleepTestSpheres[i].GetRadius(), sleep_color);
  658. }
  659. }
  660. UnlockAllBodies();
  661. }
  662. #endif // JPH_DEBUG_RENDERER
  663. void BodyManager::InvalidateContactCacheForBody(Body &ioBody)
  664. {
  665. // 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
  666. if (ioBody.InvalidateContactCacheInternal())
  667. {
  668. lock_guard lock(mBodiesCacheInvalidMutex);
  669. mBodiesCacheInvalid.push_back(ioBody.GetID());
  670. }
  671. }
  672. void BodyManager::ValidateContactCacheForAllBodies()
  673. {
  674. lock_guard lock(mBodiesCacheInvalidMutex);
  675. for (const BodyID &b : mBodiesCacheInvalid)
  676. {
  677. // The body may have been removed between the call to InvalidateContactCacheForBody and this call, so check if it still exists
  678. Body *body = TryGetBody(b);
  679. if (body != nullptr)
  680. body->ValidateContactCacheInternal();
  681. }
  682. mBodiesCacheInvalid.clear();
  683. }
  684. #ifdef _DEBUG
  685. void BodyManager::ValidateActiveBodyBounds()
  686. {
  687. UniqueLock lock(mActiveBodiesMutex, EPhysicsLockTypes::ActiveBodiesList);
  688. for (BodyID *id = mActiveBodies, *id_end = mActiveBodies + mNumActiveBodies; id < id_end; ++id)
  689. {
  690. const Body *body = mBodies[id->GetIndex()];
  691. AABox cached = body->GetWorldSpaceBounds();
  692. AABox calculated = body->GetShape()->GetWorldSpaceBounds(body->GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  693. JPH_ASSERT(cached == calculated);
  694. }
  695. }
  696. #endif // _DEBUG
  697. JPH_NAMESPACE_END