PhysicsSystem.cpp 92 KB

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