Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
Body.inl
Go to the documentation of this file.
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
8
10{
11 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
12
13 return RMat44::sRotationTranslation(mRotation, mPosition).PreTranslated(-mShape->GetCenterOfMass());
14}
15
17{
18 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
19
20 return RMat44::sRotationTranslation(mRotation, mPosition);
21}
22
24{
25 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
26
27 return RMat44::sInverseRotationTranslation(mRotation, mPosition);
28}
29
30inline static bool sIsValidSensorBodyPair(const Body &inSensor, const Body &inOther)
31{
32 // If the sensor is not an actual sensor then this is not a valid pair
33 if (!inSensor.IsSensor())
34 return false;
35
36 if (inSensor.SensorDetectsStatic())
37 return !inOther.IsDynamic(); // If the other body is dynamic, the pair will be handled when the bodies are swapped, otherwise we'll detect the collision twice
38 else
39 return inOther.IsKinematic(); // Only kinematic bodies are valid
40}
41
42inline bool Body::sFindCollidingPairsCanCollide(const Body &inBody1, const Body &inBody2)
43{
44 // First body should never be a soft body
45 JPH_ASSERT(!inBody1.IsSoftBody());
46
47 // One of these conditions must be true
48 // - One of the bodies must be dynamic to collide
49 // - A sensor can collide with non-dynamic bodies
50 if ((!inBody1.IsDynamic() && !inBody2.IsDynamic())
51 && !sIsValidSensorBodyPair(inBody1, inBody2)
52 && !sIsValidSensorBodyPair(inBody2, inBody1))
53 return false;
54
55 // Check that body 1 is active
56 uint32 body1_index_in_active_bodies = inBody1.GetIndexInActiveBodiesInternal();
57 JPH_ASSERT(!inBody1.IsStatic() && body1_index_in_active_bodies != Body::cInactiveIndex, "This function assumes that Body 1 is active");
58
59 // If the pair A, B collides we need to ensure that the pair B, A does not collide or else we will handle the collision twice.
60 // If A is the same body as B we don't want to collide (1)
61 // If A is dynamic and B is static we should collide (2)
62 // If A is dynamic / kinematic and B is dynamic / kinematic we should only collide if (kinematic vs kinematic is ruled out by the if above)
63 // - A is active and B is not yet active (3)
64 // - A is active and B will become active during this simulation step (4)
65 // - A is active and B is active, we require a condition that makes A, B collide and B, A not (5)
66 //
67 // In order to implement this we use the index in the active body list and make use of the fact that
68 // a body not in the active list has Body.Index = 0xffffffff which is the highest possible value for an uint32.
69 //
70 // Because we know that A is active we know that A.Index != 0xffffffff:
71 // (1) Because A.Index != 0xffffffff, if A.Index = B.Index then A = B, so to collide A.Index != B.Index
72 // (2) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's static and cannot be in the active list), so to collide A.Index != B.Index
73 // (3) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's not yet active), so to collide A.Index != B.Index
74 // (4) A.Index != 0xffffffff, B.Index = 0xffffffff currently. But it can activate during the Broad/NarrowPhase step at which point it
75 // will be added to the end of the active list which will make B.Index > A.Index (this holds only true when we don't deactivate
76 // bodies during the Broad/NarrowPhase step), so to collide A.Index < B.Index.
77 // (5) As tie breaker we can use the same condition A.Index < B.Index to collide, this means that if A, B collides then B, A won't
78 static_assert(Body::cInactiveIndex == 0xffffffff, "The algorithm below uses this value");
79 if (!inBody2.IsSoftBody() && body1_index_in_active_bodies >= inBody2.GetIndexInActiveBodiesInternal())
80 return false;
81 JPH_ASSERT(inBody1.GetID() != inBody2.GetID(), "Read the comment above, A and B are the same body which should not be possible!");
82
83 // Bodies in the same group don't collide
84 if (!inBody1.GetCollisionGroup().CanCollide(inBody2.GetCollisionGroup()))
85 return false;
86
87 return true;
88}
89
90void Body::AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
91{
93 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
94
95 // This used to use the equation: d/dt R(t) = 1/2 * w(t) * R(t) so that R(t + dt) = R(t) + 1/2 * w(t) * R(t) * dt
96 // See: Appendix B of An Introduction to Physically Based Modeling: Rigid Body Simulation II-Nonpenetration Constraints
97 // URL: https://www.cs.cmu.edu/~baraff/sigcourse/notesd2.pdf
98 // But this is a first order approximation and does not work well for kinematic ragdolls that are driven to a new
99 // pose if the poses differ enough. So now we split w(t) * dt into an axis and angle part and create a quaternion with it.
100 // Note that the resulting quaternion is normalized since otherwise numerical drift will eventually make the rotation non-normalized.
101 float len = inAngularVelocityTimesDeltaTime.Length();
102 if (len > 1.0e-6f)
103 {
104 mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, len) * mRotation).Normalized();
105 JPH_ASSERT(!mRotation.IsNaN());
106 }
107}
108
109void Body::SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
110{
112 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
113
114 // See comment at Body::AddRotationStep
115 float len = inAngularVelocityTimesDeltaTime.Length();
116 if (len > 1.0e-6f)
117 {
118 mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, -len) * mRotation).Normalized();
119 JPH_ASSERT(!mRotation.IsNaN());
120 }
121}
122
123Vec3 Body::GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, RVec3Arg inPosition) const
124{
126 return inv_com.Multiply3x3Transposed(mShape->GetSurfaceNormal(inSubShapeID, Vec3(inv_com * inPosition))).Normalized();
127}
128
135
136void Body::AddForce(Vec3Arg inForce, RVec3Arg inPosition)
137{
138 AddForce(inForce);
139 AddTorque(Vec3(inPosition - mPosition).Cross(inForce));
140}
141
143{
145
146 SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass());
147}
148
149void Body::AddImpulse(Vec3Arg inImpulse, RVec3Arg inPosition)
150{
152
153 SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass());
154
155 SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + mMotionProperties->MultiplyWorldSpaceInverseInertiaByVector(mRotation, Vec3(inPosition - mPosition).Cross(inImpulse)));
156}
157
158void Body::AddAngularImpulse(Vec3Arg inAngularImpulse)
159{
161
162 SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + mMotionProperties->MultiplyWorldSpaceInverseInertiaByVector(mRotation, inAngularImpulse));
163}
164
165void Body::GetSleepTestPoints(RVec3 *outPoints) const
166{
167 JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
168
169 // Center of mass is the first position
170 outPoints[0] = mPosition;
171
172 // The second and third position are on the largest axis of the bounding box
173 Vec3 extent = mShape->GetLocalBounds().GetExtent();
174 int lowest_component = extent.GetLowestComponentIndex();
175 Mat44 rotation = Mat44::sRotation(mRotation);
176 switch (lowest_component)
177 {
178 case 0:
179 outPoints[1] = mPosition + extent.GetY() * rotation.GetColumn3(1);
180 outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2);
181 break;
182
183 case 1:
184 outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0);
185 outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2);
186 break;
187
188 case 2:
189 outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0);
190 outPoints[2] = mPosition + extent.GetY() * rotation.GetColumn3(1);
191 break;
192
193 default:
194 JPH_ASSERT(false);
195 break;
196 }
197}
198
199void Body::ResetSleepTestSpheres()
200{
201 RVec3 points[3];
202 GetSleepTestPoints(points);
203 mMotionProperties->ResetSleepTestSpheres(points);
204}
205
#define JPH_NAMESPACE_END
Definition Core.h:354
std::uint32_t uint32
Definition Core.h:429
#define JPH_NAMESPACE_BEGIN
Definition Core.h:348
#define JPH_ASSERT(...)
Definition IssueReporting.h:33
Vec3 GetExtent() const
Get extent of bounding box (half of the size)
Definition AABox.h:111
Definition Body.h:35
const MotionProperties * GetMotionProperties() const
Access to the motion properties.
Definition Body.h:228
Vec3 GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, RVec3Arg inPosition) const
Get surface normal of a particular sub shape and its world space surface position on this body.
Definition Body.inl:123
bool SensorDetectsStatic() const
Check if this sensor detects static objects entering it.
Definition Body.h:86
bool IsDynamic() const
Check if this body is dynamic, which means that it moves and forces can act on it.
Definition Body.h:67
bool IsSensor() const
Check if this body is a sensor.
Definition Body.h:80
void AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Update rotation using an Euler step (using during position integrate & constraint solving)
Definition Body.inl:90
bool IsSoftBody() const
Check if this body is a soft body.
Definition Body.h:55
RMat44 GetWorldTransform() const
Calculates the transform of this body.
Definition Body.inl:9
const CollisionGroup & GetCollisionGroup() const
Collision group and sub-group ID, determines which other objects it collides with.
Definition Body.h:109
void SetLinearVelocityClamped(Vec3Arg inLinearVelocity)
Set world space linear velocity of the center of mass, will make sure the value is clamped against th...
Definition Body.h:132
uint32 GetIndexInActiveBodiesInternal() const
Access to the index in the BodyManager::mActiveBodies list.
Definition Body.h:295
static constexpr uint32 cInactiveIndex
Constant indicating that body is not active.
Definition Body.h:308
static bool sFindCollidingPairsCanCollide(const Body &inBody1, const Body &inBody2)
Definition Body.inl:42
Mat44 GetInverseInertia() const
Get inverse inertia tensor in world space.
Definition Body.inl:129
bool IsRigidBody() const
Check if this body is a rigid body.
Definition Body.h:52
bool IsStatic() const
Check if this body is static (not movable)
Definition Body.h:61
void SetAngularVelocityClamped(Vec3Arg inAngularVelocity)
Set world space angular velocity of the center of mass, will make sure the value is clamped against t...
Definition Body.h:141
RMat44 GetCenterOfMassTransform() const
Calculates the transform for this body's center of mass.
Definition Body.inl:16
RMat44 GetInverseCenterOfMassTransform() const
Calculates the inverse of the transform for this body's center of mass.
Definition Body.inl:23
void AddAngularImpulse(Vec3Arg inAngularImpulse)
Add angular impulse in world space (unit: N m s)
Definition Body.inl:158
void SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
Definition Body.inl:109
bool IsKinematic() const
Check if this body is kinematic (keyframed), which means that it will move according to its current v...
Definition Body.h:64
const BodyID & GetID() const
Get the id of this body.
Definition Body.h:46
void AddForce(Vec3Arg inForce)
Add force (unit: N) at center of mass for the next time step, will be reset after the next call to Ph...
Definition Body.h:150
void AddTorque(Vec3Arg inTorque)
Add torque (unit: N m) for the next time step, will be reset after the next call to PhysicsSimulation...
Definition Body.h:156
void AddImpulse(Vec3Arg inImpulse)
Add impulse to center of mass (unit: kg m/s)
Definition Body.inl:142
bool CanCollide(const CollisionGroup &inOther) const
Check if this object collides with another object.
Definition CollisionGroup.h:71
Holds a 4x4 matrix of floats, but supports also operations on the 3x3 upper left part of the matrix.
Definition Mat44.h:13
JPH_INLINE Mat44 PreTranslated(Vec3Arg inTranslation) const
Pre multiply by translation matrix: result = this * Mat44::sTranslation(inTranslation)
Definition Mat44.inl:891
JPH_INLINE Vec3 Multiply3x3Transposed(Vec3Arg inV) const
Multiply vector by only 3x3 part of the transpose of the matrix ( )
Definition Mat44.inl:327
JPH_INLINE Vec3 GetColumn3(uint inCol) const
Definition Mat44.h:155
static JPH_INLINE Mat44 sRotationTranslation(QuatArg inR, Vec3Arg inT)
Get matrix that rotates and translates.
Definition Mat44.inl:149
static JPH_INLINE Mat44 sRotation(Vec3Arg inAxis, float inAngle)
Rotate around arbitrary axis.
Definition Mat44.inl:139
static JPH_INLINE Mat44 sInverseRotationTranslation(QuatArg inR, Vec3Arg inT)
Get inverse matrix of sRotationTranslation.
Definition Mat44.inl:156
Vec3 GetLinearVelocity() const
Get world space linear velocity of the center of mass.
Definition MotionProperties.h:43
Vec3 GetAngularVelocity() const
Get world space angular velocity of the center of mass.
Definition MotionProperties.h:52
float GetInverseMass() const
Get inverse mass (1 / mass). Should only be called on a dynamic object (static or kinematic bodies ha...
Definition MotionProperties.h:95
JPH_INLINE Vec3 MultiplyWorldSpaceInverseInertiaByVector(QuatArg inBodyRotation, Vec3Arg inV) const
Multiply a vector with the inverse world space inertia tensor ( ). Zero if object is static or kinema...
Definition MotionProperties.inl:68
void ResetSleepTestSpheres(const RVec3 *inPoints)
Reset spheres to center around inPoints with radius 0.
Definition MotionProperties.inl:100
Mat44 GetInverseInertiaForRotation(Mat44Arg inRotation) const
Get inverse inertia matrix ( ) for a given object rotation (translation will be ignored)....
Definition MotionProperties.inl:59
static JPH_INLINE Quat sRotation(Vec3Arg inAxis, float inAngle)
Rotation from axis and angle.
Definition Quat.inl:74
bool IsNaN() const
If any component of this quaternion is a NaN (not a number)
Definition Quat.h:62
virtual AABox GetLocalBounds() const =0
Get local bounding box including convex radius, this box is centered around the center of mass rather...
virtual Vec3 GetCenterOfMass() const
All shapes are centered around their center of mass. This function returns the center of mass positio...
Definition Shape.h:199
virtual Vec3 GetSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inLocalSurfacePosition) const =0
A sub shape id contains a path to an element (usually a triangle or other primitive type) of a compou...
Definition SubShapeID.h:23
Definition Vec3.h:16
JPH_INLINE Vec3 Normalized() const
Normalize vector.
Definition Vec3.inl:694
JPH_INLINE float GetX() const
Get individual components.
Definition Vec3.h:123
JPH_INLINE float Length() const
Length of vector.
Definition Vec3.inl:669
JPH_INLINE int GetLowestComponentIndex() const
Get index of component with lowest value.
Definition Vec3.inl:554
JPH_INLINE float GetY() const
Definition Vec3.h:124
JPH_INLINE float GetZ() const
Definition Vec3.h:125