CharacterVirtual.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Character/CharacterBase.h>
  6. #include <Jolt/Physics/Character/CharacterID.h>
  7. #include <Jolt/Physics/Body/MotionType.h>
  8. #include <Jolt/Physics/Body/BodyFilter.h>
  9. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
  10. #include <Jolt/Physics/Collision/ObjectLayer.h>
  11. #include <Jolt/Physics/Collision/TransformedShape.h>
  12. #include <Jolt/Core/STLTempAllocator.h>
  13. #include <Jolt/Core/UnorderedMap.h>
  14. JPH_NAMESPACE_BEGIN
  15. class CharacterVirtual;
  16. class CollideShapeSettings;
  17. /// Contains the configuration of a character
  18. class JPH_EXPORT CharacterVirtualSettings : public CharacterBaseSettings
  19. {
  20. public:
  21. JPH_OVERRIDE_NEW_DELETE
  22. /// Constructor
  23. CharacterVirtualSettings() = default;
  24. CharacterVirtualSettings(const CharacterVirtualSettings &) = default;
  25. CharacterVirtualSettings & operator = (const CharacterVirtualSettings &) = default;
  26. /// ID to give to this character. This is used for deterministically sorting and as an identifier to represent the character in the contact removal callback.
  27. CharacterID mID = CharacterID::sNextCharacterID();
  28. /// Character mass (kg). Used to push down objects with gravity when the character is standing on top.
  29. float mMass = 70.0f;
  30. /// Maximum force with which the character can push other bodies (N).
  31. float mMaxStrength = 100.0f;
  32. /// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  33. Vec3 mShapeOffset = Vec3::sZero();
  34. ///@name Movement settings
  35. EBackFaceMode mBackFaceMode = EBackFaceMode::CollideWithBackFaces; ///< When colliding with back faces, the character will not be able to move through back facing triangles. Use this if you have triangles that need to collide on both sides.
  36. float mPredictiveContactDistance = 0.1f; ///< How far to scan outside of the shape for predictive contacts. A value of 0 will most likely cause the character to get stuck as it cannot properly calculate a sliding direction anymore. A value that's too high will cause ghost collisions.
  37. uint mMaxCollisionIterations = 5; ///< Max amount of collision loops
  38. uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving
  39. float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done
  40. float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry
  41. float mCharacterPadding = 0.02f; ///< How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
  42. uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection
  43. float mHitReductionCosMaxAngle = 0.999f; ///< Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  44. float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  45. /// This character can optionally have an inner rigid body. This rigid body can be used to give the character presence in the world. When set it means that:
  46. /// - Regular collision checks (e.g. NarrowPhaseQuery::CastRay) will collide with the rigid body (they cannot collide with CharacterVirtual since it is not added to the broad phase)
  47. /// - Regular contact callbacks will be called through the ContactListener (next to the ones that will be passed to the CharacterContactListener)
  48. /// - Fast moving objects of motion quality LinearCast will not be able to pass through the CharacterVirtual in 1 time step
  49. RefConst<Shape> mInnerBodyShape;
  50. /// For a deterministic simulation, it is important to have a deterministic body ID. When set and when mInnerBodyShape is specified,
  51. /// the inner body will be created with this specified ID instead of a generated ID.
  52. BodyID mInnerBodyIDOverride;
  53. /// Layer that the inner rigid body will be added to
  54. ObjectLayer mInnerBodyLayer = 0;
  55. };
  56. /// This class contains settings that allow you to override the behavior of a character's collision response
  57. class CharacterContactSettings
  58. {
  59. public:
  60. /// True when the object can push the virtual character.
  61. bool mCanPushCharacter = true;
  62. /// True when the virtual character can apply impulses (push) the body.
  63. /// Note that this only works against rigid bodies. Other CharacterVirtual objects can only be moved in their own update,
  64. /// so you must ensure that in their OnCharacterContactAdded mCanPushCharacter is true.
  65. bool mCanReceiveImpulses = true;
  66. };
  67. /// This class receives callbacks when a virtual character hits something.
  68. /// Once created, register it on a CharacterVirtual by using the character's SetListener method.
  69. class JPH_EXPORT CharacterContactListener
  70. {
  71. public:
  72. /// Destructor
  73. virtual ~CharacterContactListener() = default;
  74. /// Callback to adjust the velocity of a body as seen by the character. Can be adjusted to e.g. implement a conveyor belt or an inertial dampener system of a sci-fi space ship.
  75. /// Note that inBody2 is locked during the callback so you can read its properties freely.
  76. virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }
  77. /// Checks if a character can collide with specified body. Return true if the contact is valid.
  78. virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }
  79. /// Same as OnContactValidate but when colliding with a CharacterVirtual
  80. virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) { return true; }
  81. /// Called whenever the character collides with a body for the first time.
  82. /// @param inCharacter Character that is being solved
  83. /// @param inBodyID2 Body ID of body that is being hit
  84. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  85. /// @param inContactPosition World space contact position
  86. /// @param inContactNormal World space contact normal
  87. /// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
  88. virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  89. /// Called whenever the character persists colliding with a body.
  90. /// @param inCharacter Character that is being solved
  91. /// @param inBodyID2 Body ID of body that is being hit
  92. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  93. /// @param inContactPosition World space contact position
  94. /// @param inContactNormal World space contact normal
  95. /// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
  96. virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  97. /// Called whenever the character loses contact with a body.
  98. /// Note that there is no guarantee that the body or its sub shape still exists at this point. The body may have been deleted since the last update.
  99. /// @param inCharacter Character that is being solved
  100. /// @param inBodyID2 Body ID of body that is being hit
  101. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  102. virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }
  103. /// Same as OnContactAdded but when colliding with a CharacterVirtual
  104. virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  105. /// Same as OnContactPersisted but when colliding with a CharacterVirtual
  106. virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  107. /// Same as OnContactRemoved but when colliding with a CharacterVirtual
  108. /// Note that inOtherCharacterID can be the ID of a character that has been deleted. This happens if the character was in contact with this character during the last update, but has been deleted since.
  109. virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }
  110. /// Called whenever a contact is being used by the solver. Allows the listener to override the resulting character velocity (e.g. by preventing sliding along certain surfaces).
  111. /// @param inCharacter Character that is being solved
  112. /// @param inBodyID2 Body ID of body that is being hit
  113. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  114. /// @param inContactPosition World space contact position
  115. /// @param inContactNormal World space contact normal
  116. /// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)
  117. /// @param inContactMaterial Material of contact point
  118. /// @param inCharacterVelocity World space velocity of the character prior to hitting this contact
  119. /// @param ioNewCharacterVelocity Contains the calculated world space velocity of the character after hitting this contact, this velocity slides along the surface of the contact. Can be modified by the listener to provide an alternative velocity.
  120. virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) { /* Default do nothing */ }
  121. /// Same as OnContactSolve but when colliding with a CharacterVirtual
  122. virtual void OnCharacterContactSolve(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) { /* Default do nothing */ }
  123. };
  124. /// Interface class that allows a CharacterVirtual to check collision with other CharacterVirtual instances.
  125. /// Since CharacterVirtual instances are not registered anywhere, it is up to the application to test collision against relevant characters.
  126. /// The characters could be stored in a tree structure to make this more efficient.
  127. class JPH_EXPORT CharacterVsCharacterCollision : public NonCopyable
  128. {
  129. public:
  130. virtual ~CharacterVsCharacterCollision() = default;
  131. /// Collide a character against other CharacterVirtuals.
  132. /// @param inCharacter The character to collide.
  133. /// @param inCenterOfMassTransform Center of mass transform for this character.
  134. /// @param inCollideShapeSettings Settings for the collision check.
  135. /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
  136. /// @param ioCollector Collision collector that receives the collision results.
  137. virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const = 0;
  138. /// Cast a character against other CharacterVirtuals.
  139. /// @param inCharacter The character to cast.
  140. /// @param inCenterOfMassTransform Center of mass transform for this character.
  141. /// @param inDirection Direction and length to cast in.
  142. /// @param inShapeCastSettings Settings for the shape cast.
  143. /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
  144. /// @param ioCollector Collision collector that receives the collision results.
  145. virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const = 0;
  146. };
  147. /// Simple collision checker that loops over all registered characters.
  148. /// This is a brute force checking algorithm. If you have a lot of characters you may want to store your characters
  149. /// in a hierarchical structure to make this more efficient.
  150. /// Note that this is not thread safe, so make sure that only one CharacterVirtual is checking collision at a time.
  151. class JPH_EXPORT CharacterVsCharacterCollisionSimple : public CharacterVsCharacterCollision
  152. {
  153. public:
  154. /// Add a character to the list of characters to check collision against.
  155. void Add(CharacterVirtual *inCharacter) { mCharacters.push_back(inCharacter); }
  156. /// Remove a character from the list of characters to check collision against.
  157. void Remove(const CharacterVirtual *inCharacter);
  158. // See: CharacterVsCharacterCollision
  159. virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const override;
  160. virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const override;
  161. Array<CharacterVirtual *> mCharacters; ///< The list of characters to check collision against
  162. };
  163. /// Runtime character object.
  164. /// This object usually represents the player. Contrary to the Character class it doesn't use a rigid body but moves doing collision checks only (hence the name virtual).
  165. /// The advantage of this is that you can determine when the character moves in the frame (usually this has to happen at a very particular point in the frame)
  166. /// but the downside is that other objects don't see this virtual character. To make a CharacterVirtual visible to the simulation, you can optionally create an inner
  167. /// rigid body through CharacterVirtualSettings::mInnerBodyShape. A CharacterVirtual is not tracked by the PhysicsSystem so you need to update it yourself. This also means
  168. /// that a call to PhysicsSystem::SaveState will not save its state, you need to call CharacterVirtual::SaveState yourself.
  169. class JPH_EXPORT CharacterVirtual : public CharacterBase
  170. {
  171. public:
  172. JPH_OVERRIDE_NEW_DELETE
  173. /// Constructor
  174. /// @param inSettings The settings for the character
  175. /// @param inPosition Initial position for the character
  176. /// @param inRotation Initial rotation for the character (usually only around the up-axis)
  177. /// @param inUserData Application specific value
  178. /// @param inSystem Physics system that this character will be added to
  179. CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, uint64 inUserData, PhysicsSystem *inSystem);
  180. /// Constructor without user data
  181. CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem) : CharacterVirtual(inSettings, inPosition, inRotation, 0, inSystem) { }
  182. /// Destructor
  183. virtual ~CharacterVirtual() override;
  184. /// The ID of this character
  185. inline const CharacterID & GetID() const { return mID; }
  186. /// Set the contact listener
  187. void SetListener(CharacterContactListener *inListener) { mListener = inListener; }
  188. /// Get the current contact listener
  189. CharacterContactListener * GetListener() const { return mListener; }
  190. /// Set the character vs character collision interface
  191. void SetCharacterVsCharacterCollision(CharacterVsCharacterCollision *inCharacterVsCharacterCollision) { mCharacterVsCharacterCollision = inCharacterVsCharacterCollision; }
  192. /// Get the linear velocity of the character (m / s)
  193. Vec3 GetLinearVelocity() const { return mLinearVelocity; }
  194. /// Set the linear velocity of the character (m / s)
  195. void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }
  196. /// Get the position of the character
  197. RVec3 GetPosition() const { return mPosition; }
  198. /// Set the position of the character
  199. void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; UpdateInnerBodyTransform(); }
  200. /// Get the rotation of the character
  201. Quat GetRotation() const { return mRotation; }
  202. /// Set the rotation of the character
  203. void SetRotation(QuatArg inRotation) { mRotation = inRotation; UpdateInnerBodyTransform(); }
  204. // Get the center of mass position of the shape
  205. inline RVec3 GetCenterOfMassPosition() const { return mPosition + (mRotation * (mShapeOffset + mShape->GetCenterOfMass()) + mCharacterPadding * mUp); }
  206. /// Calculate the world transform of the character
  207. RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }
  208. /// Calculates the transform for this character's center of mass
  209. RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }
  210. /// Character mass (kg)
  211. float GetMass() const { return mMass; }
  212. void SetMass(float inMass) { mMass = inMass; }
  213. /// Maximum force with which the character can push other bodies (N)
  214. float GetMaxStrength() const { return mMaxStrength; }
  215. void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }
  216. /// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  217. float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }
  218. void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }
  219. /// Set to indicate that extra effort should be made to try to remove ghost contacts (collisions with internal edges of a mesh). This is more expensive but makes bodies move smoother over a mesh with convex edges.
  220. bool GetEnhancedInternalEdgeRemoval() const { return mEnhancedInternalEdgeRemoval; }
  221. void SetEnhancedInternalEdgeRemoval(bool inApply) { mEnhancedInternalEdgeRemoval = inApply; }
  222. /// Character padding
  223. float GetCharacterPadding() const { return mCharacterPadding; }
  224. /// Max num hits to collect in order to avoid excess of contact points collection
  225. uint GetMaxNumHits() const { return mMaxNumHits; }
  226. void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }
  227. /// Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  228. float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }
  229. void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }
  230. /// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.
  231. /// This can be used to find areas that have too complex geometry for the character to navigate properly.
  232. /// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will
  233. /// try to do its best to select the most relevant contacts to avoid the character from getting stuck.
  234. bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }
  235. /// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space. Note that setting it on the fly can cause the shape to teleport into collision.
  236. Vec3 GetShapeOffset() const { return mShapeOffset; }
  237. void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; UpdateInnerBodyTransform(); }
  238. /// Access to the user data, can be used for anything by the application
  239. uint64 GetUserData() const { return mUserData; }
  240. void SetUserData(uint64 inUserData);
  241. /// Optional inner rigid body that proxies the character in the world. Can be used to update body properties.
  242. BodyID GetInnerBodyID() const { return mInnerBodyID; }
  243. /// This function can be called prior to calling Update() to convert a desired velocity into a velocity that won't make the character move further onto steep slopes.
  244. /// This velocity can then be set on the character using SetLinearVelocity()
  245. /// @param inDesiredVelocity Velocity to clamp against steep walls
  246. /// @return A new velocity vector that won't make the character move up steep slopes
  247. Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;
  248. /// This function is internally called by Update, WalkStairs, StickToFloor and ExtendedUpdate and is responsible for tracking if contacts are added, persisted or removed.
  249. /// If you want to do multiple operations on a character (e.g. first Update then WalkStairs), you can surround the code with a StartTrackingContactChanges and FinishTrackingContactChanges pair
  250. /// to only receive a single callback per contact on the CharacterContactListener. If you don't do this then you could for example receive a contact added callback during the Update and a
  251. /// contact persisted callback during WalkStairs.
  252. void StartTrackingContactChanges();
  253. /// This call triggers contact removal callbacks and is used in conjunction with StartTrackingContactChanges.
  254. void FinishTrackingContactChanges();
  255. /// This is the main update function. It moves the character according to its current velocity (the character is similar to a kinematic body in the sense
  256. /// that you set the velocity and the character will follow unless collision is blocking the way). Note it's your own responsibility to apply gravity to the character velocity!
  257. /// Different surface materials (like ice) can be emulated by getting the ground material and adjusting the velocity and/or the max slope angle accordingly every frame.
  258. /// @param inDeltaTime Time step to simulate.
  259. /// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
  260. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  261. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  262. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  263. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  264. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  265. void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  266. /// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).
  267. /// You would call WalkStairs to attempt to step up stairs.
  268. /// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pushing into a step.
  269. bool CanWalkStairs(Vec3Arg inLinearVelocity) const;
  270. /// When stair walking is needed, you can call the WalkStairs function to cast up, forward and down again to try to find a valid position
  271. /// @param inDeltaTime Time step to simulate.
  272. /// @param inStepUp The direction and distance to step up (this corresponds to the max step height)
  273. /// @param inStepForward The direction and distance to step forward after the step up
  274. /// @param inStepForwardTest When running at a high frequency, inStepForward can be very small and it's likely that you hit the side of the stairs on the way down. This could produce a normal that violates the max slope angle. If this happens, we test again using this distance from the up position to see if we find a valid slope.
  275. /// @param inStepDownExtra An additional translation that is added when stepping down at the end. Allows you to step further down than up. Set to zero if you don't want this. Should be in the opposite direction of up.
  276. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  277. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  278. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  279. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  280. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  281. /// @return true if the stair walk was successful
  282. bool WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg inStepForward, Vec3Arg inStepForwardTest, Vec3Arg inStepDownExtra, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  283. /// This function can be used to artificially keep the character to the floor. Normally when a character is on a small step and starts moving horizontally, the character will
  284. /// lose contact with the floor because the initial vertical velocity is zero while the horizontal velocity is quite high. To prevent the character from losing contact with the floor,
  285. /// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.
  286. /// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)
  287. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  288. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  289. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  290. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  291. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  292. /// @return True if the character was successfully projected onto the floor.
  293. bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  294. /// Settings struct with settings for ExtendedUpdate
  295. struct ExtendedUpdateSettings
  296. {
  297. Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.
  298. Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.
  299. float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  300. float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  301. float mWalkStairsCosAngleForwardContact { Cos(DegreesToRadians(75.0f)) }; ///< Cos(angle) where angle is the maximum angle between the ground normal in the horizontal plane and the character forward vector where we're willing to adjust the step forward test towards the contact normal.
  302. Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra
  303. };
  304. /// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.
  305. /// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:
  306. /// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity
  307. /// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity
  308. /// @param inDeltaTime Time step to simulate.
  309. /// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
  310. /// @param inSettings A structure containing settings for the algorithm.
  311. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  312. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  313. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  314. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  315. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  316. void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  317. /// This function can be used after a character has teleported to determine the new contacts with the world.
  318. void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  319. /// Use the ground body ID to get an updated estimate of the ground velocity. This function can be used if the ground body has moved / changed velocity and you want a new estimate of the ground velocity.
  320. /// It will not perform collision detection, so is less accurate than RefreshContacts but a lot faster.
  321. void UpdateGroundVelocity();
  322. /// Switch the shape of the character (e.g. for stance).
  323. /// @param inShape The shape to switch to.
  324. /// @param inMaxPenetrationDepth When inMaxPenetrationDepth is not FLT_MAX, it checks if the new shape collides before switching shape. This is the max penetration we're willing to accept after the switch.
  325. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  326. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  327. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  328. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  329. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  330. /// @return Returns true if the switch succeeded.
  331. bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  332. /// Updates the shape of the inner rigid body. Should be called after a successful call to SetShape.
  333. void SetInnerBodyShape(const Shape *inShape);
  334. /// Get the transformed shape that represents the volume of the character, can be used for collision checks.
  335. TransformedShape GetTransformedShape() const { return TransformedShape(GetCenterOfMassPosition(), mRotation, mShape, mInnerBodyID); }
  336. /// @brief Get all contacts for the character at a particular location.
  337. /// When colliding with another character virtual, this pointer will be provided through CollideShapeCollector::SetUserContext before adding a hit.
  338. /// @param inPosition Position to test, note that this position will be corrected for the character padding.
  339. /// @param inRotation Rotation at which to test the shape.
  340. /// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.
  341. /// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).
  342. /// @param inShape Shape to test collision with.
  343. /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
  344. /// @param ioCollector Collision collector that receives the collision results.
  345. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  346. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  347. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  348. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  349. void CheckCollision(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  350. /// Get the character settings that can recreate this character
  351. CharacterVirtualSettings GetCharacterVirtualSettings() const;
  352. // Saving / restoring state for replay
  353. virtual void SaveState(StateRecorder &inStream) const override;
  354. virtual void RestoreState(StateRecorder &inStream) override;
  355. #ifdef JPH_DEBUG_RENDERER
  356. static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them
  357. static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm
  358. static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm
  359. #endif
  360. /// Uniquely identifies a contact between a character and another body or character
  361. class ContactKey
  362. {
  363. public:
  364. /// Constructor
  365. ContactKey() = default;
  366. ContactKey(const ContactKey &inContact) = default;
  367. ContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }
  368. ContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }
  369. ContactKey & operator = (const ContactKey &inContact) = default;
  370. /// Checks if two contacts refer to the same body (or virtual character)
  371. inline bool IsSameBody(const ContactKey &inOther) const { return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB; }
  372. /// Equality operator
  373. bool operator == (const ContactKey &inRHS) const
  374. {
  375. return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;
  376. }
  377. bool operator != (const ContactKey &inRHS) const
  378. {
  379. return !(*this == inRHS);
  380. }
  381. /// Hash of this structure
  382. uint64 GetHash() const
  383. {
  384. static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(ContactKey), "No padding expected");
  385. return HashBytes(this, sizeof(ContactKey));
  386. }
  387. // Saving / restoring state for replay
  388. void SaveState(StateRecorder &inStream) const;
  389. void RestoreState(StateRecorder &inStream);
  390. BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)
  391. CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)
  392. SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with
  393. };
  394. /// Encapsulates a collision contact
  395. struct Contact : public ContactKey
  396. {
  397. // Saving / restoring state for replay
  398. void SaveState(StateRecorder &inStream) const;
  399. void RestoreState(StateRecorder &inStream);
  400. RVec3 mPosition; ///< Position where the character makes contact
  401. Vec3 mLinearVelocity; ///< Velocity of the contact point
  402. Vec3 mContactNormal; ///< Contact normal, pointing towards the character
  403. Vec3 mSurfaceNormal; ///< Surface normal of the contact
  404. float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive
  405. float mFraction; ///< Fraction along the path where this contact takes place
  406. EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact
  407. bool mIsSensorB; ///< If B is a sensor
  408. const CharacterVirtual * mCharacterB = nullptr; ///< Character we're colliding with (if not nullptr). Note that this may be a dangling pointer when accessed through GetActiveContacts(), use mCharacterIDB instead.
  409. uint64 mUserData; ///< User data of B
  410. const PhysicsMaterial * mMaterial; ///< Material of B
  411. bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)
  412. bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor
  413. bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character
  414. };
  415. using TempContactList = Array<Contact, STLTempAllocator<Contact>>;
  416. using ContactList = Array<Contact>;
  417. /// Access to the internal list of contacts that the character has found.
  418. /// Note that only contacts that have their mHadCollision flag set are actual contacts.
  419. const ContactList & GetActiveContacts() const { return mActiveContacts; }
  420. /// Check if the character is currently in contact with or has collided with another body in the last operation (e.g. Update or WalkStairs)
  421. bool HasCollidedWith(const BodyID &inBody) const
  422. {
  423. for (const CharacterVirtual::Contact &c : mActiveContacts)
  424. if (c.mHadCollision && c.mBodyB == inBody)
  425. return true;
  426. return false;
  427. }
  428. /// Check if the character is currently in contact with or has collided with another character in the last time step (e.g. Update or WalkStairs)
  429. bool HasCollidedWith(const CharacterID &inCharacterID) const
  430. {
  431. for (const CharacterVirtual::Contact &c : mActiveContacts)
  432. if (c.mHadCollision && c.mCharacterIDB == inCharacterID)
  433. return true;
  434. return false;
  435. }
  436. /// Check if the character is currently in contact with or has collided with another character in the last time step (e.g. Update or WalkStairs)
  437. bool HasCollidedWith(const CharacterVirtual *inCharacter) const
  438. {
  439. return HasCollidedWith(inCharacter->GetID());
  440. }
  441. private:
  442. // Sorting predicate for making contact order deterministic
  443. struct ContactOrderingPredicate
  444. {
  445. inline bool operator () (const Contact &inLHS, const Contact &inRHS) const
  446. {
  447. if (inLHS.mBodyB != inRHS.mBodyB)
  448. return inLHS.mBodyB < inRHS.mBodyB;
  449. if (inLHS.mCharacterIDB != inRHS.mCharacterIDB)
  450. return inLHS.mCharacterIDB < inRHS.mCharacterIDB;
  451. return inLHS.mSubShapeIDB.GetValue() < inRHS.mSubShapeIDB.GetValue();
  452. }
  453. };
  454. using IgnoredContactList = Array<ContactKey, STLTempAllocator<ContactKey>>;
  455. // A constraint that limits the movement of the character
  456. struct Constraint
  457. {
  458. Contact * mContact; ///< Contact that this constraint was generated from
  459. float mTOI; ///< Calculated time of impact (can be negative if penetrating)
  460. float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)
  461. Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)
  462. Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)
  463. bool mIsSteepSlope = false; ///< If this constraint belongs to a steep slope
  464. };
  465. using ConstraintList = Array<Constraint, STLTempAllocator<Constraint>>;
  466. // Collision collector that collects hits for CollideShape
  467. class ContactCollector : public CollideShapeCollector
  468. {
  469. public:
  470. ContactCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, uint inMaxHits, float inHitReductionCosMaxAngle, Vec3Arg inUp, RVec3Arg inBaseOffset, TempContactList &outContacts) : mBaseOffset(inBaseOffset), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mContacts(outContacts), mMaxHits(inMaxHits), mHitReductionCosMaxAngle(inHitReductionCosMaxAngle) { }
  471. virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }
  472. virtual void AddHit(const CollideShapeResult &inResult) override;
  473. RVec3 mBaseOffset;
  474. Vec3 mUp;
  475. PhysicsSystem * mSystem;
  476. const CharacterVirtual * mCharacter;
  477. CharacterVirtual * mOtherCharacter = nullptr;
  478. TempContactList & mContacts;
  479. uint mMaxHits;
  480. float mHitReductionCosMaxAngle;
  481. bool mMaxHitsExceeded = false;
  482. };
  483. // A collision collector that collects hits for CastShape
  484. class ContactCastCollector : public CastShapeCollector
  485. {
  486. public:
  487. ContactCastCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, Vec3Arg inDisplacement, Vec3Arg inUp, const IgnoredContactList &inIgnoredContacts, RVec3Arg inBaseOffset, Contact &outContact) : mBaseOffset(inBaseOffset), mDisplacement(inDisplacement), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mIgnoredContacts(inIgnoredContacts), mContact(outContact) { }
  488. virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }
  489. virtual void AddHit(const ShapeCastResult &inResult) override;
  490. RVec3 mBaseOffset;
  491. Vec3 mDisplacement;
  492. Vec3 mUp;
  493. PhysicsSystem * mSystem;
  494. const CharacterVirtual * mCharacter;
  495. CharacterVirtual * mOtherCharacter = nullptr;
  496. const IgnoredContactList & mIgnoredContacts;
  497. Contact & mContact;
  498. };
  499. // Helper function to convert a Jolt collision result into a contact
  500. template <class taCollector>
  501. inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);
  502. inline static void sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);
  503. // Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry
  504. void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator
  505. #ifdef JPH_DEBUG_RENDERER
  506. , bool inDrawConstraints = false
  507. #endif // JPH_DEBUG_RENDERER
  508. );
  509. // Ask the callback if inContact is a valid contact point
  510. bool ValidateContact(const Contact &inContact) const;
  511. // Trigger the contact callback for inContact and get the contact settings
  512. void ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings);
  513. // Tests the shape for collision around inPosition
  514. void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  515. // Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck
  516. void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;
  517. // Convert contacts into constraints. The character is assumed to start at the origin and the constraints are planes around the origin that confine the movement of the character.
  518. void DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const;
  519. // Use the constraints to solve the displacement of the character. This will slide the character on the planes around the origin for as far as possible.
  520. void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator
  521. #ifdef JPH_DEBUG_RENDERER
  522. , bool inDrawConstraints = false
  523. #endif // JPH_DEBUG_RENDERER
  524. );
  525. // Get the velocity of a body adjusted by the contact listener
  526. void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;
  527. // Calculate the ground velocity of the character assuming it's standing on an object with specified linear and angular velocity and with specified center of mass.
  528. // Note that we don't just take the point velocity because a point on an object with angular velocity traces an arc,
  529. // so if you just take point velocity * delta time you get an error that accumulates over time
  530. Vec3 CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const;
  531. // Handle contact with physics object that we're colliding against
  532. bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime);
  533. // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision
  534. bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  535. // Store contacts so that we have proper ground information
  536. void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);
  537. // This function will determine which contacts are touching the character and will calculate the one that is supporting us
  538. void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);
  539. /// This function can be called after moving the character to a new colliding position
  540. void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  541. // This function returns the actual center of mass of the shape, not corrected for the character padding
  542. inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const
  543. {
  544. return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);
  545. }
  546. // This function returns the position of the inner rigid body
  547. inline RVec3 GetInnerBodyPosition() const
  548. {
  549. return mPosition + (mRotation * mShapeOffset + mCharacterPadding * mUp);
  550. }
  551. // Move the inner rigid body to the current position
  552. void UpdateInnerBodyTransform();
  553. // ID
  554. CharacterID mID;
  555. // Our main listener for contacts
  556. CharacterContactListener * mListener = nullptr;
  557. // Interface to detect collision between characters
  558. CharacterVsCharacterCollision * mCharacterVsCharacterCollision = nullptr;
  559. // Movement settings
  560. EBackFaceMode mBackFaceMode; // When colliding with back faces, the character will not be able to move through back facing triangles. Use this if you have triangles that need to collide on both sides.
  561. float mPredictiveContactDistance; // How far to scan outside of the shape for predictive contacts. A value of 0 will most likely cause the character to get stuck as it cannot properly calculate a sliding direction anymore. A value that's too high will cause ghost collisions.
  562. uint mMaxCollisionIterations; // Max amount of collision loops
  563. uint mMaxConstraintIterations; // How often to try stepping in the constraint solving
  564. float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done
  565. float mCollisionTolerance; // How far we're willing to penetrate geometry
  566. float mCharacterPadding; // How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
  567. uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection
  568. float mHitReductionCosMaxAngle; // Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  569. float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  570. bool mEnhancedInternalEdgeRemoval; // Set to indicate that extra effort should be made to try to remove ghost contacts (collisions with internal edges of a mesh). This is more expensive but makes bodies move smoother over a mesh with convex edges.
  571. // Character mass (kg)
  572. float mMass;
  573. // Maximum force with which the character can push other bodies (N)
  574. float mMaxStrength;
  575. // An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  576. Vec3 mShapeOffset = Vec3::sZero();
  577. // Current position (of the base, not the center of mass)
  578. RVec3 mPosition = RVec3::sZero();
  579. // Current rotation (of the base, not of the center of mass)
  580. Quat mRotation = Quat::sIdentity();
  581. // Current linear velocity
  582. Vec3 mLinearVelocity = Vec3::sZero();
  583. // List of contacts that were active in the last frame
  584. ContactList mActiveContacts;
  585. // Remembers how often we called StartTrackingContactChanges
  586. int mTrackingContactChanges = 0;
  587. // View from a contact listener perspective on which contacts have been added/removed
  588. struct ListenerContactValue
  589. {
  590. ListenerContactValue() = default;
  591. explicit ListenerContactValue(const CharacterContactSettings &inSettings) : mSettings(inSettings) { }
  592. CharacterContactSettings mSettings;
  593. int mCount = 0;
  594. };
  595. using ListenerContacts = UnorderedMap<ContactKey, ListenerContactValue>;
  596. ListenerContacts mListenerContacts;
  597. // Remembers the delta time of the last update
  598. float mLastDeltaTime = 1.0f / 60.0f;
  599. // Remember if we exceeded the maximum number of hits and had to remove similar contacts
  600. mutable bool mMaxHitsExceeded = false;
  601. // User data, can be used for anything by the application
  602. uint64 mUserData = 0;
  603. // The inner rigid body that proxies the character in the world
  604. BodyID mInnerBodyID;
  605. };
  606. JPH_NAMESPACE_END