PhysicsSystem.cpp 110 KB

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