IslandBuilder.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt.h>
  4. #include <Physics/IslandBuilder.h>
  5. #include <Physics/Body/Body.h>
  6. #include <Physics/PhysicsSettings.h>
  7. #include <Core/Profiler.h>
  8. #include <Core/Atomics.h>
  9. #include <Core/TempAllocator.h>
  10. namespace JPH {
  11. static const uint32 cNoLink = 0x7fffffff;
  12. static const uint32 cProcessedLink = 0x80000000;
  13. IslandBuilder::~IslandBuilder()
  14. {
  15. JPH_ASSERT(mConstraintLinks == nullptr);
  16. JPH_ASSERT(mContactLinks == nullptr);
  17. JPH_ASSERT(mBodyIslands == nullptr);
  18. JPH_ASSERT(mBodyIslandEnds == nullptr);
  19. JPH_ASSERT(mConstraintIslands == nullptr);
  20. JPH_ASSERT(mConstraintIslandEnds == nullptr);
  21. JPH_ASSERT(mContactIslands == nullptr);
  22. JPH_ASSERT(mContactIslandEnds == nullptr);
  23. JPH_ASSERT(mIslandsSorted == nullptr);
  24. delete [] mBodyLinks;
  25. }
  26. void IslandBuilder::Init(uint32 inMaxActiveBodies)
  27. {
  28. mMaxActiveBodies = inMaxActiveBodies;
  29. // Link each body to itself, BuildBodyIslands() will restore this so that we don't need to do this each step
  30. JPH_ASSERT(mBodyLinks == nullptr);
  31. mBodyLinks = new BodyLink [mMaxActiveBodies];
  32. for (uint32 i = 0; i < mMaxActiveBodies; ++i)
  33. mBodyLinks[i].mLinkedTo = i;
  34. }
  35. void IslandBuilder::PrepareContactConstraints(uint32 inMaxContacts, TempAllocator *inTempAllocator)
  36. {
  37. JPH_PROFILE_FUNCTION();
  38. // Need to call Init first
  39. JPH_ASSERT(mBodyLinks != nullptr);
  40. // Check that the builder has been reset
  41. JPH_ASSERT(mNumContacts == 0);
  42. JPH_ASSERT(mNumIslands == 0);
  43. // Create contact link buffer, not initialized so each contact needs to be explicitly set
  44. JPH_ASSERT(mContactLinks == nullptr);
  45. mContactLinks = (uint32 *)inTempAllocator->Allocate(inMaxContacts * sizeof(uint32));
  46. mMaxContacts = inMaxContacts;
  47. #ifdef JPH_VALIDATE_ISLAND_BUILDER
  48. // Create validation structures
  49. JPH_ASSERT(mLinkValidation == nullptr);
  50. mLinkValidation = (LinkValidation *)inTempAllocator->Allocate(inMaxContacts * sizeof(LinkValidation));
  51. mNumLinkValidation = 0;
  52. #endif
  53. }
  54. void IslandBuilder::PrepareNonContactConstraints(uint32 inNumConstraints, TempAllocator *inTempAllocator)
  55. {
  56. JPH_PROFILE_FUNCTION();
  57. // Need to call Init first
  58. JPH_ASSERT(mBodyLinks != nullptr);
  59. // Check that the builder has been reset
  60. JPH_ASSERT(mNumIslands == 0);
  61. // Store number of constraints
  62. mNumConstraints = inNumConstraints;
  63. // Create constraint link buffer, not initialized so each constraint needs to be explicitly set
  64. JPH_ASSERT(mConstraintLinks == nullptr);
  65. mConstraintLinks = (uint32 *)inTempAllocator->Allocate(inNumConstraints * sizeof(uint32));
  66. }
  67. uint32 IslandBuilder::GetLowestBodyIndex(uint32 inActiveBodyIndex) const
  68. {
  69. uint32 index = inActiveBodyIndex;
  70. for (;;)
  71. {
  72. uint32 link_to = mBodyLinks[index].mLinkedTo;
  73. if (link_to == index)
  74. break;
  75. index = link_to;
  76. }
  77. return index;
  78. }
  79. void IslandBuilder::LinkBodies(uint32 inFirst, uint32 inSecond)
  80. {
  81. JPH_PROFILE_FUNCTION();
  82. // Both need to be active, we don't want to create an island with static objects
  83. if (inFirst >= mMaxActiveBodies || inSecond >= mMaxActiveBodies)
  84. return;
  85. #ifdef JPH_VALIDATE_ISLAND_BUILDER
  86. // Add link to the validation list
  87. if (mNumLinkValidation < uint32(mMaxContacts))
  88. mLinkValidation[mNumLinkValidation++] = { inFirst, inSecond };
  89. else
  90. JPH_ASSERT(false, "Out of links");
  91. #endif
  92. // Start the algorithm with the two bodies
  93. uint32 first_link_to = inFirst;
  94. uint32 second_link_to = inSecond;
  95. for (;;)
  96. {
  97. // Follow the chain until we get to the body with lowest index
  98. // If the swap compare below fails, we'll keep searching from the lowest index for the new lowest index
  99. first_link_to = GetLowestBodyIndex(first_link_to);
  100. second_link_to = GetLowestBodyIndex(second_link_to);
  101. // If the targets are the same, the bodies are already connected
  102. if (first_link_to != second_link_to)
  103. {
  104. // We always link the highest to the lowest
  105. if (first_link_to < second_link_to)
  106. {
  107. // Attempt to link the second to the first
  108. // Since we found this body to be at the end of the chain it must point to itself, and if it
  109. // doesn't it has been reparented and we need to retry the algorithm
  110. if (!mBodyLinks[second_link_to].mLinkedTo.compare_exchange_strong(second_link_to, first_link_to))
  111. continue;
  112. }
  113. else
  114. {
  115. // Attempt to link the first to the second
  116. // Since we found this body to be at the end of the chain it must point to itself, and if it
  117. // doesn't it has been reparented and we need to retry the algorithm
  118. if (!mBodyLinks[first_link_to].mLinkedTo.compare_exchange_strong(first_link_to, second_link_to))
  119. continue;
  120. }
  121. }
  122. // Linking succeeded!
  123. // Chains of bodies can become really long, resulting in an O(N) loop to find the lowest body index
  124. // to prevent this we attempt to update the link of the bodies that were passed in to directly point
  125. // to the lowest index that we found. If the value became lower than our lowest link, some other
  126. // thread must have relinked these bodies in the mean time so we won't update the value.
  127. uint32 lowest_link_to = min(first_link_to, second_link_to);
  128. AtomicMin(mBodyLinks[inFirst].mLinkedTo, lowest_link_to);
  129. AtomicMin(mBodyLinks[inSecond].mLinkedTo, lowest_link_to);
  130. break;
  131. }
  132. }
  133. void IslandBuilder::LinkConstraint(uint32 inConstraintIndex, uint32 inFirst, uint32 inSecond)
  134. {
  135. LinkBodies(inFirst, inSecond);
  136. JPH_ASSERT(inConstraintIndex < mNumConstraints);
  137. mConstraintLinks[inConstraintIndex] = min(inFirst, inSecond); // Use fact that invalid index is 0xffffffff, we want the active body of two
  138. }
  139. void IslandBuilder::LinkContact(uint32 inContactIndex, uint32 inFirst, uint32 inSecond)
  140. {
  141. JPH_ASSERT(inContactIndex < mMaxContacts);
  142. mContactLinks[inContactIndex] = min(inFirst, inSecond); // Use fact that invalid index is 0xffffffff, we want the active body of two
  143. }
  144. #ifdef JPH_VALIDATE_ISLAND_BUILDER
  145. void IslandBuilder::ValidateIslands(uint32 inNumActiveBodies) const
  146. {
  147. JPH_PROFILE_FUNCTION();
  148. // Go through all links so far
  149. for (uint32 i = 0; i < mNumLinkValidation; ++i)
  150. {
  151. // If the bodies in this link ended up in different groups we have a problem
  152. if (mBodyLinks[mLinkValidation[i].mFirst].mLinkedTo != mBodyLinks[mLinkValidation[i].mSecond].mLinkedTo)
  153. {
  154. Trace("Fail: %d, %d", mLinkValidation[i].mFirst, mLinkValidation[i].mSecond);
  155. Trace("Num Active: %d", inNumActiveBodies);
  156. for (uint32 j = 0; j < mNumLinkValidation; ++j)
  157. Trace("builder.Link(%d, %d);", mLinkValidation[j].mFirst, mLinkValidation[j].mSecond);
  158. IslandBuilder tmp;
  159. tmp.Init(inNumActiveBodies);
  160. for (uint32 j = 0; j < mNumLinkValidation; ++j)
  161. {
  162. Trace("Link %d -> %d", mLinkValidation[j].mFirst, mLinkValidation[j].mSecond);
  163. tmp.LinkBodies(mLinkValidation[j].mFirst, mLinkValidation[j].mSecond);
  164. for (uint32 t = 0; t < inNumActiveBodies; ++t)
  165. Trace("%d -> %d", t, (uint32)tmp.mBodyLinks[t].mLinkedTo);
  166. }
  167. JPH_ASSERT(false, "IslandBuilder validation failed");
  168. }
  169. }
  170. }
  171. #endif
  172. void IslandBuilder::BuildBodyIslands(const BodyID *inActiveBodies, uint32 inNumActiveBodies, TempAllocator *inTempAllocator)
  173. {
  174. JPH_PROFILE_FUNCTION();
  175. // Check that the number of active bodies does not exceed our special value
  176. JPH_ASSERT(inNumActiveBodies < cNoLink);
  177. // Make the linked to field for all active bodies point to the body with the lowest index
  178. for (uint32 t = 0; t < inNumActiveBodies; ++t)
  179. {
  180. BodyLink &target_link = mBodyLinks[t];
  181. target_link.mLinkedTo = mBodyLinks[target_link.mLinkedTo].mLinkedTo.load();
  182. target_link.mNextLinkOrIslandIndex = cNoLink;
  183. }
  184. #ifdef JPH_VALIDATE_ISLAND_BUILDER
  185. ValidateIslands(inNumActiveBodies);
  186. #endif
  187. // Form a linked list connecting all bodies in an island
  188. JPH_ASSERT(mNumIslands == 0);
  189. for (int t = (int)inNumActiveBodies - 1; t >= 0; --t)
  190. {
  191. BodyLink &target_link = mBodyLinks[t];
  192. uint32 s = target_link.mLinkedTo;
  193. if (s != uint32(t))
  194. {
  195. // Links to another body, link it
  196. BodyLink &source_link = mBodyLinks[s];
  197. uint32 source_next_link = source_link.mNextLinkOrIslandIndex;
  198. source_link.mNextLinkOrIslandIndex = t;
  199. target_link.mNextLinkOrIslandIndex = source_next_link;
  200. }
  201. else
  202. {
  203. // Does not link to other body, this is the start of a new island
  204. ++mNumIslands;
  205. }
  206. }
  207. JPH_ASSERT((mNumIslands & cProcessedLink) == 0);
  208. // Store the amount of active bodies
  209. mNumActiveBodies = inNumActiveBodies;
  210. // Create output arrays for body ID's, don't call constructors
  211. JPH_ASSERT(mBodyIslands == nullptr);
  212. mBodyIslands = (BodyID *)inTempAllocator->Allocate(inNumActiveBodies * sizeof(BodyID));
  213. // Create output array for end index of each contact island
  214. JPH_ASSERT(mBodyIslandEnds == nullptr);
  215. mBodyIslandEnds = (uint32 *)inTempAllocator->Allocate(mNumIslands * sizeof(uint32));
  216. // Convert the linked list to a linear list grouped by island
  217. uint32 island_idx = 0;
  218. uint32 output_idx = 0;
  219. for (uint32 i = 0; i < inNumActiveBodies; ++i)
  220. if ((mBodyLinks[i].mNextLinkOrIslandIndex & cProcessedLink) == 0)
  221. {
  222. uint32 active_body_idx = i;
  223. do
  224. {
  225. // Store body id of active body
  226. mBodyIslands[output_idx++] = inActiveBodies[active_body_idx];
  227. // Get next body in chain
  228. BodyLink &link = mBodyLinks[active_body_idx];
  229. uint32 next = link.mNextLinkOrIslandIndex;
  230. // Store island index and mark this link as processed
  231. link.mNextLinkOrIslandIndex = island_idx | cProcessedLink;
  232. // Reset linked to field for the next update
  233. link.mLinkedTo = active_body_idx;
  234. active_body_idx = next;
  235. }
  236. while (active_body_idx != cNoLink);
  237. // Store next pointer
  238. mBodyIslandEnds[island_idx] = output_idx;
  239. ++island_idx;
  240. }
  241. JPH_ASSERT(island_idx == mNumIslands);
  242. }
  243. void IslandBuilder::BuildConstraintIslands(uint32 *inConstraintToBody, uint32 inNumConstraints, uint32 *&outConstraints, uint32 *&outConstraintsEnd, TempAllocator *inTempAllocator)
  244. {
  245. JPH_PROFILE_FUNCTION();
  246. // Check if there's anything to do
  247. if (inNumConstraints == 0)
  248. return;
  249. // Create output arrays for constraints
  250. uint32 *constraints = (uint32 *)inTempAllocator->Allocate(inNumConstraints * sizeof(uint32));
  251. uint32 *constraint_ends = (uint32 *)inTempAllocator->Allocate(mNumIslands * sizeof(uint32));
  252. // Reset sizes
  253. for (uint32 island = 0; island < mNumIslands; ++island)
  254. constraint_ends[island] = 0;
  255. // Loop over array and increment start relative position for the next island
  256. for (uint32 constraint = 0; constraint < inNumConstraints; ++constraint)
  257. {
  258. uint32 body_idx = inConstraintToBody[constraint];
  259. uint32 next_island_idx = (mBodyLinks[body_idx].mNextLinkOrIslandIndex & (~cProcessedLink)) + 1;
  260. JPH_ASSERT(next_island_idx <= mNumIslands);
  261. if (next_island_idx < mNumIslands)
  262. constraint_ends[next_island_idx]++;
  263. }
  264. // Make start positions absolute
  265. for (uint32 island = 1; island < mNumIslands; ++island)
  266. constraint_ends[island] += constraint_ends[island - 1];
  267. // Loop over array and collect constraints
  268. for (uint32 constraint = 0; constraint < inNumConstraints; ++constraint)
  269. {
  270. uint32 body_idx = inConstraintToBody[constraint];
  271. uint32 island_idx = mBodyLinks[body_idx].mNextLinkOrIslandIndex & (~cProcessedLink);
  272. constraints[constraint_ends[island_idx]++] = constraint;
  273. }
  274. JPH_ASSERT(outConstraints == nullptr);
  275. outConstraints = constraints;
  276. JPH_ASSERT(outConstraintsEnd == nullptr);
  277. outConstraintsEnd = constraint_ends;
  278. }
  279. void IslandBuilder::SortIslands(TempAllocator *inTempAllocator)
  280. {
  281. JPH_PROFILE_FUNCTION();
  282. if (mNumContacts > 0 || mNumConstraints > 0)
  283. {
  284. // Allocate mapping table
  285. JPH_ASSERT(mIslandsSorted == nullptr);
  286. mIslandsSorted = (uint32 *)inTempAllocator->Allocate(mNumIslands * sizeof(uint32));
  287. // Initialize index
  288. for (uint32 island = 0; island < mNumIslands; ++island)
  289. mIslandsSorted[island] = island;
  290. // Determine the sum of contact constraints / constraints per island
  291. uint32 *num_constraints = (uint32 *)inTempAllocator->Allocate(mNumIslands * sizeof(uint32));
  292. if (mNumContacts > 0 && mNumConstraints > 0)
  293. {
  294. num_constraints[0] = mConstraintIslandEnds[0] + mContactIslandEnds[0];
  295. for (uint32 island = 1; island < mNumIslands; ++island)
  296. num_constraints[island] = mConstraintIslandEnds[island] - mConstraintIslandEnds[island - 1]
  297. + mContactIslandEnds[island] - mContactIslandEnds[island - 1];
  298. }
  299. else if (mNumContacts > 0)
  300. {
  301. num_constraints[0] = mContactIslandEnds[0];
  302. for (uint32 island = 1; island < mNumIslands; ++island)
  303. num_constraints[island] = mContactIslandEnds[island] - mContactIslandEnds[island - 1];
  304. }
  305. else
  306. {
  307. num_constraints[0] = mConstraintIslandEnds[0];
  308. for (uint32 island = 1; island < mNumIslands; ++island)
  309. num_constraints[island] = mConstraintIslandEnds[island] - mConstraintIslandEnds[island - 1];
  310. }
  311. // Sort so the biggest islands go first, this means that the jobs that take longest will be running
  312. // first which improves the chance that all jobs finish at the same time.
  313. sort(mIslandsSorted, mIslandsSorted + mNumIslands, [num_constraints](uint32 inLHS, uint32 inRHS) {
  314. return num_constraints[inLHS] > num_constraints[inRHS];
  315. });
  316. inTempAllocator->Free(num_constraints, mNumIslands * sizeof(uint32));
  317. }
  318. }
  319. void IslandBuilder::Finalize(const BodyID *inActiveBodies, uint32 inNumActiveBodies, uint32 inNumContacts, TempAllocator *inTempAllocator)
  320. {
  321. JPH_PROFILE_FUNCTION();
  322. mNumContacts = inNumContacts;
  323. BuildBodyIslands(inActiveBodies, inNumActiveBodies, inTempAllocator);
  324. BuildConstraintIslands(mConstraintLinks, mNumConstraints, mConstraintIslands, mConstraintIslandEnds, inTempAllocator);
  325. BuildConstraintIslands(mContactLinks, mNumContacts, mContactIslands, mContactIslandEnds, inTempAllocator);
  326. SortIslands(inTempAllocator);
  327. }
  328. void IslandBuilder::GetBodiesInIsland(uint32 inIslandIndex, BodyID *&outBodiesBegin, BodyID *&outBodiesEnd) const
  329. {
  330. JPH_ASSERT(inIslandIndex < mNumIslands);
  331. uint32 sorted_index = mIslandsSorted != nullptr? mIslandsSorted[inIslandIndex] : inIslandIndex;
  332. outBodiesBegin = sorted_index > 0? mBodyIslands + mBodyIslandEnds[sorted_index - 1] : mBodyIslands;
  333. outBodiesEnd = mBodyIslands + mBodyIslandEnds[sorted_index];
  334. }
  335. bool IslandBuilder::GetConstraintsInIsland(uint32 inIslandIndex, uint32 *&outConstraintsBegin, uint32 *&outConstraintsEnd) const
  336. {
  337. JPH_ASSERT(inIslandIndex < mNumIslands);
  338. if (mNumConstraints == 0)
  339. {
  340. outConstraintsBegin = nullptr;
  341. outConstraintsEnd = nullptr;
  342. return false;
  343. }
  344. else
  345. {
  346. uint32 sorted_index = mIslandsSorted[inIslandIndex];
  347. outConstraintsBegin = sorted_index > 0? mConstraintIslands + mConstraintIslandEnds[sorted_index - 1] : mConstraintIslands;
  348. outConstraintsEnd = mConstraintIslands + mConstraintIslandEnds[sorted_index];
  349. return outConstraintsBegin != outConstraintsEnd;
  350. }
  351. }
  352. bool IslandBuilder::GetContactsInIsland(uint32 inIslandIndex, uint32 *&outContactsBegin, uint32 *&outContactsEnd) const
  353. {
  354. JPH_ASSERT(inIslandIndex < mNumIslands);
  355. if (mNumContacts == 0)
  356. {
  357. outContactsBegin = nullptr;
  358. outContactsEnd = nullptr;
  359. return false;
  360. }
  361. else
  362. {
  363. uint32 sorted_index = mIslandsSorted[inIslandIndex];
  364. outContactsBegin = sorted_index > 0? mContactIslands + mContactIslandEnds[sorted_index - 1] : mContactIslands;
  365. outContactsEnd = mContactIslands + mContactIslandEnds[sorted_index];
  366. return outContactsBegin != outContactsEnd;
  367. }
  368. }
  369. void IslandBuilder::ResetIslands(TempAllocator *inTempAllocator)
  370. {
  371. JPH_PROFILE_FUNCTION();
  372. if (mIslandsSorted != nullptr)
  373. {
  374. inTempAllocator->Free(mIslandsSorted, mNumIslands * sizeof(uint32));
  375. mIslandsSorted = nullptr;
  376. }
  377. if (mContactIslands != nullptr)
  378. {
  379. inTempAllocator->Free(mContactIslandEnds, mNumIslands * sizeof(uint32));
  380. mContactIslandEnds = nullptr;
  381. inTempAllocator->Free(mContactIslands, mNumContacts * sizeof(uint32));
  382. mContactIslands = nullptr;
  383. }
  384. if (mConstraintIslands != nullptr)
  385. {
  386. inTempAllocator->Free(mConstraintIslandEnds, mNumIslands * sizeof(uint32));
  387. mConstraintIslandEnds = nullptr;
  388. inTempAllocator->Free(mConstraintIslands, mNumConstraints * sizeof(uint32));
  389. mConstraintIslands = nullptr;
  390. }
  391. inTempAllocator->Free(mBodyIslandEnds, mNumIslands * sizeof(uint32));
  392. mBodyIslandEnds = nullptr;
  393. inTempAllocator->Free(mBodyIslands, mNumActiveBodies * sizeof(uint32));
  394. mBodyIslands = nullptr;
  395. inTempAllocator->Free(mConstraintLinks, mNumConstraints * sizeof(uint32));
  396. mConstraintLinks = nullptr;
  397. #ifdef JPH_VALIDATE_ISLAND_BUILDER
  398. inTempAllocator->Free(mLinkValidation, mMaxContacts * sizeof(LinkValidation));
  399. mLinkValidation = nullptr;
  400. #endif
  401. inTempAllocator->Free(mContactLinks, mMaxContacts * sizeof(uint32));
  402. mContactLinks = nullptr;
  403. mNumActiveBodies = 0;
  404. mNumConstraints = 0;
  405. mMaxContacts = 0;
  406. mNumContacts = 0;
  407. mNumIslands = 0;
  408. }
  409. } // JPH