PhysicsSystem.cpp 89 KB

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