LargeIslandSplitter.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Core/NonCopyable.h>
  5. #include <Jolt/Core/Atomics.h>
  6. JPH_NAMESPACE_BEGIN
  7. class Body;
  8. class BodyID;
  9. class IslandBuilder;
  10. class TempAllocator;
  11. class Constraint;
  12. class BodyManager;
  13. class ContactConstraintManager;
  14. /// Assigns bodies in large islands to multiple groups that can run in parallel
  15. ///
  16. /// This basically implements what is described in: High-Performance Physical Simulations on Next-Generation Architecture with Many Cores by Chen et al.
  17. /// See: http://web.eecs.umich.edu/~msmelyan/papers/physsim_onmanycore_itj.pdf section "PARALLELIZATION METHODOLOGY"
  18. class LargeIslandSplitter : public NonCopyable
  19. {
  20. private:
  21. using SplitMask = uint32;
  22. public:
  23. static constexpr uint cNumSplits = sizeof(SplitMask) * 8;
  24. static constexpr uint cNonParallelSplitIdx = cNumSplits - 1;
  25. static constexpr uint cLargeIslandTreshold = 128; ///< If the number of constraints + contacts in an island is larger than this, we will try to split the island
  26. /// Status code for retrieving a batch
  27. enum class EStatus
  28. {
  29. WaitingForBatch, ///< Work is expected to be available later
  30. BatchRetrieved, ///< Work is being returned
  31. AllBatchesDone, ///< No further work is expected from this
  32. };
  33. /// Describes a split of constraints and contacts
  34. struct Split
  35. {
  36. inline uint GetNumContacts() const { return mContactBufferEnd - mContactBufferBegin; }
  37. inline uint GetNumConstraints() const { return mConstraintBufferEnd - mConstraintBufferBegin; }
  38. inline uint GetNumItems() const { return GetNumContacts() + GetNumConstraints(); }
  39. uint32 mContactBufferBegin; ///< Begin of the contact buffer (offset relative to mContactAndConstraintIndices)
  40. uint32 mContactBufferEnd; ///< End of the contact buffer
  41. uint32 mConstraintBufferBegin; ///< Begin of the constraint buffer (offset relative to mContactAndConstraintIndices)
  42. uint32 mConstraintBufferEnd; ///< End of the constraint buffer
  43. };
  44. /// Structure that describes the resulting splits from the large island splitter
  45. class Splits
  46. {
  47. public:
  48. inline uint GetNumSplits() const
  49. {
  50. return mNumSplits;
  51. }
  52. inline void GetConstraintsInSplit(uint inSplitIndex, uint32 &outConstraintsBegin, uint32 &outConstraintsEnd) const
  53. {
  54. const Split &split = mSplits[inSplitIndex];
  55. outConstraintsBegin = split.mConstraintBufferBegin;
  56. outConstraintsEnd = split.mConstraintBufferEnd;
  57. }
  58. inline void GetContactsInSplit(uint inSplitIndex, uint32 &outContactsBegin, uint32 &outContactsEnd) const
  59. {
  60. const Split &split = mSplits[inSplitIndex];
  61. outContactsBegin = split.mContactBufferBegin;
  62. outContactsEnd = split.mContactBufferEnd;
  63. }
  64. /// Reset current status so that no work can be picked up from this split
  65. inline void ResetStatus()
  66. {
  67. mStatus.store(StatusItemMask, memory_order_relaxed);
  68. }
  69. /// Make the first batch available to other threads
  70. inline void StartFirstBatch()
  71. {
  72. uint split_index = mNumSplits > 0? 0 : cNonParallelSplitIdx;
  73. mStatus.store(uint64(split_index) << StatusSplitShift, memory_order_release);
  74. }
  75. /// Fetch the next batch to process
  76. EStatus FetchNextBatch(uint32 &outConstraintsBegin, uint32 &outConstraintsEnd, uint32 &outContactsBegin, uint32 &outContactsEnd, bool &outFirstIteration);
  77. /// Mark a batch as processed
  78. void MarkBatchProcessed(uint inNumProcessed, bool &outLastIteration, bool &outFinalBatch);
  79. enum EIterationStatus : uint64
  80. {
  81. StatusIterationMask = 0xffff000000000000,
  82. StatusIterationShift = 48,
  83. StatusSplitMask = 0x0000ffff00000000,
  84. StatusSplitShift = 32,
  85. StatusItemMask = 0x00000000ffffffff,
  86. };
  87. static inline int sGetIteration(uint64 inStatus)
  88. {
  89. return int((inStatus & StatusIterationMask) >> StatusIterationShift);
  90. }
  91. static inline uint sGetSplit(uint64 inStatus)
  92. {
  93. return uint((inStatus & StatusSplitMask) >> StatusSplitShift);
  94. }
  95. static inline uint sGetItem(uint64 inStatus)
  96. {
  97. return uint(inStatus & StatusItemMask);
  98. }
  99. Split mSplits[cNumSplits]; ///< Data per split
  100. uint32 mIslandIndex; ///< Index of the island that was split
  101. uint mNumSplits; ///< Number of splits that were created (excluding the non-parallel split)
  102. int mNumIterations; ///< Number of iterations to do
  103. int mNumVelocitySteps; ///< Number of velocity steps to do (cached for 2nd sub step)
  104. int mNumPositionSteps; ///< Number of position steps to do
  105. atomic<uint64> mStatus; ///< Status of the split, see EIterationStatus
  106. atomic<uint> mItemsProcessed; ///< Number of items that have been marked as processed
  107. };
  108. public:
  109. /// Destructor
  110. ~LargeIslandSplitter();
  111. /// Prepare the island splitter by allocating memory
  112. void Prepare(const IslandBuilder &inIslandBuilder, uint32 inNumActiveBodies, TempAllocator *inTempAllocator);
  113. /// Assign two bodies to a split. Returns the split index.
  114. uint AssignSplit(const Body *inBody1, const Body *inBody2);
  115. /// Force a body to be in a non parallel split. Returns the split index.
  116. uint AssignToNonParallelSplit(const Body *inBody);
  117. /// Splits up an island, the created splits will be added to the list of batches and can be fetched with FetchNextBatch. Returns false if the island did not need splitting.
  118. bool SplitIsland(uint32 inIslandIndex, const IslandBuilder &inIslandBuilder, const BodyManager &inBodyManager, const ContactConstraintManager &inContactManager, Constraint **inActiveConstraints, int inNumVelocitySteps, int inNumPositionSteps);
  119. /// Fetch the next batch to process, returns a handle in outSplitIslandIndex that must be provided to MarkBatchProcessed when complete
  120. EStatus FetchNextBatch(uint &outSplitIslandIndex, uint32 *&outConstraintsBegin, uint32 *&outConstraintsEnd, uint32 *&outContactsBegin, uint32 *&outContactsEnd, bool &outFirstIteration);
  121. /// Mark a batch as processed
  122. void MarkBatchProcessed(uint inSplitIslandIndex, const uint32 *inConstraintsBegin, const uint32 *inConstraintsEnd, const uint32 *inContactsBegin, const uint32 *inContactsEnd, bool &outLastIteration, bool &outFinalBatch);
  123. /// Get the island index of the island that was split for a particular split island index
  124. inline uint32 GetIslandIndex(uint inSplitIslandIndex) const
  125. {
  126. JPH_ASSERT(inSplitIslandIndex < mNumSplitIslands);
  127. return mSplitIslands[inSplitIslandIndex].mIslandIndex;
  128. }
  129. /// Prepare the island splitter for iterating over the split islands again for position solving. Marks all batches as startable.
  130. void PrepareForSolvePositions();
  131. /// Reset the island splitter
  132. void Reset(TempAllocator *inTempAllocator);
  133. private:
  134. static constexpr uint cSplitCombineTreshold = 32; ///< If the number of constraints + contacts in a split is lower than this, we will merge this split into the 'non-parallel split'
  135. static constexpr uint cBatchSize = 16; ///< Number of items to process in a constraint batch
  136. uint32 mNumActiveBodies = 0; ///< Cached number of active bodies
  137. SplitMask * mSplitMasks = nullptr; ///< Bits that indicate for each body in the BodyManager::mActiveBodies list which split they already belong to
  138. uint32 * mContactAndConstaintsSplitIdx = nullptr; ///< Buffer to store the split index per constraint or contact
  139. uint32 * mContactAndConstraintIndices = nullptr; ///< Buffer to store the ordered constraint indices per split
  140. uint mContactAndConstraintsSize = 0; ///< Total size of mContactAndConstraintsSplitIdx and mContactAndConstraintIndices
  141. atomic<uint> mContactAndConstraintsNextFree { 0 }; ///< Next element that is free in both buffers
  142. uint mNumSplitIslands = 0; ///< Total number of islands that required splitting
  143. Splits * mSplitIslands = nullptr; ///< List of islands that required splitting
  144. atomic<uint> mNextSplitIsland = 0; ///< Next split island to pick from mSplitIslands
  145. };
  146. JPH_NAMESPACE_END