PhysicsSystem.cpp 115 KB

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