Debian Codegraph @

thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.h

raw symbols SCIP
1 // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2 // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
3 // SPDX-License-Identifier: MIT
4
5 #pragma once
6
7 #include <Jolt/Core/Reference.h>
8 #include <Jolt/Core/Result.h>
9 #include <Jolt/Physics/Body/BodyCreationSettings.h>
10 #include <Jolt/Physics/Constraints/TwoBodyConstraint.h>
11 #include <Jolt/Skeleton/Skeleton.h>
12 #include <Jolt/Skeleton/SkeletonPose.h>
13 #include <Jolt/Physics/EActivation.h>
14
15 JPH_NAMESPACE_BEGIN
16
17 class Ragdoll;
18 class PhysicsSystem;
19
20 /// Contains the structure of a ragdoll
21 class JPH_EXPORT RagdollSettings : public RefTarget<RagdollSettings>
22 {
23 JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(JPH_EXPORT, RagdollSettings)
24
25 public:
26 /// Stabilize the constraints of the ragdoll
27 /// @return True on success, false on failure.
28 bool Stabilize();
29
30 /// After the ragdoll has been fully configured, call this function to automatically create and add a GroupFilterTable collision filter to all bodies
31 /// and configure them so that parent and children don't collide.
32 ///
33 /// This will:
34 /// - Create a GroupFilterTable and assign it to all of the bodies in a ragdoll.
35 /// - Each body in your ragdoll will get a SubGroupID that is equal to the joint index in the Skeleton that it is attached to.
36 /// - Loop over all joints in the Skeleton and call GroupFilterTable::DisableCollision(joint index, parent joint index).
37 /// - When a pose is provided through inJointMatrices the function will detect collisions between joints
38 /// (they must be separated by more than inMinSeparationDistance to be treated as not colliding) and automatically disable collisions.
39 ///
40 /// When you create an instance using Ragdoll::CreateRagdoll pass in a unique GroupID for each ragdoll (e.g. a simple counter), note that this number
41 /// should be unique throughout the PhysicsSystem, so if you have different types of ragdolls they should not share the same GroupID.
42 void DisableParentChildCollisions(const Mat44 *inJointMatrices = nullptr, float inMinSeparationDistance = 0.0f);
43
44 /// Saves the state of this object in binary form to inStream.
45 /// @param inStream The stream to save the state to
46 /// @param inSaveShapes If the shapes should be saved as well (these could be shared between ragdolls, in which case the calling application may want to write custom code to restore them)
47 /// @param inSaveGroupFilter If the group filter should be saved as well (these could be shared)
48 void SaveBinaryState(StreamOut &inStream, bool inSaveShapes, bool inSaveGroupFilter) const;
49
50 using RagdollResult = Result<Ref<RagdollSettings>>;
51
52 /// Restore a saved ragdoll from inStream
53 static RagdollResult sRestoreFromBinaryState(StreamIn &inStream);
54
55 /// Create ragdoll instance from these settings
56 /// @return Newly created ragdoll or null when out of bodies
57 Ragdoll * CreateRagdoll(CollisionGroup::GroupID inCollisionGroup, uint64 inUserData, PhysicsSystem *inSystem) const;
58
59 /// Access to the skeleton of this ragdoll
60 const Skeleton * GetSkeleton() const { return mSkeleton; }
61 Skeleton * GetSkeleton() { return mSkeleton; }
62
63 /// Calculate the map needed for GetBodyIndexToConstraintIndex()
64 void CalculateBodyIndexToConstraintIndex();
65
66 /// Get table that maps a body index to the constraint index with which it is connected to its parent. -1 if there is no constraint associated with the body.
67 /// Note that this will only tell you which constraint connects the body to its parent, it will not look in the additional constraint list.
68 const Array<int> & GetBodyIndexToConstraintIndex() const { return mBodyIndexToConstraintIndex; }
69
70 /// Map a single body index to a constraint index
71 int GetConstraintIndexForBodyIndex(int inBodyIndex) const { return mBodyIndexToConstraintIndex[inBodyIndex]; }
72
73 /// Calculate the map needed for GetConstraintIndexToBodyIdxPair()
74 void CalculateConstraintIndexToBodyIdxPair();
75
76 using BodyIdxPair = std::pair<int, int>;
77
78 /// Table that maps a constraint index (index in mConstraints) to the indices of the bodies that the constraint is connected to (index in mBodyIDs)
79 const Array<BodyIdxPair> & GetConstraintIndexToBodyIdxPair() const { return mConstraintIndexToBodyIdxPair; }
80
81 /// Map a single constraint index (index in mConstraints) to the indices of the bodies that the constraint is connected to (index in mBodyIDs)
82 BodyIdxPair GetBodyIndicesForConstraintIndex(int inConstraintIndex) const { return mConstraintIndexToBodyIdxPair[inConstraintIndex]; }
83
84 /// A single rigid body sub part of the ragdoll
85 class Part : public BodyCreationSettings
86 {
87 JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(JPH_EXPORT, Part)
88
89 public:
90 Ref<TwoBodyConstraintSettings> mToParent;
91 };
92
93 /// List of ragdoll parts
94 using PartVector = Array<Part>; ///< The constraint that connects this part to its parent part (should be null for the root)
95
96 /// A constraint that connects two bodies in a ragdoll (for non parent child related constraints)
97 class AdditionalConstraint
98 {
99 JPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(JPH_EXPORT, AdditionalConstraint)
100
101 public:
102 /// Constructors
103 AdditionalConstraint() = default;
104 AdditionalConstraint(int inBodyIdx1, int inBodyIdx2, TwoBodyConstraintSettings *inConstraint) : mBodyIdx { inBodyIdx1, inBodyIdx2 }, mConstraint(inConstraint) { }
105
106 int mBodyIdx[2]; ///< Indices of the bodies that this constraint connects
107 Ref<TwoBodyConstraintSettings> mConstraint; ///< The constraint that connects these bodies
108 };
109
110 /// List of additional constraints
111 using AdditionalConstraintVector = Array<AdditionalConstraint>;
112
113 /// The skeleton for this ragdoll
114 Ref<Skeleton> mSkeleton;
115
116 /// For each of the joints, the body and constraint attaching it to its parent body (1-on-1 with mSkeleton.GetJoints())
117 PartVector mParts;
118
119 /// A list of constraints that connects two bodies in a ragdoll (for non parent child related constraints)
120 AdditionalConstraintVector mAdditionalConstraints;
121
122 private:
123 /// Table that maps a body index (index in mBodyIDs) to the constraint index with which it is connected to its parent. -1 if there is no constraint associated with the body.
124 Array<int> mBodyIndexToConstraintIndex;
125
126 /// Table that maps a constraint index (index in mConstraints) to the indices of the bodies that the constraint is connected to (index in mBodyIDs)
127 Array<BodyIdxPair> mConstraintIndexToBodyIdxPair;
128 };
129
130 /// Runtime ragdoll information
131 class JPH_EXPORT Ragdoll : public RefTarget<Ragdoll>, public NonCopyable
132 {
133 public:
134 JPH_OVERRIDE_NEW_DELETE
135
136 /// Constructor
137 explicit Ragdoll(PhysicsSystem *inSystem) : mSystem(inSystem) { }
138
139 /// Destructor
140 ~Ragdoll();
141
142 /// Add bodies and constraints to the system and optionally activate the bodies
143 void AddToPhysicsSystem(EActivation inActivationMode, bool inLockBodies = true);
144
145 /// Remove bodies and constraints from the system
146 void RemoveFromPhysicsSystem(bool inLockBodies = true);
147
148 /// Wake up all bodies in the ragdoll
149 void Activate(bool inLockBodies = true);
150
151 /// Check if one or more of the bodies in the ragdoll are active.
152 /// Note that this involves locking the bodies (if inLockBodies is true) and looping over them. An alternative and possibly faster
153 /// way could be to install a BodyActivationListener and count the number of active bodies of a ragdoll as they're activated / deactivated
154 /// (basically check if the body that activates / deactivates is in GetBodyIDs() and increment / decrement a counter).
155 bool IsActive(bool inLockBodies = true) const;
156
157 /// Set the group ID on all bodies in the ragdoll
158 void SetGroupID(CollisionGroup::GroupID inGroupID, bool inLockBodies = true);
159
160 /// Set the ragdoll to a pose (calls BodyInterface::SetPositionAndRotation to instantly move the ragdoll)
161 void SetPose(const SkeletonPose &inPose, bool inLockBodies = true);
162
163 /// Lower level version of SetPose that directly takes the world space joint matrices
164 void SetPose(RVec3Arg inRootOffset, const Mat44 *inJointMatrices, bool inLockBodies = true);
165
166 /// Get the ragdoll pose (uses the world transform of the bodies to calculate the pose)
167 void GetPose(SkeletonPose &outPose, bool inLockBodies = true);
168
169 /// Lower level version of GetPose that directly returns the world space joint matrices
170 void GetPose(RVec3 &outRootOffset, Mat44 *outJointMatrices, bool inLockBodies = true);
171
172 /// This function calls ResetWarmStart on all constraints. It can be used after calling SetPose to reset previous frames impulses. See: Constraint::ResetWarmStart.
173 void ResetWarmStart();
174
175 /// Drive the ragdoll to a specific pose by setting velocities on each of the bodies so that it will reach inPose in inDeltaTime
176 void DriveToPoseUsingKinematics(const SkeletonPose &inPose, float inDeltaTime, bool inLockBodies = true);
177
178 /// Lower level version of DriveToPoseUsingKinematics that directly takes the world space joint matrices
179 void DriveToPoseUsingKinematics(RVec3Arg inRootOffset, const Mat44 *inJointMatrices, float inDeltaTime, bool inLockBodies = true);
180
181 /// Drive the ragdoll to a specific pose by activating the motors on each constraint
182 void DriveToPoseUsingMotors(const SkeletonPose &inPose);
183
184 /// Control the linear and velocity of all bodies in the ragdoll
185 void SetLinearAndAngularVelocity(Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, bool inLockBodies = true);
186
187 /// Set the world space linear velocity of all bodies in the ragdoll.
188 void SetLinearVelocity(Vec3Arg inLinearVelocity, bool inLockBodies = true);
189
190 /// Add a world space velocity (in m/s) to all bodies in the ragdoll.
191 void AddLinearVelocity(Vec3Arg inLinearVelocity, bool inLockBodies = true);
192
193 /// Add impulse to all bodies of the ragdoll (center of mass of each of them)
194 void AddImpulse(Vec3Arg inImpulse, bool inLockBodies = true);
195
196 /// Get the position and orientation of the root of the ragdoll
197 void GetRootTransform(RVec3 &outPosition, Quat &outRotation, bool inLockBodies = true) const;
198
199 /// Get number of bodies in the ragdoll
200 size_t GetBodyCount() const { return mBodyIDs.size(); }
201
202 /// Access a body ID
203 BodyID GetBodyID(int inBodyIndex) const { return mBodyIDs[inBodyIndex]; }
204
205 /// Access to the array of body IDs
206 const Array<BodyID> & GetBodyIDs() const { return mBodyIDs; }
207
208 /// Get number of constraints in the ragdoll
209 size_t GetConstraintCount() const { return mConstraints.size(); }
210
211 /// Access a constraint by index
212 TwoBodyConstraint * GetConstraint(int inConstraintIndex) { return mConstraints[inConstraintIndex]; }
213
214 /// Access a constraint by index
215 const TwoBodyConstraint * GetConstraint(int inConstraintIndex) const { return mConstraints[inConstraintIndex]; }
216
217 /// Get world space bounding box for all bodies of the ragdoll
218 AABox GetWorldSpaceBounds(bool inLockBodies = true) const;
219
220 /// Get the settings object that created this ragdoll
221 const RagdollSettings * GetRagdollSettings() const { return mRagdollSettings; }
222
223 private:
224 /// For RagdollSettings::CreateRagdoll function
225 friend class RagdollSettings;
226
227 /// The settings that created this ragdoll
228 RefConst<RagdollSettings> mRagdollSettings;
229
230 /// The bodies and constraints that this ragdoll consists of (1-on-1 with mRagdollSettings->mParts)
231 Array<BodyID> mBodyIDs;
232
233 /// Array of constraints that connect the bodies together
234 Array<Ref<TwoBodyConstraint>> mConstraints;
235
236 /// Cached physics system
237 PhysicsSystem * mSystem;
238 };
239
240 JPH_NAMESPACE_END