PhysicsSystem.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426
  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/PhysicsSystem.h>
  6. #include <Jolt/Physics/PhysicsSettings.h>
  7. #include <Jolt/Physics/PhysicsUpdateContext.h>
  8. #include <Jolt/Physics/PhysicsStepListener.h>
  9. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h>
  10. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>
  11. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  12. #include <Jolt/Physics/Collision/AABoxCast.h>
  13. #include <Jolt/Physics/Collision/ShapeCast.h>
  14. #include <Jolt/Physics/Collision/CollideShape.h>
  15. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  16. #include <Jolt/Physics/Collision/CastResult.h>
  17. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  18. #include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>
  19. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  20. #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  21. #include <Jolt/Physics/DeterminismLog.h>
  22. #include <Jolt/Geometry/RayAABox.h>
  23. #include <Jolt/Core/JobSystem.h>
  24. #include <Jolt/Core/TempAllocator.h>
  25. #include <Jolt/Core/QuickSort.h>
  26. #ifdef JPH_DEBUG_RENDERER
  27. #include <Jolt/Renderer/DebugRenderer.h>
  28. #endif // JPH_DEBUG_RENDERER
  29. JPH_NAMESPACE_BEGIN
  30. #ifdef JPH_DEBUG_RENDERER
  31. bool PhysicsSystem::sDrawMotionQualityLinearCast = false;
  32. #endif // JPH_DEBUG_RENDERER
  33. //#define BROAD_PHASE BroadPhaseBruteForce
  34. #define BROAD_PHASE BroadPhaseQuadTree
  35. static const Color cColorUpdateBroadPhaseFinalize = Color::sGetDistinctColor(1);
  36. static const Color cColorUpdateBroadPhasePrepare = Color::sGetDistinctColor(2);
  37. static const Color cColorFindCollisions = Color::sGetDistinctColor(3);
  38. static const Color cColorApplyGravity = Color::sGetDistinctColor(4);
  39. static const Color cColorSetupVelocityConstraints = Color::sGetDistinctColor(5);
  40. static const Color cColorBuildIslandsFromConstraints = Color::sGetDistinctColor(6);
  41. static const Color cColorDetermineActiveConstraints = Color::sGetDistinctColor(7);
  42. static const Color cColorFinalizeIslands = Color::sGetDistinctColor(8);
  43. static const Color cColorContactRemovedCallbacks = Color::sGetDistinctColor(9);
  44. static const Color cColorBodySetIslandIndex = Color::sGetDistinctColor(10);
  45. static const Color cColorStartNextStep = Color::sGetDistinctColor(11);
  46. static const Color cColorSolveVelocityConstraints = Color::sGetDistinctColor(12);
  47. static const Color cColorPreIntegrateVelocity = Color::sGetDistinctColor(13);
  48. static const Color cColorIntegrateVelocity = Color::sGetDistinctColor(14);
  49. static const Color cColorPostIntegrateVelocity = Color::sGetDistinctColor(15);
  50. static const Color cColorResolveCCDContacts = Color::sGetDistinctColor(16);
  51. static const Color cColorSolvePositionConstraints = Color::sGetDistinctColor(17);
  52. static const Color cColorStartNextSubStep = Color::sGetDistinctColor(18);
  53. static const Color cColorFindCCDContacts = Color::sGetDistinctColor(19);
  54. static const Color cColorStepListeners = Color::sGetDistinctColor(20);
  55. PhysicsSystem::~PhysicsSystem()
  56. {
  57. // Remove broadphase
  58. delete mBroadPhase;
  59. }
  60. void PhysicsSystem::Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter)
  61. {
  62. mObjectVsBroadPhaseLayerFilter = &inObjectVsBroadPhaseLayerFilter;
  63. mObjectLayerPairFilter = &inObjectLayerPairFilter;
  64. // Initialize body manager
  65. mBodyManager.Init(inMaxBodies, inNumBodyMutexes, inBroadPhaseLayerInterface);
  66. // Create broadphase
  67. mBroadPhase = new BROAD_PHASE();
  68. mBroadPhase->Init(&mBodyManager, inBroadPhaseLayerInterface);
  69. // Init contact constraint manager
  70. mContactManager.Init(inMaxBodyPairs, inMaxContactConstraints);
  71. // Init islands builder
  72. mIslandBuilder.Init(inMaxBodies);
  73. // Initialize body interface
  74. mBodyInterfaceLocking.Init(mBodyLockInterfaceLocking, mBodyManager, *mBroadPhase);
  75. mBodyInterfaceNoLock.Init(mBodyLockInterfaceNoLock, mBodyManager, *mBroadPhase);
  76. // Initialize narrow phase query
  77. mNarrowPhaseQueryLocking.Init(mBodyLockInterfaceLocking, *mBroadPhase);
  78. mNarrowPhaseQueryNoLock.Init(mBodyLockInterfaceNoLock, *mBroadPhase);
  79. }
  80. void PhysicsSystem::OptimizeBroadPhase()
  81. {
  82. mBroadPhase->Optimize();
  83. }
  84. void PhysicsSystem::AddStepListener(PhysicsStepListener *inListener)
  85. {
  86. lock_guard lock(mStepListenersMutex);
  87. JPH_ASSERT(find(mStepListeners.begin(), mStepListeners.end(), inListener) == mStepListeners.end());
  88. mStepListeners.push_back(inListener);
  89. }
  90. void PhysicsSystem::RemoveStepListener(PhysicsStepListener *inListener)
  91. {
  92. lock_guard lock(mStepListenersMutex);
  93. StepListeners::iterator i = find(mStepListeners.begin(), mStepListeners.end(), inListener);
  94. JPH_ASSERT(i != mStepListeners.end());
  95. *i = mStepListeners.back();
  96. mStepListeners.pop_back();
  97. }
  98. EPhysicsUpdateError PhysicsSystem::Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem)
  99. {
  100. JPH_PROFILE_FUNCTION();
  101. JPH_DET_LOG("PhysicsSystem::Update: dt: " << inDeltaTime << " steps: " << inCollisionSteps << " substeps: " << inIntegrationSubSteps);
  102. JPH_ASSERT(inDeltaTime >= 0.0f);
  103. JPH_ASSERT(inIntegrationSubSteps <= PhysicsUpdateContext::cMaxSubSteps);
  104. // Sync point for the broadphase. This will allow it to do clean up operations without having any mutexes locked yet.
  105. mBroadPhase->FrameSync();
  106. // If there are no active bodies or there's no time delta
  107. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  108. if (num_active_bodies == 0 || inDeltaTime <= 0.0f)
  109. {
  110. mBodyManager.LockAllBodies();
  111. // Update broadphase
  112. mBroadPhase->LockModifications();
  113. BroadPhase::UpdateState update_state = mBroadPhase->UpdatePrepare();
  114. mBroadPhase->UpdateFinalize(update_state);
  115. mBroadPhase->UnlockModifications();
  116. // Call contact removal callbacks from contacts that existed in the previous update
  117. mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(0, 0);
  118. mBodyManager.UnlockAllBodies();
  119. return EPhysicsUpdateError::None;
  120. }
  121. // Calculate ratio between current and previous frame delta time to scale initial constraint forces
  122. float sub_step_delta_time = inDeltaTime / (inCollisionSteps * inIntegrationSubSteps);
  123. float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart && mPreviousSubStepDeltaTime > 0.0f? sub_step_delta_time / mPreviousSubStepDeltaTime : 0.0f;
  124. mPreviousSubStepDeltaTime = sub_step_delta_time;
  125. // Create the context used for passing information between jobs
  126. PhysicsUpdateContext context(*inTempAllocator);
  127. context.mPhysicsSystem = this;
  128. context.mJobSystem = inJobSystem;
  129. context.mBarrier = inJobSystem->CreateBarrier();
  130. context.mIslandBuilder = &mIslandBuilder;
  131. context.mStepDeltaTime = inDeltaTime / inCollisionSteps;
  132. context.mSubStepDeltaTime = sub_step_delta_time;
  133. context.mWarmStartImpulseRatio = warm_start_impulse_ratio;
  134. context.mUseLargeIslandSplitter = mPhysicsSettings.mUseLargeIslandSplitter && inIntegrationSubSteps == 1; // Only use large island splitter if we don't have sub steps, not yet supported
  135. context.mSteps.resize(inCollisionSteps);
  136. // Allocate space for body pairs
  137. JPH_ASSERT(context.mBodyPairs == nullptr);
  138. context.mBodyPairs = static_cast<BodyPair *>(inTempAllocator->Allocate(sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs));
  139. // Lock all bodies for write so that we can freely touch them
  140. mStepListenersMutex.lock();
  141. mBodyManager.LockAllBodies();
  142. mBroadPhase->LockModifications();
  143. // Get max number of concurrent jobs
  144. int max_concurrency = context.GetMaxConcurrency();
  145. // Calculate how many step listener jobs we spawn
  146. int num_step_listener_jobs = mStepListeners.empty()? 0 : max(1, min((int)mStepListeners.size() / mPhysicsSettings.mStepListenersBatchSize / mPhysicsSettings.mStepListenerBatchesPerJob, max_concurrency));
  147. // Number of gravity jobs depends on the amount of active bodies.
  148. // Launch max 1 job per batch of active bodies
  149. // Leave 1 thread for update broadphase prepare and 1 for determine active constraints
  150. int num_apply_gravity_jobs = max(1, min(((int)num_active_bodies + cApplyGravityBatchSize - 1) / cApplyGravityBatchSize, max_concurrency - 2));
  151. // Number of determine active constraints jobs to run depends on number of constraints.
  152. // Leave 1 thread for update broadphase prepare and 1 for apply gravity
  153. int num_determine_active_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cDetermineActiveConstraintsBatchSize - 1) / cDetermineActiveConstraintsBatchSize, max_concurrency - 2));
  154. // Number of find collisions jobs to run depends on number of active bodies.
  155. // Note that when we have more than 1 thread, we always spawn at least 2 find collisions jobs so that the first job can wait for build islands from constraints
  156. // (which may activate additional bodies that need to be processed) while the second job can start processing collision work.
  157. int num_find_collisions_jobs = max(max_concurrency == 1? 1 : 2, min(((int)num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_concurrency));
  158. // Number of integrate velocity jobs depends on number of active bodies.
  159. int num_integrate_velocity_jobs = max(1, min(((int)num_active_bodies + cIntegrateVelocityBatchSize - 1) / cIntegrateVelocityBatchSize, max_concurrency));
  160. {
  161. JPH_PROFILE("Build Jobs");
  162. // Iterate over collision steps
  163. for (int step_idx = 0; step_idx < inCollisionSteps; ++step_idx)
  164. {
  165. bool is_first_step = step_idx == 0;
  166. bool is_last_step = step_idx == inCollisionSteps - 1;
  167. PhysicsUpdateContext::Step &step = context.mSteps[step_idx];
  168. step.mContext = &context;
  169. step.mSubSteps.resize(inIntegrationSubSteps);
  170. // Create job to do broadphase finalization
  171. // This job must finish before integrating velocities. Until then the positions will not be updated neither will bodies be added / removed.
  172. step.mUpdateBroadphaseFinalize = inJobSystem->CreateJob("UpdateBroadPhaseFinalize", cColorUpdateBroadPhaseFinalize, [&context, &step]()
  173. {
  174. // Validate that all find collision jobs have stopped
  175. JPH_ASSERT(step.mActiveFindCollisionJobs == 0);
  176. // Finalize the broadphase update
  177. context.mPhysicsSystem->mBroadPhase->UpdateFinalize(step.mBroadPhaseUpdateState);
  178. // Signal that it is done
  179. step.mSubSteps[0].mPreIntegrateVelocity.RemoveDependency();
  180. }, num_find_collisions_jobs + 2); // depends on: find collisions, broadphase prepare update, finish building jobs
  181. // The immediate jobs below are only immediate for the first step, the all finished job will kick them for the next step
  182. int previous_step_dependency_count = is_first_step? 0 : 1;
  183. // Start job immediately: Start the prepare broadphase
  184. // Must be done under body lock protection since the order is body locks then broadphase mutex
  185. // If this is turned around the RemoveBody call will hang since it locks in that order
  186. step.mBroadPhasePrepare = inJobSystem->CreateJob("UpdateBroadPhasePrepare", cColorUpdateBroadPhasePrepare, [&context, &step]()
  187. {
  188. // Prepare the broadphase update
  189. step.mBroadPhaseUpdateState = context.mPhysicsSystem->mBroadPhase->UpdatePrepare();
  190. // Now the finalize can run (if other dependencies are met too)
  191. step.mUpdateBroadphaseFinalize.RemoveDependency();
  192. }, previous_step_dependency_count);
  193. // This job will find all collisions
  194. step.mBodyPairQueues.resize(max_concurrency);
  195. step.mMaxBodyPairsPerQueue = mPhysicsSettings.mMaxInFlightBodyPairs / max_concurrency;
  196. step.mActiveFindCollisionJobs = ~PhysicsUpdateContext::JobMask(0) >> (sizeof(PhysicsUpdateContext::JobMask) * 8 - num_find_collisions_jobs);
  197. step.mFindCollisions.resize(num_find_collisions_jobs);
  198. for (int i = 0; i < num_find_collisions_jobs; ++i)
  199. {
  200. // Build islands from constraints may activate additional bodies, so the first job will wait for this to finish in order to not miss any active bodies
  201. int num_dep_build_islands_from_constraints = i == 0? 1 : 0;
  202. step.mFindCollisions[i] = inJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [&step, i]()
  203. {
  204. step.mContext->mPhysicsSystem->JobFindCollisions(&step, i);
  205. }, num_apply_gravity_jobs + num_determine_active_constraints_jobs + 1 + num_dep_build_islands_from_constraints); // depends on: apply gravity, determine active constraints, finish building jobs, build islands from constraints
  206. }
  207. if (is_first_step)
  208. {
  209. #ifdef JPH_ENABLE_ASSERTS
  210. // Don't allow write operations to the active bodies list
  211. mBodyManager.SetActiveBodiesLocked(true);
  212. #endif
  213. // Store the number of active bodies at the start of the step
  214. step.mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies();
  215. // Lock all constraints
  216. mConstraintManager.LockAllConstraints();
  217. // Allocate memory for storing the active constraints
  218. JPH_ASSERT(context.mActiveConstraints == nullptr);
  219. context.mActiveConstraints = static_cast<Constraint **>(inTempAllocator->Allocate(mConstraintManager.GetNumConstraints() * sizeof(Constraint *)));
  220. // Prepare contact buffer
  221. mContactManager.PrepareConstraintBuffer(&context);
  222. // Setup island builder
  223. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), context.mTempAllocator);
  224. }
  225. // This job applies gravity to all active bodies
  226. step.mApplyGravity.resize(num_apply_gravity_jobs);
  227. for (int i = 0; i < num_apply_gravity_jobs; ++i)
  228. step.mApplyGravity[i] = inJobSystem->CreateJob("ApplyGravity", cColorApplyGravity, [&context, &step]()
  229. {
  230. context.mPhysicsSystem->JobApplyGravity(&context, &step);
  231. JobHandle::sRemoveDependencies(step.mFindCollisions);
  232. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  233. // This job will setup velocity constraints for non-collision constraints
  234. step.mSetupVelocityConstraints = inJobSystem->CreateJob("SetupVelocityConstraints", cColorSetupVelocityConstraints, [&context, &step]()
  235. {
  236. context.mPhysicsSystem->JobSetupVelocityConstraints(context.mSubStepDeltaTime, &step);
  237. JobHandle::sRemoveDependencies(step.mSubSteps[0].mSolveVelocityConstraints);
  238. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  239. // This job will build islands from constraints
  240. step.mBuildIslandsFromConstraints = inJobSystem->CreateJob("BuildIslandsFromConstraints", cColorBuildIslandsFromConstraints, [&context, &step]()
  241. {
  242. context.mPhysicsSystem->JobBuildIslandsFromConstraints(&context, &step);
  243. step.mFindCollisions[0].RemoveDependency(); // The first collisions job cannot start running until we've finished building islands and activated all bodies
  244. step.mFinalizeIslands.RemoveDependency();
  245. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  246. // This job determines active constraints
  247. step.mDetermineActiveConstraints.resize(num_determine_active_constraints_jobs);
  248. for (int i = 0; i < num_determine_active_constraints_jobs; ++i)
  249. step.mDetermineActiveConstraints[i] = inJobSystem->CreateJob("DetermineActiveConstraints", cColorDetermineActiveConstraints, [&context, &step]()
  250. {
  251. context.mPhysicsSystem->JobDetermineActiveConstraints(&step);
  252. step.mSetupVelocityConstraints.RemoveDependency();
  253. step.mBuildIslandsFromConstraints.RemoveDependency();
  254. // Kick find collisions last as they will use up all CPU cores leaving no space for the previous 2 jobs
  255. JobHandle::sRemoveDependencies(step.mFindCollisions);
  256. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  257. // This job calls the step listeners
  258. step.mStepListeners.resize(num_step_listener_jobs);
  259. for (int i = 0; i < num_step_listener_jobs; ++i)
  260. step.mStepListeners[i] = inJobSystem->CreateJob("StepListeners", cColorStepListeners, [&context, &step]()
  261. {
  262. // Call the step listeners
  263. context.mPhysicsSystem->JobStepListeners(&step);
  264. // Kick apply gravity and determine active constraint jobs
  265. JobHandle::sRemoveDependencies(step.mApplyGravity);
  266. JobHandle::sRemoveDependencies(step.mDetermineActiveConstraints);
  267. }, previous_step_dependency_count);
  268. // Unblock the previous step
  269. if (!is_first_step)
  270. context.mSteps[step_idx - 1].mStartNextStep.RemoveDependency();
  271. // This job will finalize the simulation islands
  272. step.mFinalizeIslands = inJobSystem->CreateJob("FinalizeIslands", cColorFinalizeIslands, [&context, &step]()
  273. {
  274. // Validate that all find collision jobs have stopped
  275. JPH_ASSERT(step.mActiveFindCollisionJobs == 0);
  276. context.mPhysicsSystem->JobFinalizeIslands(&context);
  277. JobHandle::sRemoveDependencies(step.mSubSteps[0].mSolveVelocityConstraints);
  278. step.mBodySetIslandIndex.RemoveDependency();
  279. }, num_find_collisions_jobs + 2); // depends on: find collisions, build islands from constraints, finish building jobs
  280. // Unblock previous job
  281. // Note: technically we could release find collisions here but we don't want to because that could make them run before 'setup velocity constraints' which means that job won't have a thread left
  282. step.mBuildIslandsFromConstraints.RemoveDependency();
  283. // This job will call the contact removed callbacks
  284. step.mContactRemovedCallbacks = inJobSystem->CreateJob("ContactRemovedCallbacks", cColorContactRemovedCallbacks, [&context, &step]()
  285. {
  286. context.mPhysicsSystem->JobContactRemovedCallbacks(&step);
  287. if (step.mStartNextStep.IsValid())
  288. step.mStartNextStep.RemoveDependency();
  289. }, 1); // depends on the find ccd contacts of the last sub step
  290. // This job will set the island index on each body (only used for debug drawing purposes)
  291. // It will also delete any bodies that have been destroyed in the last frame
  292. step.mBodySetIslandIndex = inJobSystem->CreateJob("BodySetIslandIndex", cColorBodySetIslandIndex, [&context, &step]()
  293. {
  294. context.mPhysicsSystem->JobBodySetIslandIndex();
  295. if (step.mStartNextStep.IsValid())
  296. step.mStartNextStep.RemoveDependency();
  297. }, 1); // depends on: finalize islands
  298. // Job to start the next collision step
  299. if (!is_last_step)
  300. {
  301. PhysicsUpdateContext::Step *next_step = &context.mSteps[step_idx + 1];
  302. step.mStartNextStep = inJobSystem->CreateJob("StartNextStep", cColorStartNextStep, [this, next_step]()
  303. {
  304. #ifdef _DEBUG
  305. // Validate that the cached bounds are correct
  306. mBodyManager.ValidateActiveBodyBounds();
  307. #endif // _DEBUG
  308. // Store the number of active bodies at the start of the step
  309. next_step->mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies();
  310. // Clear the large island splitter
  311. TempAllocator *temp_allocator = next_step->mContext->mTempAllocator;
  312. mLargeIslandSplitter.Reset(temp_allocator);
  313. // Clear the island builder
  314. mIslandBuilder.ResetIslands(temp_allocator);
  315. // Setup island builder
  316. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), temp_allocator);
  317. // Restart the contact manager
  318. mContactManager.RecycleConstraintBuffer();
  319. // Kick the jobs of the next step (in the same order as the first step)
  320. next_step->mBroadPhasePrepare.RemoveDependency();
  321. if (next_step->mStepListeners.empty())
  322. {
  323. // Kick the gravity and active constraints jobs immediately
  324. JobHandle::sRemoveDependencies(next_step->mApplyGravity);
  325. JobHandle::sRemoveDependencies(next_step->mDetermineActiveConstraints);
  326. }
  327. else
  328. {
  329. // Kick the step listeners job first
  330. JobHandle::sRemoveDependencies(next_step->mStepListeners);
  331. }
  332. }, max_concurrency + 3); // depends on: solve position constraints of the last step, body set island index, contact removed callbacks, finish building the previous step
  333. }
  334. // Create solve jobs for each of the integration sub steps
  335. for (int sub_step_idx = 0; sub_step_idx < inIntegrationSubSteps; ++sub_step_idx)
  336. {
  337. bool is_first_sub_step = sub_step_idx == 0;
  338. bool is_last_sub_step = sub_step_idx == inIntegrationSubSteps - 1;
  339. PhysicsUpdateContext::SubStep &sub_step = step.mSubSteps[sub_step_idx];
  340. sub_step.mStep = &step;
  341. sub_step.mIsFirst = is_first_sub_step;
  342. sub_step.mIsLast = is_last_sub_step;
  343. sub_step.mIsFirstOfAll = is_first_step && is_first_sub_step;
  344. sub_step.mIsLastOfAll = is_last_step && is_last_sub_step;
  345. // This job will solve the velocity constraints
  346. int num_dependencies_solve_velocity_constraints = is_first_sub_step? 3 : 2; // in first sub step depends on: finalize islands, setup velocity constraints, in later sub steps depends on: previous sub step finished. For both: finish building jobs.
  347. sub_step.mSolveVelocityConstraints.resize(max_concurrency);
  348. for (int i = 0; i < max_concurrency; ++i)
  349. sub_step.mSolveVelocityConstraints[i] = inJobSystem->CreateJob("SolveVelocityConstraints", cColorSolveVelocityConstraints, [&context, &sub_step]()
  350. {
  351. context.mPhysicsSystem->JobSolveVelocityConstraints(&context, &sub_step);
  352. sub_step.mPreIntegrateVelocity.RemoveDependency();
  353. }, num_dependencies_solve_velocity_constraints);
  354. // Unblock previous jobs
  355. if (is_first_sub_step)
  356. {
  357. // Kick find collisions after setup velocity constraints because the former job will use up all CPU cores
  358. step.mSetupVelocityConstraints.RemoveDependency();
  359. JobHandle::sRemoveDependencies(step.mFindCollisions);
  360. // Finalize islands is a dependency on find collisions so it can go last
  361. step.mFinalizeIslands.RemoveDependency();
  362. }
  363. else
  364. {
  365. step.mSubSteps[sub_step_idx - 1].mStartNextSubStep.RemoveDependency();
  366. }
  367. // This job will prepare the position update of all active bodies
  368. int num_dependencies_integrate_velocity = is_first_sub_step? 2 + max_concurrency : 1 + max_concurrency; // depends on: broadphase update finalize in first step, solve velocity constraints in all steps. For both: finish building jobs.
  369. sub_step.mPreIntegrateVelocity = inJobSystem->CreateJob("PreIntegrateVelocity", cColorPreIntegrateVelocity, [&context, &sub_step]()
  370. {
  371. context.mPhysicsSystem->JobPreIntegrateVelocity(&context, &sub_step);
  372. JobHandle::sRemoveDependencies(sub_step.mIntegrateVelocity);
  373. }, num_dependencies_integrate_velocity);
  374. // Unblock previous jobs
  375. if (is_first_sub_step)
  376. step.mUpdateBroadphaseFinalize.RemoveDependency();
  377. JobHandle::sRemoveDependencies(sub_step.mSolveVelocityConstraints);
  378. // This job will update the positions of all active bodies
  379. sub_step.mIntegrateVelocity.resize(num_integrate_velocity_jobs);
  380. for (int i = 0; i < num_integrate_velocity_jobs; ++i)
  381. sub_step.mIntegrateVelocity[i] = inJobSystem->CreateJob("IntegrateVelocity", cColorIntegrateVelocity, [&context, &sub_step]()
  382. {
  383. context.mPhysicsSystem->JobIntegrateVelocity(&context, &sub_step);
  384. sub_step.mPostIntegrateVelocity.RemoveDependency();
  385. }, 2); // depends on: pre integrate velocity, finish building jobs.
  386. // Unblock previous job
  387. sub_step.mPreIntegrateVelocity.RemoveDependency();
  388. // This job will finish the position update of all active bodies
  389. sub_step.mPostIntegrateVelocity = inJobSystem->CreateJob("PostIntegrateVelocity", cColorPostIntegrateVelocity, [&context, &sub_step]()
  390. {
  391. context.mPhysicsSystem->JobPostIntegrateVelocity(&context, &sub_step);
  392. sub_step.mResolveCCDContacts.RemoveDependency();
  393. }, num_integrate_velocity_jobs + 1); // depends on: integrate velocity, finish building jobs
  394. // Unblock previous jobs
  395. JobHandle::sRemoveDependencies(sub_step.mIntegrateVelocity);
  396. // This job will update the positions and velocities for all bodies that need continuous collision detection
  397. sub_step.mResolveCCDContacts = inJobSystem->CreateJob("ResolveCCDContacts", cColorResolveCCDContacts, [&context, &sub_step]()
  398. {
  399. context.mPhysicsSystem->JobResolveCCDContacts(&context, &sub_step);
  400. JobHandle::sRemoveDependencies(sub_step.mSolvePositionConstraints);
  401. }, 2); // depends on: integrate velocities, detect ccd contacts (added dynamically), finish building jobs.
  402. // Unblock previous job
  403. sub_step.mPostIntegrateVelocity.RemoveDependency();
  404. // Fixes up drift in positions and updates the broadphase with new body positions
  405. sub_step.mSolvePositionConstraints.resize(max_concurrency);
  406. for (int i = 0; i < max_concurrency; ++i)
  407. sub_step.mSolvePositionConstraints[i] = inJobSystem->CreateJob("SolvePositionConstraints", cColorSolvePositionConstraints, [&context, &sub_step]()
  408. {
  409. context.mPhysicsSystem->JobSolvePositionConstraints(&context, &sub_step);
  410. // Kick the next sub step
  411. if (sub_step.mStartNextSubStep.IsValid())
  412. sub_step.mStartNextSubStep.RemoveDependency();
  413. }, 2); // depends on: resolve ccd contacts, finish building jobs.
  414. // Unblock previous job.
  415. sub_step.mResolveCCDContacts.RemoveDependency();
  416. // This job starts the next sub step
  417. if (!is_last_sub_step)
  418. {
  419. PhysicsUpdateContext::SubStep &next_sub_step = step.mSubSteps[sub_step_idx + 1];
  420. sub_step.mStartNextSubStep = inJobSystem->CreateJob("StartNextSubStep", cColorStartNextSubStep, [&next_sub_step]()
  421. {
  422. // Kick velocity constraint solving for the next sub step
  423. JobHandle::sRemoveDependencies(next_sub_step.mSolveVelocityConstraints);
  424. }, max_concurrency + 1); // depends on: solve position constraints, finish building jobs.
  425. }
  426. else
  427. sub_step.mStartNextSubStep = step.mStartNextStep;
  428. // Unblock previous jobs
  429. JobHandle::sRemoveDependencies(sub_step.mSolvePositionConstraints);
  430. }
  431. }
  432. }
  433. // Build the list of jobs to wait for
  434. JobSystem::Barrier *barrier = context.mBarrier;
  435. {
  436. JPH_PROFILE("Build job barrier");
  437. StaticArray<JobHandle, cMaxPhysicsJobs> handles;
  438. for (const PhysicsUpdateContext::Step &step : context.mSteps)
  439. {
  440. if (step.mBroadPhasePrepare.IsValid())
  441. handles.push_back(step.mBroadPhasePrepare);
  442. for (const JobHandle &h : step.mStepListeners)
  443. handles.push_back(h);
  444. for (const JobHandle &h : step.mDetermineActiveConstraints)
  445. handles.push_back(h);
  446. for (const JobHandle &h : step.mApplyGravity)
  447. handles.push_back(h);
  448. for (const JobHandle &h : step.mFindCollisions)
  449. handles.push_back(h);
  450. if (step.mUpdateBroadphaseFinalize.IsValid())
  451. handles.push_back(step.mUpdateBroadphaseFinalize);
  452. handles.push_back(step.mSetupVelocityConstraints);
  453. handles.push_back(step.mBuildIslandsFromConstraints);
  454. handles.push_back(step.mFinalizeIslands);
  455. handles.push_back(step.mBodySetIslandIndex);
  456. for (const PhysicsUpdateContext::SubStep &sub_step : step.mSubSteps)
  457. {
  458. for (const JobHandle &h : sub_step.mSolveVelocityConstraints)
  459. handles.push_back(h);
  460. handles.push_back(sub_step.mPreIntegrateVelocity);
  461. for (const JobHandle &h : sub_step.mIntegrateVelocity)
  462. handles.push_back(h);
  463. handles.push_back(sub_step.mPostIntegrateVelocity);
  464. handles.push_back(sub_step.mResolveCCDContacts);
  465. for (const JobHandle &h : sub_step.mSolvePositionConstraints)
  466. handles.push_back(h);
  467. if (sub_step.mStartNextSubStep.IsValid())
  468. handles.push_back(sub_step.mStartNextSubStep);
  469. }
  470. handles.push_back(step.mContactRemovedCallbacks);
  471. }
  472. barrier->AddJobs(handles.data(), handles.size());
  473. }
  474. // Wait until all jobs finish
  475. // Note we don't just wait for the last job. If we would and another job
  476. // would be scheduled in between there is the possibility of a deadlock.
  477. // The other job could try to e.g. add/remove a body which would try to
  478. // lock a body mutex while this thread has already locked the mutex
  479. inJobSystem->WaitForJobs(barrier);
  480. // We're done with the barrier for this update
  481. inJobSystem->DestroyBarrier(barrier);
  482. #ifdef _DEBUG
  483. // Validate that the cached bounds are correct
  484. mBodyManager.ValidateActiveBodyBounds();
  485. #endif // _DEBUG
  486. // Clear the large island splitter
  487. mLargeIslandSplitter.Reset(inTempAllocator);
  488. // Clear the island builder
  489. mIslandBuilder.ResetIslands(inTempAllocator);
  490. // Clear the contact manager
  491. mContactManager.FinishConstraintBuffer();
  492. // Free active constraints
  493. inTempAllocator->Free(context.mActiveConstraints, mConstraintManager.GetNumConstraints() * sizeof(Constraint *));
  494. context.mActiveConstraints = nullptr;
  495. // Free body pairs
  496. inTempAllocator->Free(context.mBodyPairs, sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs);
  497. context.mBodyPairs = nullptr;
  498. // Unlock the broadphase
  499. mBroadPhase->UnlockModifications();
  500. // Unlock all constraints
  501. mConstraintManager.UnlockAllConstraints();
  502. #ifdef JPH_ENABLE_ASSERTS
  503. // Allow write operations to the active bodies list
  504. mBodyManager.SetActiveBodiesLocked(false);
  505. #endif
  506. // Unlock all bodies
  507. mBodyManager.UnlockAllBodies();
  508. // Unlock step listeners
  509. mStepListenersMutex.unlock();
  510. // Return any errors
  511. EPhysicsUpdateError errors = static_cast<EPhysicsUpdateError>(context.mErrors.load(memory_order_acquire));
  512. JPH_ASSERT(errors == EPhysicsUpdateError::None, "An error occured during the physics update, see EPhysicsUpdateError for more information");
  513. return errors;
  514. }
  515. void PhysicsSystem::JobStepListeners(PhysicsUpdateContext::Step *ioStep)
  516. {
  517. #ifdef JPH_ENABLE_ASSERTS
  518. // Read positions (broadphase updates concurrently so we can't write), read/write velocities
  519. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  520. // Can activate bodies only (we cache the amount of active bodies at the beginning of the step in mNumActiveBodiesAtStepStart so we cannot deactivate here)
  521. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  522. #endif
  523. float step_time = ioStep->mContext->mStepDeltaTime;
  524. uint32 batch_size = mPhysicsSettings.mStepListenersBatchSize;
  525. for (;;)
  526. {
  527. // Get the start of a new batch
  528. uint32 batch = ioStep->mStepListenerReadIdx.fetch_add(batch_size);
  529. if (batch >= mStepListeners.size())
  530. break;
  531. // Call the listeners
  532. for (uint32 i = batch, i_end = min((uint32)mStepListeners.size(), batch + batch_size); i < i_end; ++i)
  533. mStepListeners[i]->OnStep(step_time, *this);
  534. }
  535. }
  536. void PhysicsSystem::JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const
  537. {
  538. #ifdef JPH_ENABLE_ASSERTS
  539. // No body access
  540. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  541. #endif
  542. uint32 num_constraints = mConstraintManager.GetNumConstraints();
  543. uint32 num_active_constraints;
  544. Constraint **active_constraints = (Constraint **)JPH_STACK_ALLOC(cDetermineActiveConstraintsBatchSize * sizeof(Constraint *));
  545. for (;;)
  546. {
  547. // Atomically fetch a batch of constraints
  548. uint32 constraint_idx = ioStep->mConstraintReadIdx.fetch_add(cDetermineActiveConstraintsBatchSize);
  549. if (constraint_idx >= num_constraints)
  550. break;
  551. // Calculate the end of the batch
  552. uint32 constraint_idx_end = min(num_constraints, constraint_idx + cDetermineActiveConstraintsBatchSize);
  553. // Store the active constraints at the start of the step (bodies get activated during the step which in turn may activate constraints leading to an inconsistent shapshot)
  554. mConstraintManager.GetActiveConstraints(constraint_idx, constraint_idx_end, active_constraints, num_active_constraints);
  555. // Copy the block of active constraints to the global list of active constraints
  556. if (num_active_constraints > 0)
  557. {
  558. uint32 active_constraint_idx = ioStep->mNumActiveConstraints.fetch_add(num_active_constraints);
  559. memcpy(ioStep->mContext->mActiveConstraints + active_constraint_idx, active_constraints, num_active_constraints * sizeof(Constraint *));
  560. }
  561. }
  562. }
  563. void PhysicsSystem::JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  564. {
  565. #ifdef JPH_ENABLE_ASSERTS
  566. // We update velocities and need the rotation to do so
  567. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  568. #endif
  569. // Get list of active bodies that we had at the start of the physics update.
  570. // Any body that is activated as part of the simulation step does not receive gravity this frame.
  571. // Note that bodies may be activated during this job but not deactivated, this means that only elements
  572. // will be added to the array. Since the array is made to not reallocate, this is a safe operation.
  573. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe();
  574. uint32 num_active_bodies_at_step_start = ioStep->mNumActiveBodiesAtStepStart;
  575. // Fetch delta time once outside the loop
  576. float delta_time = ioContext->mSubStepDeltaTime;
  577. // Update velocities from forces
  578. for (;;)
  579. {
  580. // Atomically fetch a batch of bodies
  581. uint32 active_body_idx = ioStep->mApplyGravityReadIdx.fetch_add(cApplyGravityBatchSize);
  582. if (active_body_idx >= num_active_bodies_at_step_start)
  583. break;
  584. // Calculate the end of the batch
  585. uint32 active_body_idx_end = min(num_active_bodies_at_step_start, active_body_idx + cApplyGravityBatchSize);
  586. // Process the batch
  587. while (active_body_idx < active_body_idx_end)
  588. {
  589. Body &body = mBodyManager.GetBody(active_bodies[active_body_idx]);
  590. if (body.IsDynamic())
  591. body.GetMotionProperties()->ApplyForceTorqueAndDragInternal(body.GetRotation(), mGravity, delta_time);
  592. active_body_idx++;
  593. }
  594. }
  595. }
  596. void PhysicsSystem::JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const
  597. {
  598. #ifdef JPH_ENABLE_ASSERTS
  599. // We only read positions
  600. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  601. #endif
  602. ConstraintManager::sSetupVelocityConstraints(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, inDeltaTime);
  603. }
  604. void PhysicsSystem::JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  605. {
  606. #ifdef JPH_ENABLE_ASSERTS
  607. // We read constraints and positions
  608. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  609. // Can only activate bodies
  610. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  611. #endif
  612. // Prepare the island builder
  613. mIslandBuilder.PrepareNonContactConstraints(ioStep->mNumActiveConstraints, ioContext->mTempAllocator);
  614. // Build the islands
  615. ConstraintManager::sBuildIslands(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, mIslandBuilder, mBodyManager);
  616. }
  617. void PhysicsSystem::TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const
  618. {
  619. // Get how many jobs we can spawn and check if we can spawn more
  620. uint max_jobs = ioStep->mBodyPairQueues.size();
  621. if (CountBits(ioStep->mActiveFindCollisionJobs) >= max_jobs)
  622. return;
  623. // Count how many body pairs we have waiting
  624. uint32 num_body_pairs = 0;
  625. for (const PhysicsUpdateContext::BodyPairQueue &queue : ioStep->mBodyPairQueues)
  626. num_body_pairs += queue.mWriteIdx - queue.mReadIdx;
  627. // Count how many active bodies we have waiting
  628. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies() - ioStep->mActiveBodyReadIdx;
  629. // Calculate how many jobs we would like
  630. uint desired_num_jobs = min((num_body_pairs + cNarrowPhaseBatchSize - 1) / cNarrowPhaseBatchSize + (num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_jobs);
  631. for (;;)
  632. {
  633. // Get the bit mask of active jobs and see if we can spawn more
  634. PhysicsUpdateContext::JobMask current_active_jobs = ioStep->mActiveFindCollisionJobs;
  635. if (CountBits(current_active_jobs) >= desired_num_jobs)
  636. break;
  637. // Loop through all possible job indices
  638. for (uint job_index = 0; job_index < max_jobs; ++job_index)
  639. {
  640. // Test if it has been started
  641. PhysicsUpdateContext::JobMask job_mask = PhysicsUpdateContext::JobMask(1) << job_index;
  642. if ((current_active_jobs & job_mask) == 0)
  643. {
  644. // Try to claim the job index
  645. PhysicsUpdateContext::JobMask prev_value = ioStep->mActiveFindCollisionJobs.fetch_or(job_mask);
  646. if ((prev_value & job_mask) == 0)
  647. {
  648. // Add dependencies from the find collisions job to the next jobs
  649. ioStep->mUpdateBroadphaseFinalize.AddDependency();
  650. ioStep->mFinalizeIslands.AddDependency();
  651. // Start the job
  652. JobHandle job = ioStep->mContext->mJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [step = ioStep, job_index]()
  653. {
  654. step->mContext->mPhysicsSystem->JobFindCollisions(step, job_index);
  655. });
  656. // Add the job to the job barrier so the main updating thread can execute the job too
  657. ioStep->mContext->mBarrier->AddJob(job);
  658. // Spawn only 1 extra job at a time
  659. return;
  660. }
  661. }
  662. }
  663. }
  664. }
  665. static void sFinalizeContactAllocator(PhysicsUpdateContext::Step &ioStep, const ContactConstraintManager::ContactAllocator &inAllocator)
  666. {
  667. // Atomically accumulate the number of found manifolds and body pairs
  668. ioStep.mNumBodyPairs.fetch_add(inAllocator.mNumBodyPairs, memory_order_relaxed);
  669. ioStep.mNumManifolds.fetch_add(inAllocator.mNumManifolds, memory_order_relaxed);
  670. // Combine update errors
  671. ioStep.mContext->mErrors.fetch_or((uint32)inAllocator.mErrors, memory_order_relaxed);
  672. }
  673. void PhysicsSystem::JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex)
  674. {
  675. #ifdef JPH_ENABLE_ASSERTS
  676. // We read positions and read velocities (for elastic collisions)
  677. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  678. // Can only activate bodies
  679. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  680. #endif
  681. // Allocation context for allocating new contact points
  682. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  683. // Determine initial queue to read pairs from if no broadphase work can be done
  684. // (always start looking at results from the next job)
  685. int read_queue_idx = (inJobIndex + 1) % ioStep->mBodyPairQueues.size();
  686. for (;;)
  687. {
  688. // Check if there are active bodies to be processed
  689. uint32 active_bodies_read_idx = ioStep->mActiveBodyReadIdx;
  690. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  691. if (active_bodies_read_idx < num_active_bodies)
  692. {
  693. // Take a batch of active bodies
  694. uint32 active_bodies_read_idx_end = min(num_active_bodies, active_bodies_read_idx + cActiveBodiesBatchSize);
  695. if (ioStep->mActiveBodyReadIdx.compare_exchange_strong(active_bodies_read_idx, active_bodies_read_idx_end))
  696. {
  697. // Callback when a new body pair is found
  698. class MyBodyPairCallback : public BodyPairCollector
  699. {
  700. public:
  701. // Constructor
  702. MyBodyPairCallback(PhysicsUpdateContext::Step *inStep, ContactAllocator &ioContactAllocator, int inJobIndex) :
  703. mStep(inStep),
  704. mContactAllocator(ioContactAllocator),
  705. mJobIndex(inJobIndex)
  706. {
  707. }
  708. // Callback function when a body pair is found
  709. virtual void AddHit(const BodyPair &inPair) override
  710. {
  711. // Check if we have space in our write queue
  712. PhysicsUpdateContext::BodyPairQueue &queue = mStep->mBodyPairQueues[mJobIndex];
  713. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  714. if (body_pairs_in_queue >= mStep->mMaxBodyPairsPerQueue)
  715. {
  716. // Buffer full, process the pair now
  717. mStep->mContext->mPhysicsSystem->ProcessBodyPair(mContactAllocator, inPair);
  718. }
  719. else
  720. {
  721. // Store the pair in our own queue
  722. mStep->mContext->mBodyPairs[mJobIndex * mStep->mMaxBodyPairsPerQueue + queue.mWriteIdx % mStep->mMaxBodyPairsPerQueue] = inPair;
  723. ++queue.mWriteIdx;
  724. }
  725. }
  726. private:
  727. PhysicsUpdateContext::Step * mStep;
  728. ContactAllocator & mContactAllocator;
  729. int mJobIndex;
  730. };
  731. MyBodyPairCallback add_pair(ioStep, contact_allocator, inJobIndex);
  732. // Copy active bodies to temporary array, broadphase will reorder them
  733. uint32 batch_size = active_bodies_read_idx_end - active_bodies_read_idx;
  734. BodyID *active_bodies = (BodyID *)JPH_STACK_ALLOC(batch_size * sizeof(BodyID));
  735. memcpy(active_bodies, mBodyManager.GetActiveBodiesUnsafe() + active_bodies_read_idx, batch_size * sizeof(BodyID));
  736. // Find pairs in the broadphase
  737. mBroadPhase->FindCollidingPairs(active_bodies, batch_size, mPhysicsSettings.mSpeculativeContactDistance, *mObjectVsBroadPhaseLayerFilter, *mObjectLayerPairFilter, add_pair);
  738. // Check if we have enough pairs in the buffer to start a new job
  739. const PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[inJobIndex];
  740. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  741. if (body_pairs_in_queue >= cNarrowPhaseBatchSize)
  742. TrySpawnJobFindCollisions(ioStep);
  743. }
  744. }
  745. else
  746. {
  747. // Lockless loop to get the next body pair from the pairs buffer
  748. const PhysicsUpdateContext *context = ioStep->mContext;
  749. int first_read_queue_idx = read_queue_idx;
  750. for (;;)
  751. {
  752. PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[read_queue_idx];
  753. // Get the next pair to process
  754. uint32 pair_idx = queue.mReadIdx;
  755. // If the pair hasn't been written yet
  756. if (pair_idx >= queue.mWriteIdx)
  757. {
  758. // Go to the next queue
  759. read_queue_idx = (read_queue_idx + 1) % ioStep->mBodyPairQueues.size();
  760. // If we're back at the first queue, we've looked at all of them and found nothing
  761. if (read_queue_idx == first_read_queue_idx)
  762. {
  763. // Collect information from the contact allocator and accumulate it in the step.
  764. sFinalizeContactAllocator(*ioStep, contact_allocator);
  765. // Mark this job as inactive
  766. ioStep->mActiveFindCollisionJobs.fetch_and(~PhysicsUpdateContext::JobMask(1 << inJobIndex));
  767. // Trigger the next jobs
  768. ioStep->mUpdateBroadphaseFinalize.RemoveDependency();
  769. ioStep->mFinalizeIslands.RemoveDependency();
  770. return;
  771. }
  772. // Try again reading from the next queue
  773. continue;
  774. }
  775. // Copy the body pair out of the buffer
  776. const BodyPair bp = context->mBodyPairs[read_queue_idx * ioStep->mMaxBodyPairsPerQueue + pair_idx % ioStep->mMaxBodyPairsPerQueue];
  777. // Mark this pair as taken
  778. if (queue.mReadIdx.compare_exchange_strong(pair_idx, pair_idx + 1))
  779. {
  780. // Process the actual body pair
  781. ProcessBodyPair(contact_allocator, bp);
  782. break;
  783. }
  784. }
  785. }
  786. }
  787. }
  788. void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair)
  789. {
  790. JPH_PROFILE_FUNCTION();
  791. // Fetch body pair
  792. Body *body1 = &mBodyManager.GetBody(inBodyPair.mBodyA);
  793. Body *body2 = &mBodyManager.GetBody(inBodyPair.mBodyB);
  794. JPH_ASSERT(body1->IsActive());
  795. JPH_DET_LOG("ProcessBodyPair: id1: " << inBodyPair.mBodyA << " id2: " << inBodyPair.mBodyB << " p1: " << body1->GetCenterOfMassPosition() << " p2: " << body2->GetCenterOfMassPosition() << " r1: " << body1->GetRotation() << " r2: " << body2->GetRotation());
  796. // Ensure that body1 is dynamic, this ensures that we do the collision detection in the space of a moving body, which avoids accuracy problems when testing a very large static object against a small dynamic object
  797. // Ensure that body1 id < body2 id for dynamic vs dynamic
  798. // Keep body order unchanged when colliding with a sensor
  799. if ((!body1->IsDynamic() || (body2->IsDynamic() && inBodyPair.mBodyB < inBodyPair.mBodyA))
  800. && !body2->IsSensor())
  801. swap(body1, body2);
  802. JPH_ASSERT(body1->IsDynamic() || (body1->IsKinematic() && body2->IsSensor()));
  803. // Check if the contact points from the previous frame are reusable and if so copy them
  804. bool pair_handled = false, constraint_created = false;
  805. if (mPhysicsSettings.mUseBodyPairContactCache && !(body1->IsCollisionCacheInvalid() || body2->IsCollisionCacheInvalid()))
  806. mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled, constraint_created);
  807. // If the cache hasn't handled this body pair do actual collision detection
  808. if (!pair_handled)
  809. {
  810. // Create entry in the cache for this body pair
  811. // Needs to happen irrespective if we found a collision or not (we want to remember that no collision was found too)
  812. ContactConstraintManager::BodyPairHandle body_pair_handle = mContactManager.AddBodyPair(ioContactAllocator, *body1, *body2);
  813. if (body_pair_handle == nullptr)
  814. return; // Out of cache space
  815. // Create the query settings
  816. CollideShapeSettings settings;
  817. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  818. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  819. settings.mMaxSeparationDistance = mPhysicsSettings.mSpeculativeContactDistance;
  820. settings.mActiveEdgeMovementDirection = body1->GetLinearVelocity() - body2->GetLinearVelocity();
  821. // Get transforms relative to body1
  822. RVec3 offset = body1->GetCenterOfMassPosition();
  823. Mat44 transform1 = Mat44::sRotation(body1->GetRotation());
  824. Mat44 transform2 = body2->GetCenterOfMassTransform().PostTranslated(-offset).ToMat44();
  825. if (mPhysicsSettings.mUseManifoldReduction // Check global flag
  826. && body1->GetUseManifoldReductionWithBody(*body2)) // Check body flag
  827. {
  828. // Version WITH contact manifold reduction
  829. class MyManifold : public ContactManifold
  830. {
  831. public:
  832. Vec3 mFirstWorldSpaceNormal;
  833. };
  834. // A temporary structure that allows us to keep track of the all manifolds between this body pair
  835. using Manifolds = StaticArray<MyManifold, 32>;
  836. // Create collector
  837. class ReductionCollideShapeCollector : public CollideShapeCollector
  838. {
  839. public:
  840. ReductionCollideShapeCollector(PhysicsSystem *inSystem, const Body *inBody1, const Body *inBody2) :
  841. mSystem(inSystem),
  842. mBody1(inBody1),
  843. mBody2(inBody2)
  844. {
  845. }
  846. virtual void AddHit(const CollideShapeResult &inResult) override
  847. {
  848. // One of the following should be true:
  849. // - Body 1 is dynamic and body 2 may be dynamic, static or kinematic
  850. // - Body 1 is kinematic in which case body 2 should be a sensor
  851. JPH_ASSERT(mBody1->IsDynamic() || (mBody1->IsKinematic() && mBody2->IsSensor()));
  852. JPH_ASSERT(!ShouldEarlyOut());
  853. // Test if we want to accept this hit
  854. if (mValidateBodyPair)
  855. {
  856. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))
  857. {
  858. case ValidateResult::AcceptContact:
  859. // We're just accepting this one, nothing to do
  860. break;
  861. case ValidateResult::AcceptAllContactsForThisBodyPair:
  862. // Accept and stop calling the validate callback
  863. mValidateBodyPair = false;
  864. break;
  865. case ValidateResult::RejectContact:
  866. // Skip this contact
  867. return;
  868. case ValidateResult::RejectAllContactsForThisBodyPair:
  869. // Skip this and early out
  870. ForceEarlyOut();
  871. return;
  872. }
  873. }
  874. // Calculate normal
  875. Vec3 world_space_normal = inResult.mPenetrationAxis.Normalized();
  876. // Check if we can add it to an existing manifold
  877. Manifolds::iterator manifold;
  878. float contact_normal_cos_max_delta_rot = mSystem->mPhysicsSettings.mContactNormalCosMaxDeltaRotation;
  879. for (manifold = mManifolds.begin(); manifold != mManifolds.end(); ++manifold)
  880. if (world_space_normal.Dot(manifold->mFirstWorldSpaceNormal) >= contact_normal_cos_max_delta_rot)
  881. {
  882. // Update average normal
  883. manifold->mWorldSpaceNormal += world_space_normal;
  884. manifold->mPenetrationDepth = max(manifold->mPenetrationDepth, inResult.mPenetrationDepth);
  885. break;
  886. }
  887. if (manifold == mManifolds.end())
  888. {
  889. // Check if array is full
  890. if (mManifolds.size() == mManifolds.capacity())
  891. {
  892. // Full, find manifold with least amount of penetration
  893. manifold = mManifolds.begin();
  894. for (Manifolds::iterator m = mManifolds.begin() + 1; m < mManifolds.end(); ++m)
  895. if (m->mPenetrationDepth < manifold->mPenetrationDepth)
  896. manifold = m;
  897. // If this contacts penetration is smaller than the smallest manifold, we skip this contact
  898. if (inResult.mPenetrationDepth < manifold->mPenetrationDepth)
  899. return;
  900. // Replace the manifold
  901. *manifold = { { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal };
  902. }
  903. else
  904. {
  905. // Not full, create new manifold
  906. mManifolds.push_back({ { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal });
  907. manifold = mManifolds.end() - 1;
  908. }
  909. }
  910. // Determine contact points
  911. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  912. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, Square(settings.mSpeculativeContactDistance) + settings.mManifoldToleranceSq, inResult.mShape1Face, inResult.mShape2Face, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, mBody1->GetCenterOfMassPosition()));
  913. // Prune if we have more than 32 points (this means we could run out of space in the next iteration)
  914. if (manifold->mRelativeContactPointsOn1.size() > 32)
  915. PruneContactPoints(manifold->mFirstWorldSpaceNormal, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold->mBaseOffset));
  916. }
  917. PhysicsSystem * mSystem;
  918. const Body * mBody1;
  919. const Body * mBody2;
  920. bool mValidateBodyPair = true;
  921. Manifolds mManifolds;
  922. };
  923. ReductionCollideShapeCollector collector(this, body1, body2);
  924. // Perform collision detection between the two shapes
  925. SubShapeIDCreator part1, part2;
  926. CollisionDispatch::sCollideShapeVsShape(body1->GetShape(), body2->GetShape(), Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), transform1, transform2, part1, part2, settings, collector);
  927. // Add the contacts
  928. for (ContactManifold &manifold : collector.mManifolds)
  929. {
  930. // Normalize the normal (is a sum of all normals from merged manifolds)
  931. manifold.mWorldSpaceNormal = manifold.mWorldSpaceNormal.Normalized();
  932. // If we still have too many points, prune them now
  933. if (manifold.mRelativeContactPointsOn1.size() > 4)
  934. PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  935. // Actually add the contact points to the manager
  936. constraint_created |= mContactManager.AddContactConstraint(ioContactAllocator, body_pair_handle, *body1, *body2, manifold);
  937. }
  938. }
  939. else
  940. {
  941. // Version WITHOUT contact manifold reduction
  942. // Create collector
  943. class NonReductionCollideShapeCollector : public CollideShapeCollector
  944. {
  945. public:
  946. NonReductionCollideShapeCollector(PhysicsSystem *inSystem, ContactAllocator &ioContactAllocator, Body *inBody1, Body *inBody2, const ContactConstraintManager::BodyPairHandle &inPairHandle) :
  947. mSystem(inSystem),
  948. mContactAllocator(ioContactAllocator),
  949. mBody1(inBody1),
  950. mBody2(inBody2),
  951. mBodyPairHandle(inPairHandle)
  952. {
  953. }
  954. virtual void AddHit(const CollideShapeResult &inResult) override
  955. {
  956. // One of the following should be true:
  957. // - Body 1 is dynamic and body 2 may be dynamic, static or kinematic
  958. // - Body 1 is kinematic in which case body 2 should be a sensor
  959. JPH_ASSERT(mBody1->IsDynamic() || (mBody1->IsKinematic() && mBody2->IsSensor()));
  960. JPH_ASSERT(!ShouldEarlyOut());
  961. // Test if we want to accept this hit
  962. if (mValidateBodyPair)
  963. {
  964. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))
  965. {
  966. case ValidateResult::AcceptContact:
  967. // We're just accepting this one, nothing to do
  968. break;
  969. case ValidateResult::AcceptAllContactsForThisBodyPair:
  970. // Accept and stop calling the validate callback
  971. mValidateBodyPair = false;
  972. break;
  973. case ValidateResult::RejectContact:
  974. // Skip this contact
  975. return;
  976. case ValidateResult::RejectAllContactsForThisBodyPair:
  977. // Skip this and early out
  978. ForceEarlyOut();
  979. return;
  980. }
  981. }
  982. // Determine contact points
  983. ContactManifold manifold;
  984. manifold.mBaseOffset = mBody1->GetCenterOfMassPosition();
  985. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  986. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, Square(settings.mSpeculativeContactDistance) + settings.mManifoldToleranceSq, inResult.mShape1Face, inResult.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  987. // Calculate normal
  988. manifold.mWorldSpaceNormal = inResult.mPenetrationAxis.Normalized();
  989. // Store penetration depth
  990. manifold.mPenetrationDepth = inResult.mPenetrationDepth;
  991. // Prune if we have more than 4 points
  992. if (manifold.mRelativeContactPointsOn1.size() > 4)
  993. PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  994. // Set other properties
  995. manifold.mSubShapeID1 = inResult.mSubShapeID1;
  996. manifold.mSubShapeID2 = inResult.mSubShapeID2;
  997. // Actually add the contact points to the manager
  998. mConstraintCreated |= mSystem->mContactManager.AddContactConstraint(mContactAllocator, mBodyPairHandle, *mBody1, *mBody2, manifold);
  999. }
  1000. PhysicsSystem * mSystem;
  1001. ContactAllocator & mContactAllocator;
  1002. Body * mBody1;
  1003. Body * mBody2;
  1004. ContactConstraintManager::BodyPairHandle mBodyPairHandle;
  1005. bool mValidateBodyPair = true;
  1006. bool mConstraintCreated = false;
  1007. };
  1008. NonReductionCollideShapeCollector collector(this, ioContactAllocator, body1, body2, body_pair_handle);
  1009. // Perform collision detection between the two shapes
  1010. SubShapeIDCreator part1, part2;
  1011. CollisionDispatch::sCollideShapeVsShape(body1->GetShape(), body2->GetShape(), Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), transform1, transform2, part1, part2, settings, collector);
  1012. constraint_created = collector.mConstraintCreated;
  1013. }
  1014. }
  1015. // If a contact constraint was created, we need to do some extra work
  1016. if (constraint_created)
  1017. {
  1018. // Wake up sleeping bodies
  1019. BodyID body_ids[2];
  1020. int num_bodies = 0;
  1021. if (body1->IsDynamic() && !body1->IsActive())
  1022. body_ids[num_bodies++] = body1->GetID();
  1023. if (body2->IsDynamic() && !body2->IsActive())
  1024. body_ids[num_bodies++] = body2->GetID();
  1025. if (num_bodies > 0)
  1026. mBodyManager.ActivateBodies(body_ids, num_bodies);
  1027. // Link the two bodies
  1028. mIslandBuilder.LinkBodies(body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  1029. }
  1030. }
  1031. void PhysicsSystem::JobFinalizeIslands(PhysicsUpdateContext *ioContext)
  1032. {
  1033. #ifdef JPH_ENABLE_ASSERTS
  1034. // We only touch island data
  1035. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1036. #endif
  1037. // Finish collecting the islands, at this point the active body list doesn't change so it's safe to access
  1038. mIslandBuilder.Finalize(mBodyManager.GetActiveBodiesUnsafe(), mBodyManager.GetNumActiveBodies(), mContactManager.GetNumConstraints(), ioContext->mTempAllocator);
  1039. // Prepare the large island splitter
  1040. if (ioContext->mUseLargeIslandSplitter)
  1041. mLargeIslandSplitter.Prepare(mIslandBuilder, mBodyManager.GetNumActiveBodies(), ioContext->mTempAllocator);
  1042. }
  1043. void PhysicsSystem::JobBodySetIslandIndex()
  1044. {
  1045. #ifdef JPH_ENABLE_ASSERTS
  1046. // We only touch island data
  1047. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1048. #endif
  1049. // Loop through the result and tag all bodies with an island index
  1050. for (uint32 island_idx = 0, n = mIslandBuilder.GetNumIslands(); island_idx < n; ++island_idx)
  1051. {
  1052. BodyID *body_start, *body_end;
  1053. mIslandBuilder.GetBodiesInIsland(island_idx, body_start, body_end);
  1054. for (const BodyID *body = body_start; body < body_end; ++body)
  1055. mBodyManager.GetBody(*body).GetMotionProperties()->SetIslandIndexInternal(island_idx);
  1056. }
  1057. }
  1058. void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1059. {
  1060. #ifdef JPH_ENABLE_ASSERTS
  1061. // We update velocities and need to read positions to do so
  1062. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  1063. #endif
  1064. float delta_time = ioContext->mSubStepDeltaTime;
  1065. Constraint **active_constraints = ioContext->mActiveConstraints;
  1066. bool first_sub_step = ioSubStep->mIsFirst;
  1067. bool last_sub_step = ioSubStep->mIsLast;
  1068. // Only the first sub step of the first step needs to correct for the delta time difference in the previous update
  1069. float warm_start_impulse_ratio = ioSubStep->mIsFirstOfAll? ioContext->mWarmStartImpulseRatio : 1.0f;
  1070. bool check_islands = true, check_split_islands = ioContext->mUseLargeIslandSplitter;
  1071. do
  1072. {
  1073. // First try to get work from large islands
  1074. if (check_split_islands)
  1075. {
  1076. bool first_iteration;
  1077. uint split_island_index;
  1078. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1079. switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))
  1080. {
  1081. case LargeIslandSplitter::EStatus::BatchRetrieved:
  1082. {
  1083. if (first_iteration)
  1084. {
  1085. // Iteration 0 is used to warm start the batch (we added 1 to the number of iterations in LargeIslandSplitter::SplitIsland)
  1086. ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio);
  1087. mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio);
  1088. }
  1089. else
  1090. {
  1091. // Solve velocity constraints
  1092. ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1093. mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);
  1094. }
  1095. // Mark the batch as processed
  1096. bool last_iteration, final_batch;
  1097. mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);
  1098. // Save back the lambdas in the contact cache for the warm start of the next physics update
  1099. if (last_sub_step && last_iteration)
  1100. mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);
  1101. // We processed work, loop again
  1102. continue;
  1103. }
  1104. case LargeIslandSplitter::EStatus::WaitingForBatch:
  1105. break;
  1106. case LargeIslandSplitter::EStatus::AllBatchesDone:
  1107. check_split_islands = false;
  1108. break;
  1109. }
  1110. }
  1111. // If that didn't succeed try to process an island
  1112. if (check_islands)
  1113. {
  1114. // Next island
  1115. uint32 island_idx = ioSubStep->mSolveVelocityConstraintsNextIsland++;
  1116. if (island_idx >= mIslandBuilder.GetNumIslands())
  1117. {
  1118. // We processed all islands, stop checking islands
  1119. check_islands = false;
  1120. continue;
  1121. }
  1122. JPH_PROFILE("Island");
  1123. // Get iterators for this island
  1124. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1125. bool has_constraints = mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  1126. bool has_contacts = mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  1127. if (first_sub_step)
  1128. {
  1129. // If we don't have any contacts or constraints, we know that none of the following islands have any contacts or constraints
  1130. // (because they're sorted by most constraints first). This means we're done.
  1131. if (!has_contacts && !has_constraints)
  1132. {
  1133. #ifdef JPH_ENABLE_ASSERTS
  1134. // Validate our assumption that the next islands don't have any constraints or contacts
  1135. for (; island_idx < mIslandBuilder.GetNumIslands(); ++island_idx)
  1136. {
  1137. JPH_ASSERT(!mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end));
  1138. JPH_ASSERT(!mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end));
  1139. }
  1140. #endif // JPH_ENABLE_ASSERTS
  1141. check_islands = false;
  1142. continue;
  1143. }
  1144. // Sorting is costly but needed for a deterministic simulation, allow the user to turn this off
  1145. if (mPhysicsSettings.mDeterministicSimulation)
  1146. {
  1147. // Sort constraints to give a deterministic simulation
  1148. ConstraintManager::sSortConstraints(active_constraints, constraints_begin, constraints_end);
  1149. // Sort contacts to give a deterministic simulation
  1150. mContactManager.SortContacts(contacts_begin, contacts_end);
  1151. }
  1152. }
  1153. else
  1154. {
  1155. {
  1156. JPH_PROFILE("Apply Gravity");
  1157. // Get bodies in this island
  1158. BodyID *bodies_begin, *bodies_end;
  1159. mIslandBuilder.GetBodiesInIsland(island_idx, bodies_begin, bodies_end);
  1160. // Apply gravity. In the first step this is done in a separate job.
  1161. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1162. {
  1163. Body &body = mBodyManager.GetBody(*body_id);
  1164. if (body.IsDynamic())
  1165. body.GetMotionProperties()->ApplyForceTorqueAndDragInternal(body.GetRotation(), mGravity, delta_time);
  1166. }
  1167. }
  1168. // If we don't have any contacts or constraints, we don't need to run the solver, but we do need to process
  1169. // the next island in order to apply gravity
  1170. if (!has_contacts && !has_constraints)
  1171. continue;
  1172. // Prepare velocity constraints. In the first step this is done when adding the contact constraints.
  1173. ConstraintManager::sSetupVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1174. mContactManager.SetupVelocityConstraints(contacts_begin, contacts_end, delta_time);
  1175. }
  1176. // Split up large islands
  1177. int num_velocity_steps = mPhysicsSettings.mNumVelocitySteps;
  1178. if (ioContext->mUseLargeIslandSplitter
  1179. && mLargeIslandSplitter.SplitIsland(island_idx, mIslandBuilder, mBodyManager, mContactManager, active_constraints, num_velocity_steps, mPhysicsSettings.mNumPositionSteps))
  1180. continue; // Loop again to try to fetch the newly split island
  1181. // We didn't create a split, just run the solver now for this entire island. Begin by warm starting.
  1182. ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio, num_velocity_steps);
  1183. mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio);
  1184. // Solve velocity constraints
  1185. for (int velocity_step = 0; velocity_step < num_velocity_steps; ++velocity_step)
  1186. {
  1187. bool applied_impulse = ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1188. applied_impulse |= mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);
  1189. if (!applied_impulse)
  1190. break;
  1191. }
  1192. // Save back the lambdas in the contact cache for the warm start of the next physics update
  1193. if (last_sub_step)
  1194. mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);
  1195. // We processed work, loop again
  1196. continue;
  1197. }
  1198. // If we didn't find any work, give up a time slice
  1199. std::this_thread::yield();
  1200. }
  1201. while (check_islands || check_split_islands);
  1202. }
  1203. void PhysicsSystem::JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1204. {
  1205. // Reserve enough space for all bodies that may need a cast
  1206. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1207. JPH_ASSERT(ioSubStep->mCCDBodies == nullptr);
  1208. ioSubStep->mCCDBodiesCapacity = mBodyManager.GetNumActiveCCDBodies();
  1209. ioSubStep->mCCDBodies = (CCDBody *)temp_allocator->Allocate(ioSubStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1210. // Initialize the mapping table between active body and CCD body
  1211. JPH_ASSERT(ioSubStep->mActiveBodyToCCDBody == nullptr);
  1212. ioSubStep->mNumActiveBodyToCCDBody = mBodyManager.GetNumActiveBodies();
  1213. ioSubStep->mActiveBodyToCCDBody = (int *)temp_allocator->Allocate(ioSubStep->mNumActiveBodyToCCDBody * sizeof(int));
  1214. // Prepare the split island builder for solving the position constraints
  1215. mLargeIslandSplitter.PrepareForSolvePositions();
  1216. }
  1217. void PhysicsSystem::JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1218. {
  1219. #ifdef JPH_ENABLE_ASSERTS
  1220. // We update positions and need velocity to do so, we also clamp velocities so need to write to them
  1221. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1222. #endif
  1223. float delta_time = ioContext->mSubStepDeltaTime;
  1224. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe();
  1225. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  1226. uint32 num_active_bodies_after_find_collisions = ioSubStep->mStep->mActiveBodyReadIdx;
  1227. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1228. static constexpr int cBodiesBatch = 64;
  1229. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1230. int num_bodies_to_update_bounds = 0;
  1231. for (;;)
  1232. {
  1233. // Atomically fetch a batch of bodies
  1234. uint32 active_body_idx = ioSubStep->mIntegrateVelocityReadIdx.fetch_add(cIntegrateVelocityBatchSize);
  1235. if (active_body_idx >= num_active_bodies)
  1236. break;
  1237. // Calculate the end of the batch
  1238. uint32 active_body_idx_end = min(num_active_bodies, active_body_idx + cIntegrateVelocityBatchSize);
  1239. // Process the batch
  1240. while (active_body_idx < active_body_idx_end)
  1241. {
  1242. // Update the positions using an Symplectic Euler step (which integrates using the updated velocity v1' rather
  1243. // than the original velocity v1):
  1244. // x1' = x1 + h * v1'
  1245. // At this point the active bodies list does not change, so it is safe to access the array.
  1246. BodyID body_id = active_bodies[active_body_idx];
  1247. Body &body = mBodyManager.GetBody(body_id);
  1248. MotionProperties *mp = body.GetMotionProperties();
  1249. JPH_DET_LOG("JobIntegrateVelocity: id: " << body_id << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());
  1250. // Clamp velocities (not for kinematic bodies)
  1251. if (body.IsDynamic())
  1252. {
  1253. mp->ClampLinearVelocity();
  1254. mp->ClampAngularVelocity();
  1255. }
  1256. // Update the rotation of the body according to the angular velocity
  1257. // For motion type discrete we need to do this anyway, for motion type linear cast we have multiple choices
  1258. // 1. Rotate the body first and then sweep
  1259. // 2. First sweep and then rotate the body at the end
  1260. // 3. Pick some inbetween rotation (e.g. half way), then sweep and finally rotate the remainder
  1261. // (1) has some clear advantages as when a long thin body hits a surface away from the center of mass, this will result in a large angular velocity and a limited reduction in linear velocity.
  1262. // When simulation the rotation first before doing the translation, the body will be able to rotate away from the contact point allowing the center of mass to approach the surface. When using
  1263. // approach (2) in this case what will happen is that we will immediately detect the same collision again (the body has not rotated and the body was already colliding at the end of the previous
  1264. // time step) resulting in a lot of stolen time and the body appearing to be frozen in an unnatural pose (like it is glued at an angle to the surface). (2) obviously has some negative side effects
  1265. // too as simulating the rotation first may cause it to tunnel through a small object that the linear cast might have otherwise dectected. In any case a linear cast is not good for detecting
  1266. // tunneling due to angular rotation, so we don't care about that too much (you'd need a full cast to take angular effects into account).
  1267. body.AddRotationStep(body.GetAngularVelocity() * delta_time);
  1268. // Get delta position
  1269. Vec3 delta_pos = body.GetLinearVelocity() * delta_time;
  1270. // If the position should be updated (or if it is delayed because of CCD)
  1271. bool update_position = true;
  1272. switch (mp->GetMotionQuality())
  1273. {
  1274. case EMotionQuality::Discrete:
  1275. // No additional collision checking to be done
  1276. break;
  1277. case EMotionQuality::LinearCast:
  1278. if (body.IsDynamic() // Kinematic bodies cannot be stopped
  1279. && !body.IsSensor()) // We don't support CCD sensors
  1280. {
  1281. // Determine inner radius (the smallest sphere that fits into the shape)
  1282. float inner_radius = body.GetShape()->GetInnerRadius();
  1283. JPH_ASSERT(inner_radius > 0.0f, "The shape has no inner radius, this makes the shape unsuitable for the linear cast motion quality as we cannot move it without risking tunneling.");
  1284. // Measure translation in this step and check if it above the treshold to perform a linear cast
  1285. float linear_cast_threshold_sq = Square(mPhysicsSettings.mLinearCastThreshold * inner_radius);
  1286. if (delta_pos.LengthSq() > linear_cast_threshold_sq)
  1287. {
  1288. // This body needs a cast
  1289. uint32 ccd_body_idx = ioSubStep->mNumCCDBodies++;
  1290. ioSubStep->mActiveBodyToCCDBody[active_body_idx] = ccd_body_idx;
  1291. new (&ioSubStep->mCCDBodies[ccd_body_idx]) CCDBody(body_id, delta_pos, linear_cast_threshold_sq, min(mPhysicsSettings.mPenetrationSlop, mPhysicsSettings.mLinearCastMaxPenetration * inner_radius));
  1292. update_position = false;
  1293. }
  1294. }
  1295. break;
  1296. }
  1297. if (update_position)
  1298. {
  1299. // Move the body now
  1300. body.AddPositionStep(delta_pos);
  1301. // If the body was activated due to an earlier CCD step it will have an index in the active
  1302. // body list that it higher than the highest one we processed during FindCollisions
  1303. // which means it hasn't been assigned an island and will not be updated by an island
  1304. // this means that we need to update its bounds manually
  1305. if (mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1306. {
  1307. body.CalculateWorldSpaceBoundsInternal();
  1308. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body.GetID();
  1309. if (num_bodies_to_update_bounds == cBodiesBatch)
  1310. {
  1311. // Buffer full, flush now
  1312. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds);
  1313. num_bodies_to_update_bounds = 0;
  1314. }
  1315. }
  1316. // We did not create a CCD body
  1317. ioSubStep->mActiveBodyToCCDBody[active_body_idx] = -1;
  1318. }
  1319. active_body_idx++;
  1320. }
  1321. }
  1322. // Notify change bounds on requested bodies
  1323. if (num_bodies_to_update_bounds > 0)
  1324. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1325. }
  1326. void PhysicsSystem::JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const
  1327. {
  1328. // Validate that our reservations were correct
  1329. JPH_ASSERT(ioSubStep->mNumCCDBodies <= mBodyManager.GetNumActiveCCDBodies());
  1330. if (ioSubStep->mNumCCDBodies == 0)
  1331. {
  1332. // No continous collision detection jobs -> kick the next job ourselves
  1333. if (ioSubStep->mIsLast)
  1334. ioSubStep->mStep->mContactRemovedCallbacks.RemoveDependency();
  1335. }
  1336. else
  1337. {
  1338. // Run the continous collision detection jobs
  1339. int num_continuous_collision_jobs = min(int(ioSubStep->mNumCCDBodies + cNumCCDBodiesPerJob - 1) / cNumCCDBodiesPerJob, ioContext->GetMaxConcurrency());
  1340. ioSubStep->mResolveCCDContacts.AddDependency(num_continuous_collision_jobs);
  1341. if (ioSubStep->mIsLast)
  1342. ioSubStep->mStep->mContactRemovedCallbacks.AddDependency(num_continuous_collision_jobs - 1); // Already had 1 dependency
  1343. for (int i = 0; i < num_continuous_collision_jobs; ++i)
  1344. {
  1345. JobHandle job = ioContext->mJobSystem->CreateJob("FindCCDContacts", cColorFindCCDContacts, [ioContext, ioSubStep]()
  1346. {
  1347. ioContext->mPhysicsSystem->JobFindCCDContacts(ioContext, ioSubStep);
  1348. ioSubStep->mResolveCCDContacts.RemoveDependency();
  1349. if (ioSubStep->mIsLast)
  1350. ioSubStep->mStep->mContactRemovedCallbacks.RemoveDependency();
  1351. });
  1352. ioContext->mBarrier->AddJob(job);
  1353. }
  1354. }
  1355. }
  1356. // Helper function to calculate the motion of a body during this CCD step
  1357. inline static Vec3 sCalculateBodyMotion(const Body &inBody, float inDeltaTime)
  1358. {
  1359. // If the body is linear casting, the body has not yet moved so we need to calculate its motion
  1360. if (inBody.IsDynamic() && inBody.GetMotionProperties()->GetMotionQuality() == EMotionQuality::LinearCast)
  1361. return inDeltaTime * inBody.GetLinearVelocity();
  1362. // Body has already moved, so we don't need to correct for anything
  1363. return Vec3::sZero();
  1364. }
  1365. // Helper function that finds the CCD body corresponding to a body (if it exists)
  1366. inline static PhysicsUpdateContext::SubStep::CCDBody *sGetCCDBody(const Body &inBody, PhysicsUpdateContext::SubStep *inSubStep)
  1367. {
  1368. // If the body has no motion properties it cannot have a CCD body
  1369. const MotionProperties *motion_properties = inBody.GetMotionPropertiesUnchecked();
  1370. if (motion_properties == nullptr)
  1371. return nullptr;
  1372. // If it is not active it cannot have a CCD body
  1373. uint32 active_index = motion_properties->GetIndexInActiveBodiesInternal();
  1374. if (active_index == Body::cInactiveIndex)
  1375. return nullptr;
  1376. // Check if the active body has a corresponding CCD body
  1377. JPH_ASSERT(active_index < inSubStep->mNumActiveBodyToCCDBody); // Ensure that the body has a mapping to CCD body
  1378. int ccd_index = inSubStep->mActiveBodyToCCDBody[active_index];
  1379. if (ccd_index < 0)
  1380. return nullptr;
  1381. PhysicsUpdateContext::SubStep::CCDBody *ccd_body = &inSubStep->mCCDBodies[ccd_index];
  1382. JPH_ASSERT(ccd_body->mBodyID1 == inBody.GetID(), "We found the wrong CCD body!");
  1383. return ccd_body;
  1384. }
  1385. void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1386. {
  1387. #ifdef JPH_ENABLE_ASSERTS
  1388. // We only read positions, but the validate callback may read body positions and velocities
  1389. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  1390. #endif
  1391. // Allocation context for allocating new contact points
  1392. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  1393. // Settings
  1394. ShapeCastSettings settings;
  1395. settings.mUseShrunkenShapeAndConvexRadius = true;
  1396. settings.mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;
  1397. settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;
  1398. settings.mReturnDeepestPoint = true;
  1399. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  1400. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  1401. for (;;)
  1402. {
  1403. // Fetch the next body to cast
  1404. uint32 idx = ioSubStep->mNextCCDBody++;
  1405. if (idx >= ioSubStep->mNumCCDBodies)
  1406. break;
  1407. CCDBody &ccd_body = ioSubStep->mCCDBodies[idx];
  1408. const Body &body = mBodyManager.GetBody(ccd_body.mBodyID1);
  1409. // Filter out layers
  1410. DefaultBroadPhaseLayerFilter broadphase_layer_filter = GetDefaultBroadPhaseLayerFilter(body.GetObjectLayer());
  1411. DefaultObjectLayerFilter object_layer_filter = GetDefaultLayerFilter(body.GetObjectLayer());
  1412. #ifdef JPH_DEBUG_RENDERER
  1413. // Draw start and end shape of cast
  1414. if (sDrawMotionQualityLinearCast)
  1415. {
  1416. RMat44 com = body.GetCenterOfMassTransform();
  1417. body.GetShape()->Draw(DebugRenderer::sInstance, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  1418. DebugRenderer::sInstance->DrawArrow(com.GetTranslation(), com.GetTranslation() + ccd_body.mDeltaPosition, Color::sGreen, 0.1f);
  1419. body.GetShape()->Draw(DebugRenderer::sInstance, com.PostTranslated(ccd_body.mDeltaPosition), Vec3::sReplicate(1.0f), Color::sRed, false, true);
  1420. }
  1421. #endif // JPH_DEBUG_RENDERER
  1422. // Create a collector that will find the maximum distance allowed to travel while not penetrating more than 'max penetration'
  1423. class CCDNarrowPhaseCollector : public CastShapeCollector
  1424. {
  1425. public:
  1426. CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :
  1427. mBodyManager(inBodyManager),
  1428. mContactConstraintManager(inContactConstraintManager),
  1429. mCCDBody(inCCDBody),
  1430. mResult(inResult),
  1431. mDeltaTime(inDeltaTime)
  1432. {
  1433. }
  1434. virtual void AddHit(const ShapeCastResult &inResult) override
  1435. {
  1436. JPH_PROFILE_FUNCTION();
  1437. // Check if this is a possible earlier hit than the one before
  1438. float fraction = inResult.mFraction;
  1439. if (fraction < mCCDBody.mFractionPlusSlop)
  1440. {
  1441. // Normalize normal
  1442. Vec3 normal = inResult.mPenetrationAxis.Normalized();
  1443. // Calculate how much we can add to the fraction to penetrate the collision point by mMaxPenetration.
  1444. // Note that the normal is pointing towards body 2!
  1445. // Let the extra distance that we can travel along delta_pos be 'dist': mMaxPenetration / dist = cos(angle between normal and delta_pos) = normal . delta_pos / |delta_pos|
  1446. // <=> dist = mMaxPenetration * |delta_pos| / normal . delta_pos
  1447. // Converting to a faction: delta_fraction = dist / |delta_pos| = mLinearCastTreshold / normal . delta_pos
  1448. float denominator = normal.Dot(mCCDBody.mDeltaPosition);
  1449. if (denominator > mCCDBody.mMaxPenetration) // Avoid dividing by zero, if extra hit fraction > 1 there's also no point in continuing
  1450. {
  1451. float fraction_plus_slop = fraction + mCCDBody.mMaxPenetration / denominator;
  1452. if (fraction_plus_slop < mCCDBody.mFractionPlusSlop)
  1453. {
  1454. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID2);
  1455. // Check if we've already accepted all hits from this body
  1456. if (mValidateBodyPair)
  1457. {
  1458. // Validate the contact result
  1459. const Body &body1 = mBodyManager.GetBody(mCCDBody.mBodyID1);
  1460. ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(body1, body2, body1.GetCenterOfMassPosition(), inResult); // Note that the center of mass of body 1 is the start of the sweep and is used as base offset below
  1461. switch (validate_result)
  1462. {
  1463. case ValidateResult::AcceptContact:
  1464. // Just continue
  1465. break;
  1466. case ValidateResult::AcceptAllContactsForThisBodyPair:
  1467. // Accept this and all following contacts from this body
  1468. mValidateBodyPair = false;
  1469. break;
  1470. case ValidateResult::RejectContact:
  1471. return;
  1472. case ValidateResult::RejectAllContactsForThisBodyPair:
  1473. // Reject this and all following contacts from this body
  1474. mRejectAll = true;
  1475. ForceEarlyOut();
  1476. return;
  1477. }
  1478. }
  1479. // This is the earliest hit so far, store it
  1480. mCCDBody.mContactNormal = normal;
  1481. mCCDBody.mBodyID2 = inResult.mBodyID2;
  1482. mCCDBody.mFraction = fraction;
  1483. mCCDBody.mFractionPlusSlop = fraction_plus_slop;
  1484. mResult = inResult;
  1485. // Result was assuming body 2 is not moving, but it is, so we need to correct for it
  1486. Vec3 movement2 = fraction * sCalculateBodyMotion(body2, mDeltaTime);
  1487. if (!movement2.IsNearZero())
  1488. {
  1489. mResult.mContactPointOn1 += movement2;
  1490. mResult.mContactPointOn2 += movement2;
  1491. for (Vec3 &v : mResult.mShape1Face)
  1492. v += movement2;
  1493. for (Vec3 &v : mResult.mShape2Face)
  1494. v += movement2;
  1495. }
  1496. // Update early out fraction
  1497. CastShapeCollector::UpdateEarlyOutFraction(fraction_plus_slop);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. bool mValidateBodyPair; ///< If we still have to call the ValidateContactPoint for this body pair
  1503. bool mRejectAll; ///< Reject all further contacts between this body pair
  1504. private:
  1505. const BodyManager & mBodyManager;
  1506. ContactConstraintManager & mContactConstraintManager;
  1507. CCDBody & mCCDBody;
  1508. ShapeCastResult & mResult;
  1509. float mDeltaTime;
  1510. BodyID mAcceptedBodyID;
  1511. };
  1512. // Narrowphase collector
  1513. ShapeCastResult cast_shape_result;
  1514. CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, ccd_body, cast_shape_result, ioContext->mSubStepDeltaTime);
  1515. // This collector wraps the narrowphase collector and collects the closest hit
  1516. class CCDBroadPhaseCollector : public CastShapeBodyCollector
  1517. {
  1518. public:
  1519. CCDBroadPhaseCollector(const CCDBody &inCCDBody, const Body &inBody1, const RShapeCast &inShapeCast, ShapeCastSettings &inShapeCastSettings, CCDNarrowPhaseCollector &ioCollector, const BodyManager &inBodyManager, PhysicsUpdateContext::SubStep *inSubStep, float inDeltaTime) :
  1520. mCCDBody(inCCDBody),
  1521. mBody1(inBody1),
  1522. mBody1Extent(inShapeCast.mShapeWorldBounds.GetExtent()),
  1523. mShapeCast(inShapeCast),
  1524. mShapeCastSettings(inShapeCastSettings),
  1525. mCollector(ioCollector),
  1526. mBodyManager(inBodyManager),
  1527. mSubStep(inSubStep),
  1528. mDeltaTime(inDeltaTime)
  1529. {
  1530. }
  1531. virtual void AddHit(const BroadPhaseCastResult &inResult) override
  1532. {
  1533. JPH_PROFILE_FUNCTION();
  1534. JPH_ASSERT(inResult.mFraction <= GetEarlyOutFraction(), "This hit should not have been passed on to the collector");
  1535. // Test if we're colliding with ourselves
  1536. if (mBody1.GetID() == inResult.mBodyID)
  1537. return;
  1538. // Avoid treating duplicates, if both bodies are doing CCD then only consider collision if body ID < other body ID
  1539. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID);
  1540. const CCDBody *ccd_body2 = sGetCCDBody(body2, mSubStep);
  1541. if (ccd_body2 != nullptr && mCCDBody.mBodyID1 > ccd_body2->mBodyID1)
  1542. return;
  1543. // Test group filter
  1544. if (!mBody1.GetCollisionGroup().CanCollide(body2.GetCollisionGroup()))
  1545. return;
  1546. // TODO: For now we ignore sensors
  1547. if (body2.IsSensor())
  1548. return;
  1549. // Get relative movement of these two bodies
  1550. Vec3 direction = mShapeCast.mDirection - sCalculateBodyMotion(body2, mDeltaTime);
  1551. // Test if the remaining movement is less than our movement threshold
  1552. if (direction.LengthSq() < mCCDBody.mLinearCastThresholdSq)
  1553. return;
  1554. // Get the bounds of 2, widen it by the extent of 1 and test a ray to see if it hits earlier than the current early out fraction
  1555. AABox bounds = body2.GetWorldSpaceBounds();
  1556. bounds.mMin -= mBody1Extent;
  1557. bounds.mMax += mBody1Extent;
  1558. float hit_fraction = RayAABox(Vec3(mShapeCast.mCenterOfMassStart.GetTranslation()), RayInvDirection(direction), bounds.mMin, bounds.mMax);
  1559. if (hit_fraction > max(FLT_MIN, GetEarlyOutFraction())) // If early out fraction <= 0, we have the possibility of finding a deeper hit so we need to clamp the early out fraction
  1560. return;
  1561. // Reset collector (this is a new body pair)
  1562. mCollector.ResetEarlyOutFraction(GetEarlyOutFraction());
  1563. mCollector.mValidateBodyPair = true;
  1564. mCollector.mRejectAll = false;
  1565. // Provide direction as hint for the active edges algorithm
  1566. mShapeCastSettings.mActiveEdgeMovementDirection = direction;
  1567. // Do narrow phase collision check
  1568. RShapeCast relative_cast(mShapeCast.mShape, mShapeCast.mScale, mShapeCast.mCenterOfMassStart, direction, mShapeCast.mShapeWorldBounds);
  1569. body2.GetTransformedShape().CastShape(relative_cast, mShapeCastSettings, mShapeCast.mCenterOfMassStart.GetTranslation(), mCollector);
  1570. // Update early out fraction based on narrow phase collector
  1571. if (!mCollector.mRejectAll)
  1572. UpdateEarlyOutFraction(mCollector.GetEarlyOutFraction());
  1573. }
  1574. const CCDBody & mCCDBody;
  1575. const Body & mBody1;
  1576. Vec3 mBody1Extent;
  1577. RShapeCast mShapeCast;
  1578. ShapeCastSettings & mShapeCastSettings;
  1579. CCDNarrowPhaseCollector & mCollector;
  1580. const BodyManager & mBodyManager;
  1581. PhysicsUpdateContext::SubStep *mSubStep;
  1582. float mDeltaTime;
  1583. };
  1584. // Check if we collide with any other body. Note that we use the non-locking interface as we know the broadphase cannot be modified at this point.
  1585. RShapeCast shape_cast(body.GetShape(), Vec3::sReplicate(1.0f), body.GetCenterOfMassTransform(), ccd_body.mDeltaPosition);
  1586. CCDBroadPhaseCollector bp_collector(ccd_body, body, shape_cast, settings, np_collector, mBodyManager, ioSubStep, ioContext->mSubStepDeltaTime);
  1587. mBroadPhase->CastAABoxNoLock({ shape_cast.mShapeWorldBounds, shape_cast.mDirection }, bp_collector, broadphase_layer_filter, object_layer_filter);
  1588. // Check if there was a hit
  1589. if (ccd_body.mFractionPlusSlop < 1.0f)
  1590. {
  1591. const Body &body2 = mBodyManager.GetBody(ccd_body.mBodyID2);
  1592. // Determine contact manifold
  1593. ContactManifold manifold;
  1594. manifold.mBaseOffset = shape_cast.mCenterOfMassStart.GetTranslation();
  1595. ManifoldBetweenTwoFaces(cast_shape_result.mContactPointOn1, cast_shape_result.mContactPointOn2, cast_shape_result.mPenetrationAxis, mPhysicsSettings.mManifoldToleranceSq, cast_shape_result.mShape1Face, cast_shape_result.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  1596. manifold.mSubShapeID1 = cast_shape_result.mSubShapeID1;
  1597. manifold.mSubShapeID2 = cast_shape_result.mSubShapeID2;
  1598. manifold.mPenetrationDepth = cast_shape_result.mPenetrationDepth;
  1599. manifold.mWorldSpaceNormal = ccd_body.mContactNormal;
  1600. // Call contact point callbacks
  1601. mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);
  1602. // Calculate the average position from the manifold (this will result in the same impulse applied as when we apply impulses to all contact points)
  1603. if (manifold.mRelativeContactPointsOn2.size() > 1)
  1604. {
  1605. Vec3 average_contact_point = Vec3::sZero();
  1606. for (const Vec3 &v : manifold.mRelativeContactPointsOn2)
  1607. average_contact_point += v;
  1608. average_contact_point /= (float)manifold.mRelativeContactPointsOn2.size();
  1609. ccd_body.mContactPointOn2 = manifold.mBaseOffset + average_contact_point;
  1610. }
  1611. else
  1612. ccd_body.mContactPointOn2 = manifold.mBaseOffset + cast_shape_result.mContactPointOn2;
  1613. }
  1614. }
  1615. // Collect information from the contact allocator and accumulate it in the step.
  1616. sFinalizeContactAllocator(*ioSubStep->mStep, contact_allocator);
  1617. }
  1618. void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1619. {
  1620. #ifdef JPH_ENABLE_ASSERTS
  1621. // Read/write body access
  1622. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1623. // We activate bodies that we collide with
  1624. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  1625. #endif
  1626. uint32 num_active_bodies_after_find_collisions = ioSubStep->mStep->mActiveBodyReadIdx;
  1627. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1628. // Check if there's anything to do
  1629. uint num_ccd_bodies = ioSubStep->mNumCCDBodies;
  1630. if (num_ccd_bodies > 0)
  1631. {
  1632. // Sort on fraction so that we process earliest collisions first
  1633. // This is needed to make the simulation deterministic and also to be able to stop contact processing
  1634. // between body pairs if an earlier hit was found involving the body by another CCD body
  1635. // (if it's body ID < this CCD body's body ID - see filtering logic in CCDBroadPhaseCollector)
  1636. CCDBody **sorted_ccd_bodies = (CCDBody **)temp_allocator->Allocate(num_ccd_bodies * sizeof(CCDBody *));
  1637. {
  1638. JPH_PROFILE("Sort");
  1639. // We don't want to copy the entire struct (it's quite big), so we create a pointer array first
  1640. CCDBody *src_ccd_bodies = ioSubStep->mCCDBodies;
  1641. CCDBody **dst_ccd_bodies = sorted_ccd_bodies;
  1642. CCDBody **dst_ccd_bodies_end = dst_ccd_bodies + num_ccd_bodies;
  1643. while (dst_ccd_bodies < dst_ccd_bodies_end)
  1644. *(dst_ccd_bodies++) = src_ccd_bodies++;
  1645. // Which we then sort
  1646. QuickSort(sorted_ccd_bodies, sorted_ccd_bodies + num_ccd_bodies, [](const CCDBody *inBody1, const CCDBody *inBody2)
  1647. {
  1648. if (inBody1->mFractionPlusSlop != inBody2->mFractionPlusSlop)
  1649. return inBody1->mFractionPlusSlop < inBody2->mFractionPlusSlop;
  1650. return inBody1->mBodyID1 < inBody2->mBodyID1;
  1651. });
  1652. }
  1653. // We can collide with bodies that are not active, we track them here so we can activate them in one go at the end.
  1654. // This is also needed because we can't modify the active body array while we iterate it.
  1655. static constexpr int cBodiesBatch = 64;
  1656. BodyID *bodies_to_activate = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1657. int num_bodies_to_activate = 0;
  1658. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1659. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1660. int num_bodies_to_update_bounds = 0;
  1661. for (uint i = 0; i < num_ccd_bodies; ++i)
  1662. {
  1663. const CCDBody *ccd_body = sorted_ccd_bodies[i];
  1664. Body &body1 = mBodyManager.GetBody(ccd_body->mBodyID1);
  1665. MotionProperties *body_mp = body1.GetMotionProperties();
  1666. // If there was a hit
  1667. if (!ccd_body->mBodyID2.IsInvalid())
  1668. {
  1669. Body &body2 = mBodyManager.GetBody(ccd_body->mBodyID2);
  1670. // Determine if the other body has a CCD body
  1671. CCDBody *ccd_body2 = sGetCCDBody(body2, ioSubStep);
  1672. if (ccd_body2 != nullptr)
  1673. {
  1674. JPH_ASSERT(ccd_body2->mBodyID2 != ccd_body->mBodyID1, "If we collided with another body, that other body should have ignored collisions with us!");
  1675. // Check if the other body found a hit that is further away
  1676. if (ccd_body2->mFraction > ccd_body->mFraction)
  1677. {
  1678. // Reset the colliding body of the other CCD body. The other body will shorten its distance travelled and will not do any collision response (we'll do that).
  1679. // This means that at this point we have triggered a contact point add/persist for our further hit by accident for the other body.
  1680. // We accept this as calling the contact point callbacks here would require persisting the manifolds up to this point and doing the callbacks single threaded.
  1681. ccd_body2->mBodyID2 = BodyID();
  1682. ccd_body2->mFractionPlusSlop = ccd_body->mFraction;
  1683. }
  1684. }
  1685. // If the other body moved less than us before hitting something, we're not colliding with it so we again have triggered contact point add/persist callbacks by accident.
  1686. // We'll just move to the collision position anyway (as that's the last position we know is good), but we won't do any collision response.
  1687. if (ccd_body2 == nullptr || ccd_body2->mFraction >= ccd_body->mFraction)
  1688. {
  1689. // Calculate contact points relative to center of mass of both bodies
  1690. Vec3 r1_plus_u = Vec3(ccd_body->mContactPointOn2 - (body1.GetCenterOfMassPosition() + ccd_body->mFraction * ccd_body->mDeltaPosition));
  1691. Vec3 r2 = Vec3(ccd_body->mContactPointOn2 - body2.GetCenterOfMassPosition());
  1692. // Calculate velocity of collision points
  1693. Vec3 v1 = body1.GetPointVelocityCOM(r1_plus_u);
  1694. Vec3 v2 = body2.GetPointVelocityCOM(r2);
  1695. Vec3 relative_velocity = v2 - v1;
  1696. float normal_velocity = relative_velocity.Dot(ccd_body->mContactNormal);
  1697. // Calculate velocity bias due to restitution
  1698. float normal_velocity_bias;
  1699. if (ccd_body->mContactSettings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)
  1700. normal_velocity_bias = ccd_body->mContactSettings.mCombinedRestitution * normal_velocity;
  1701. else
  1702. normal_velocity_bias = 0.0f;
  1703. // Solve contact constraint
  1704. AxisConstraintPart contact_constraint;
  1705. contact_constraint.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, ccd_body->mContactNormal, normal_velocity_bias);
  1706. contact_constraint.SolveVelocityConstraint(body1, body2, ccd_body->mContactNormal, -FLT_MAX, FLT_MAX);
  1707. // Apply friction
  1708. if (ccd_body->mContactSettings.mCombinedFriction > 0.0f)
  1709. {
  1710. Vec3 tangent1 = ccd_body->mContactNormal.GetNormalizedPerpendicular();
  1711. Vec3 tangent2 = ccd_body->mContactNormal.Cross(tangent1);
  1712. float max_lambda_f = ccd_body->mContactSettings.mCombinedFriction * contact_constraint.GetTotalLambda();
  1713. AxisConstraintPart friction1;
  1714. friction1.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, tangent1, 0.0f);
  1715. friction1.SolveVelocityConstraint(body1, body2, tangent1, -max_lambda_f, max_lambda_f);
  1716. AxisConstraintPart friction2;
  1717. friction2.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, tangent2, 0.0f);
  1718. friction2.SolveVelocityConstraint(body1, body2, tangent2, -max_lambda_f, max_lambda_f);
  1719. }
  1720. // Clamp velocities
  1721. body_mp->ClampLinearVelocity();
  1722. body_mp->ClampAngularVelocity();
  1723. if (body2.IsDynamic())
  1724. {
  1725. MotionProperties *body2_mp = body2.GetMotionProperties();
  1726. body2_mp->ClampLinearVelocity();
  1727. body2_mp->ClampAngularVelocity();
  1728. // Activate the body if it is not already active
  1729. if (!body2.IsActive())
  1730. {
  1731. bodies_to_activate[num_bodies_to_activate++] = ccd_body->mBodyID2;
  1732. if (num_bodies_to_activate == cBodiesBatch)
  1733. {
  1734. // Batch is full, activate now
  1735. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1736. num_bodies_to_activate = 0;
  1737. }
  1738. }
  1739. }
  1740. #ifdef JPH_DEBUG_RENDERER
  1741. if (sDrawMotionQualityLinearCast)
  1742. {
  1743. // Draw the collision location
  1744. RMat44 collision_transform = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFraction * ccd_body->mDeltaPosition);
  1745. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform, Vec3::sReplicate(1.0f), Color::sYellow, false, true);
  1746. // Draw the collision location + slop
  1747. RMat44 collision_transform_plus_slop = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFractionPlusSlop * ccd_body->mDeltaPosition);
  1748. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform_plus_slop, Vec3::sReplicate(1.0f), Color::sOrange, false, true);
  1749. // Draw contact normal
  1750. DebugRenderer::sInstance->DrawArrow(ccd_body->mContactPointOn2, ccd_body->mContactPointOn2 - ccd_body->mContactNormal, Color::sYellow, 0.1f);
  1751. // Draw post contact velocity
  1752. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetLinearVelocity(), Color::sOrange, 0.1f);
  1753. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetAngularVelocity(), Color::sPurple, 0.1f);
  1754. }
  1755. #endif // JPH_DEBUG_RENDERER
  1756. }
  1757. }
  1758. // Update body position
  1759. body1.AddPositionStep(ccd_body->mDeltaPosition * ccd_body->mFractionPlusSlop);
  1760. // If the body was activated due to an earlier CCD step it will have an index in the active
  1761. // body list that it higher than the highest one we processed during FindCollisions
  1762. // which means it hasn't been assigned an island and will not be updated by an island
  1763. // this means that we need to update its bounds manually
  1764. if (body_mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1765. {
  1766. body1.CalculateWorldSpaceBoundsInternal();
  1767. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body1.GetID();
  1768. if (num_bodies_to_update_bounds == cBodiesBatch)
  1769. {
  1770. // Buffer full, flush now
  1771. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds);
  1772. num_bodies_to_update_bounds = 0;
  1773. }
  1774. }
  1775. }
  1776. // Activate the requested bodies
  1777. if (num_bodies_to_activate > 0)
  1778. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1779. // Notify change bounds on requested bodies
  1780. if (num_bodies_to_update_bounds > 0)
  1781. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1782. // Free the sorted ccd bodies
  1783. temp_allocator->Free(sorted_ccd_bodies, num_ccd_bodies * sizeof(CCDBody *));
  1784. }
  1785. // Ensure we free the CCD bodies array now, will not call the destructor!
  1786. temp_allocator->Free(ioSubStep->mActiveBodyToCCDBody, ioSubStep->mNumActiveBodyToCCDBody * sizeof(int));
  1787. ioSubStep->mActiveBodyToCCDBody = nullptr;
  1788. ioSubStep->mNumActiveBodyToCCDBody = 0;
  1789. temp_allocator->Free(ioSubStep->mCCDBodies, ioSubStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1790. ioSubStep->mCCDBodies = nullptr;
  1791. ioSubStep->mCCDBodiesCapacity = 0;
  1792. }
  1793. void PhysicsSystem::JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep)
  1794. {
  1795. #ifdef JPH_ENABLE_ASSERTS
  1796. // We don't touch any bodies
  1797. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1798. #endif
  1799. // Reset the Body::EFlags::InvalidateContactCache flag for all bodies
  1800. mBodyManager.ValidateContactCacheForAllBodies();
  1801. // Finalize the contact cache (this swaps the read and write versions of the contact cache)
  1802. // Trigger all contact removed callbacks by looking at last step contact points that have not been flagged as reused
  1803. mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(ioStep->mNumBodyPairs, ioStep->mNumManifolds);
  1804. }
  1805. class PhysicsSystem::BodiesToSleep : public NonCopyable
  1806. {
  1807. public:
  1808. static constexpr int cBodiesToSleepSize = 512;
  1809. static constexpr int cMaxBodiesToPutInBuffer = 128;
  1810. inline BodiesToSleep(BodyManager &inBodyManager, BodyID *inBodiesToSleepBuffer) : mBodyManager(inBodyManager), mBodiesToSleepBuffer(inBodiesToSleepBuffer), mBodiesToSleepCur(inBodiesToSleepBuffer) { }
  1811. inline ~BodiesToSleep()
  1812. {
  1813. // Flush the bodies to sleep buffer
  1814. int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);
  1815. if (num_bodies_in_buffer > 0)
  1816. mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);
  1817. }
  1818. inline void PutToSleep(const BodyID *inBegin, const BodyID *inEnd)
  1819. {
  1820. int num_bodies_to_sleep = int(inEnd - inBegin);
  1821. if (num_bodies_to_sleep > cMaxBodiesToPutInBuffer)
  1822. {
  1823. // Too many bodies, deactivate immediately
  1824. mBodyManager.DeactivateBodies(inBegin, num_bodies_to_sleep);
  1825. }
  1826. else
  1827. {
  1828. // Check if there's enough space in the bodies to sleep buffer
  1829. int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);
  1830. if (num_bodies_in_buffer + num_bodies_to_sleep > cBodiesToSleepSize)
  1831. {
  1832. // Flush the bodies to sleep buffer
  1833. mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);
  1834. mBodiesToSleepCur = mBodiesToSleepBuffer;
  1835. }
  1836. // Copy the bodies in the buffer
  1837. memcpy(mBodiesToSleepCur, inBegin, num_bodies_to_sleep * sizeof(BodyID));
  1838. mBodiesToSleepCur += num_bodies_to_sleep;
  1839. }
  1840. }
  1841. private:
  1842. BodyManager & mBodyManager;
  1843. BodyID * mBodiesToSleepBuffer;
  1844. BodyID * mBodiesToSleepCur;
  1845. };
  1846. void PhysicsSystem::CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::SubStep *ioSubStep, BodiesToSleep &ioBodiesToSleep)
  1847. {
  1848. // Get the bodies that belong to this island
  1849. BodyID *bodies_begin, *bodies_end;
  1850. mIslandBuilder.GetBodiesInIsland(inIslandIndex, bodies_begin, bodies_end);
  1851. // Only check sleeping in the last sub step of the last step
  1852. // Also resets force and torque used during the apply gravity phase
  1853. if (ioSubStep->mIsLastOfAll)
  1854. {
  1855. JPH_PROFILE("Check Sleeping");
  1856. static_assert(int(Body::ECanSleep::CannotSleep) == 0 && int(Body::ECanSleep::CanSleep) == 1, "Loop below makes this assumption");
  1857. int all_can_sleep = mPhysicsSettings.mAllowSleeping? int(Body::ECanSleep::CanSleep) : int(Body::ECanSleep::CannotSleep);
  1858. float time_before_sleep = mPhysicsSettings.mTimeBeforeSleep;
  1859. float max_movement = mPhysicsSettings.mPointVelocitySleepThreshold * time_before_sleep;
  1860. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1861. {
  1862. Body &body = mBodyManager.GetBody(*body_id);
  1863. // Update bounding box
  1864. body.CalculateWorldSpaceBoundsInternal();
  1865. // Update sleeping
  1866. all_can_sleep &= int(body.UpdateSleepStateInternal(ioContext->mSubStepDeltaTime, max_movement, time_before_sleep));
  1867. // Reset force and torque
  1868. body.GetMotionProperties()->ResetForceAndTorqueInternal();
  1869. }
  1870. // If all bodies indicate they can sleep we can deactivate them
  1871. if (all_can_sleep == int(Body::ECanSleep::CanSleep))
  1872. ioBodiesToSleep.PutToSleep(bodies_begin, bodies_end);
  1873. }
  1874. else
  1875. {
  1876. JPH_PROFILE("Update Bounds");
  1877. // Update bounding box only for all other sub steps
  1878. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1879. {
  1880. Body &body = mBodyManager.GetBody(*body_id);
  1881. body.CalculateWorldSpaceBoundsInternal();
  1882. }
  1883. }
  1884. // Notify broadphase of changed objects (find ccd contacts can do linear casts in the next step, so
  1885. // we need to do this every sub step)
  1886. // Note: Shuffles the BodyID's around!!!
  1887. mBroadPhase->NotifyBodiesAABBChanged(bodies_begin, int(bodies_end - bodies_begin), false);
  1888. }
  1889. void PhysicsSystem::JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1890. {
  1891. #ifdef JPH_ENABLE_ASSERTS
  1892. // We fix up position errors
  1893. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::ReadWrite);
  1894. // Can only deactivate bodies
  1895. BodyManager::GrantActiveBodiesAccess grant_active(false, true);
  1896. #endif
  1897. float delta_time = ioContext->mSubStepDeltaTime;
  1898. float baumgarte = mPhysicsSettings.mBaumgarte;
  1899. Constraint **active_constraints = ioContext->mActiveConstraints;
  1900. // Keep a buffer of bodies that need to go to sleep in order to not constantly lock the active bodies mutex and create contention between all solving threads
  1901. BodiesToSleep bodies_to_sleep(mBodyManager, (BodyID *)JPH_STACK_ALLOC(BodiesToSleep::cBodiesToSleepSize * sizeof(BodyID)));
  1902. bool check_islands = true, check_split_islands = ioContext->mUseLargeIslandSplitter;
  1903. do
  1904. {
  1905. // First try to get work from large islands
  1906. if (check_split_islands)
  1907. {
  1908. bool first_iteration;
  1909. uint split_island_index;
  1910. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1911. switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))
  1912. {
  1913. case LargeIslandSplitter::EStatus::BatchRetrieved:
  1914. // Solve the batch
  1915. ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);
  1916. mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  1917. // Mark the batch as processed
  1918. bool last_iteration, final_batch;
  1919. mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);
  1920. // The final batch will update all bounds and check sleeping
  1921. if (final_batch)
  1922. CheckSleepAndUpdateBounds(mLargeIslandSplitter.GetIslandIndex(split_island_index), ioContext, ioSubStep, bodies_to_sleep);
  1923. // We processed work, loop again
  1924. continue;
  1925. case LargeIslandSplitter::EStatus::WaitingForBatch:
  1926. break;
  1927. case LargeIslandSplitter::EStatus::AllBatchesDone:
  1928. check_split_islands = false;
  1929. break;
  1930. }
  1931. }
  1932. // If that didn't succeed try to process an island
  1933. if (check_islands)
  1934. {
  1935. // Next island
  1936. uint32 island_idx = ioSubStep->mSolvePositionConstraintsNextIsland++;
  1937. if (island_idx >= mIslandBuilder.GetNumIslands())
  1938. {
  1939. // We processed all islands, stop checking islands
  1940. check_islands = false;
  1941. continue;
  1942. }
  1943. JPH_PROFILE("Island");
  1944. // Get iterators for this island
  1945. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1946. mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  1947. mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  1948. // If this island is a large island, it will be picked up as a batch and we don't need to do anything here
  1949. uint num_items = uint(constraints_end - constraints_begin) + uint(contacts_end - contacts_begin);
  1950. if (ioContext->mUseLargeIslandSplitter
  1951. && num_items >= LargeIslandSplitter::cLargeIslandTreshold)
  1952. continue;
  1953. // Check if this island needs solving
  1954. if (num_items > 0)
  1955. {
  1956. // First iteration
  1957. int num_position_steps = mPhysicsSettings.mNumPositionSteps;
  1958. if (num_position_steps > 0)
  1959. {
  1960. // In the first iteration also calculate the number of position steps (this way we avoid pulling all constraints into the cache twice)
  1961. bool applied_impulse = ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte, num_position_steps);
  1962. applied_impulse |= mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  1963. // If no impulses were applied we can stop, otherwise we already did 1 iteration
  1964. if (!applied_impulse)
  1965. num_position_steps = 0;
  1966. else
  1967. --num_position_steps;
  1968. }
  1969. else
  1970. {
  1971. // Iterate the constraints to see if they override the number of position steps
  1972. for (const uint32 *c = constraints_begin; c < constraints_end; ++c)
  1973. num_position_steps = max(num_position_steps, active_constraints[*c]->GetNumPositionStepsOverride());
  1974. }
  1975. // Further iterations
  1976. for (int position_step = 0; position_step < num_position_steps; ++position_step)
  1977. {
  1978. bool applied_impulse = ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);
  1979. applied_impulse |= mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  1980. if (!applied_impulse)
  1981. break;
  1982. }
  1983. }
  1984. // After solving we will update all bounds and check sleeping
  1985. CheckSleepAndUpdateBounds(island_idx, ioContext, ioSubStep, bodies_to_sleep);
  1986. // We processed work, loop again
  1987. continue;
  1988. }
  1989. // If we didn't find any work, give up a time slice
  1990. std::this_thread::yield();
  1991. }
  1992. while (check_islands || check_split_islands);
  1993. }
  1994. void PhysicsSystem::SaveState(StateRecorder &inStream) const
  1995. {
  1996. JPH_PROFILE_FUNCTION();
  1997. inStream.Write(mPreviousSubStepDeltaTime);
  1998. inStream.Write(mGravity);
  1999. mBodyManager.SaveState(inStream);
  2000. mContactManager.SaveState(inStream);
  2001. mConstraintManager.SaveState(inStream);
  2002. }
  2003. bool PhysicsSystem::RestoreState(StateRecorder &inStream)
  2004. {
  2005. JPH_PROFILE_FUNCTION();
  2006. inStream.Read(mPreviousSubStepDeltaTime);
  2007. inStream.Read(mGravity);
  2008. if (!mBodyManager.RestoreState(inStream))
  2009. return false;
  2010. if (!mContactManager.RestoreState(inStream))
  2011. return false;
  2012. if (!mConstraintManager.RestoreState(inStream))
  2013. return false;
  2014. // Update bounding boxes for all bodies in the broadphase
  2015. Array<BodyID> bodies;
  2016. for (const Body *b : mBodyManager.GetBodies())
  2017. if (BodyManager::sIsValidBodyPointer(b) && b->IsInBroadPhase())
  2018. bodies.push_back(b->GetID());
  2019. if (!bodies.empty())
  2020. mBroadPhase->NotifyBodiesAABBChanged(&bodies[0], (int)bodies.size());
  2021. return true;
  2022. }
  2023. JPH_NAMESPACE_END