LargeIslandSplitter.h 8.0 KB

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