Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/PhysicsUpdateContext.h
9906 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Body/BodyPair.h>7#include <Jolt/Physics/Collision/ContactListener.h>8#include <Jolt/Physics/Collision/BroadPhase/BroadPhase.h>9#include <Jolt/Core/StaticArray.h>10#include <Jolt/Core/JobSystem.h>11#include <Jolt/Core/STLTempAllocator.h>1213JPH_NAMESPACE_BEGIN1415class PhysicsSystem;16class IslandBuilder;17class Constraint;18class TempAllocator;19class SoftBodyUpdateContext;2021/// Information used during the Update call22class PhysicsUpdateContext : public NonCopyable23{24public:25/// Destructor26explicit PhysicsUpdateContext(TempAllocator &inTempAllocator);27~PhysicsUpdateContext();2829static constexpr int cMaxConcurrency = 32; ///< Maximum supported amount of concurrent jobs3031using JobHandleArray = StaticArray<JobHandle, cMaxConcurrency>;3233struct Step;3435struct BodyPairQueue36{37atomic<uint32> mWriteIdx { 0 }; ///< Next index to write in mBodyPair array (need to add thread index * mMaxBodyPairsPerQueue and modulo mMaxBodyPairsPerQueue)38uint8 mPadding1[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Moved to own cache line to avoid conflicts with consumer jobs3940atomic<uint32> mReadIdx { 0 }; ///< Next index to read in mBodyPair array (need to add thread index * mMaxBodyPairsPerQueue and modulo mMaxBodyPairsPerQueue)41uint8 mPadding2[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Moved to own cache line to avoid conflicts with producer/consumer jobs42};4344using BodyPairQueues = StaticArray<BodyPairQueue, cMaxConcurrency>;4546using JobMask = uint32; ///< A mask that has as many bits as we can have concurrent jobs47static_assert(sizeof(JobMask) * 8 >= cMaxConcurrency);4849/// Structure that contains data needed for each collision step.50struct Step51{52Step() = default;53Step(const Step &) { JPH_ASSERT(false); } // vector needs a copy constructor, but we're never going to call it5455PhysicsUpdateContext *mContext; ///< The physics update context5657bool mIsFirst; ///< If this is the first step58bool mIsLast; ///< If this is the last step5960BroadPhase::UpdateState mBroadPhaseUpdateState; ///< Handle returned by Broadphase::UpdatePrepare6162uint32 mNumActiveBodiesAtStepStart; ///< Number of bodies that were active at the start of the physics update step. Only these bodies will receive gravity (they are the first N in the active body list).6364atomic<uint32> mDetermineActiveConstraintReadIdx { 0 }; ///< Next constraint for determine active constraints65uint8 mPadding1[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic6667atomic<uint32> mNumActiveConstraints { 0 }; ///< Number of constraints in the mActiveConstraints array68uint8 mPadding2[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic6970atomic<uint32> mSetupVelocityConstraintsReadIdx { 0 }; ///< Next constraint for setting up velocity constraints71uint8 mPadding3[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic7273atomic<uint32> mStepListenerReadIdx { 0 }; ///< Next step listener to call74uint8 mPadding4[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic7576atomic<uint32> mApplyGravityReadIdx { 0 }; ///< Next body to apply gravity to77uint8 mPadding5[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic7879atomic<uint32> mActiveBodyReadIdx { 0 }; ///< Index of fist active body that has not yet been processed by the broadphase80uint8 mPadding6[JPH_CACHE_LINE_SIZE - sizeof(atomic<uint32>)];///< Padding to avoid sharing cache line with the next atomic8182BodyPairQueues mBodyPairQueues; ///< Queues in which to put body pairs that need to be tested by the narrowphase8384uint32 mMaxBodyPairsPerQueue; ///< Amount of body pairs that we can queue per queue8586atomic<JobMask> mActiveFindCollisionJobs; ///< A bitmask that indicates which jobs are still active8788atomic<uint> mNumBodyPairs { 0 }; ///< The number of body pairs found in this step (used to size the contact cache in the next step)89atomic<uint> mNumManifolds { 0 }; ///< The number of manifolds found in this step (used to size the contact cache in the next step)9091atomic<uint32> mSolveVelocityConstraintsNextIsland { 0 }; ///< Next island that needs to be processed for the solve velocity constraints step (doesn't need own cache line since position jobs don't run at same time)92atomic<uint32> mSolvePositionConstraintsNextIsland { 0 }; ///< Next island that needs to be processed for the solve position constraints step (doesn't need own cache line since velocity jobs don't run at same time)9394/// Contains the information needed to cast a body through the scene to do continuous collision detection95struct CCDBody96{97CCDBody(BodyID inBodyID1, Vec3Arg inDeltaPosition, float inLinearCastThresholdSq, float inMaxPenetration) : mDeltaPosition(inDeltaPosition), mBodyID1(inBodyID1), mLinearCastThresholdSq(inLinearCastThresholdSq), mMaxPenetration(inMaxPenetration) { }9899Vec3 mDeltaPosition; ///< Desired rotation step100Vec3 mContactNormal; ///< World space normal of closest hit (only valid if mFractionPlusSlop < 1)101RVec3 mContactPointOn2; ///< World space contact point on body 2 of closest hit (only valid if mFractionPlusSlop < 1)102BodyID mBodyID1; ///< Body 1 (the body that is performing collision detection)103BodyID mBodyID2; ///< Body 2 (the body of the closest hit, only valid if mFractionPlusSlop < 1)104SubShapeID mSubShapeID2; ///< Sub shape of body 2 that was hit (only valid if mFractionPlusSlop < 1)105float mFraction = 1.0f; ///< Fraction at which the hit occurred106float mFractionPlusSlop = 1.0f; ///< Fraction at which the hit occurred + extra delta to allow body to penetrate by mMaxPenetration107float mLinearCastThresholdSq; ///< Maximum allowed squared movement before doing a linear cast (determined by inner radius of shape)108float mMaxPenetration; ///< Maximum allowed penetration (determined by inner radius of shape)109ContactSettings mContactSettings; ///< The contact settings for this contact110};111atomic<uint32> mIntegrateVelocityReadIdx { 0 }; ///< Next active body index to take when integrating velocities112CCDBody * mCCDBodies = nullptr; ///< List of bodies that need to do continuous collision detection113uint32 mCCDBodiesCapacity = 0; ///< Capacity of the mCCDBodies list114atomic<uint32> mNumCCDBodies = 0; ///< Number of CCD bodies in mCCDBodies115atomic<uint32> mNextCCDBody { 0 }; ///< Next unprocessed body index in mCCDBodies116int * mActiveBodyToCCDBody = nullptr; ///< A mapping between an index in BodyManager::mActiveBodies and the index in mCCDBodies117uint32 mNumActiveBodyToCCDBody = 0; ///< Number of indices in mActiveBodyToCCDBody118119// Jobs in order of execution (some run in parallel)120JobHandle mBroadPhasePrepare; ///< Prepares the new tree in the background121JobHandleArray mStepListeners; ///< Listeners to notify of the beginning of a physics step122JobHandleArray mDetermineActiveConstraints; ///< Determine which constraints will be active during this step123JobHandleArray mApplyGravity; ///< Update velocities of bodies with gravity124JobHandleArray mFindCollisions; ///< Find all collisions between active bodies an the world125JobHandle mUpdateBroadphaseFinalize; ///< Swap the newly built tree with the current tree126JobHandleArray mSetupVelocityConstraints; ///< Calculate properties for all constraints in the constraint manager127JobHandle mBuildIslandsFromConstraints; ///< Go over all constraints and assign the bodies they're attached to to an island128JobHandle mFinalizeIslands; ///< Finalize calculation simulation islands129JobHandle mBodySetIslandIndex; ///< Set the current island index on each body (not used by the simulation, only for drawing purposes)130JobHandleArray mSolveVelocityConstraints; ///< Solve the constraints in the velocity domain131JobHandle mPreIntegrateVelocity; ///< Setup integration of all body positions132JobHandleArray mIntegrateVelocity; ///< Integrate all body positions133JobHandle mPostIntegrateVelocity; ///< Finalize integration of all body positions134JobHandle mResolveCCDContacts; ///< Updates the positions and velocities for all bodies that need continuous collision detection135JobHandleArray mSolvePositionConstraints; ///< Solve all constraints in the position domain136JobHandle mContactRemovedCallbacks; ///< Calls the contact removed callbacks137JobHandle mSoftBodyPrepare; ///< Prepares updating the soft bodies138JobHandleArray mSoftBodyCollide; ///< Finds all colliding shapes for soft bodies139JobHandleArray mSoftBodySimulate; ///< Simulates all particles140JobHandle mSoftBodyFinalize; ///< Finalizes the soft body update141JobHandle mStartNextStep; ///< Job that kicks the next step (empty for the last step)142};143144using Steps = Array<Step, STLTempAllocator<Step>>;145146/// Maximum amount of concurrent jobs on this machine147int GetMaxConcurrency() const { const int max_concurrency = PhysicsUpdateContext::cMaxConcurrency; return min(max_concurrency, mJobSystem->GetMaxConcurrency()); } ///< Need to put max concurrency in temp var as min requires a reference148149PhysicsSystem * mPhysicsSystem; ///< The physics system we belong to150TempAllocator * mTempAllocator; ///< Temporary allocator used during the update151JobSystem * mJobSystem; ///< Job system that processes jobs152JobSystem::Barrier * mBarrier; ///< Barrier used to wait for all physics jobs to complete153154float mStepDeltaTime; ///< Delta time for a simulation step (collision step)155float mWarmStartImpulseRatio; ///< Ratio of this step delta time vs last step156atomic<uint32> mErrors { 0 }; ///< Errors that occurred during the update, actual type is EPhysicsUpdateError157158Constraint ** mActiveConstraints = nullptr; ///< Constraints that were active at the start of the physics update step (activating bodies can activate constraints and we need a consistent snapshot). Only these constraints will be resolved.159160BodyPair * mBodyPairs = nullptr; ///< A list of body pairs found by the broadphase161162IslandBuilder * mIslandBuilder; ///< Keeps track of connected bodies and builds islands for multithreaded velocity/position update163164Steps mSteps;165166uint mNumSoftBodies; ///< Number of active soft bodies in the simulation167SoftBodyUpdateContext * mSoftBodyUpdateContexts = nullptr; ///< Contexts for updating soft bodies168atomic<uint> mSoftBodyToCollide { 0 }; ///< Next soft body to take when running SoftBodyCollide jobs169};170171JPH_NAMESPACE_END172173174