Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/PointConstraintPart.h
9913 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/Body.h>7#include <Jolt/Physics/StateRecorder.h>89JPH_NAMESPACE_BEGIN1011/// Constrains movement along 3 axis12///13/// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.2.114///15/// Constraint equation (eq 45):16///17/// \f[C = p_2 - p_1\f]18///19/// Jacobian (transposed) (eq 47):20///21/// \f[J^T = \begin{bmatrix}-E & r1x & E & -r2x^T\end{bmatrix}22/// = \begin{bmatrix}-E^T \\ r1x^T \\ E^T \\ -r2x^T\end{bmatrix}23/// = \begin{bmatrix}-E \\ -r1x \\ E \\ r2x\end{bmatrix}\f]24///25/// Used terms (here and below, everything in world space):\n26/// p1, p2 = constraint points.\n27/// r1 = p1 - x1.\n28/// r2 = p2 - x2.\n29/// r1x = 3x3 matrix for which r1x v = r1 x v (cross product).\n30/// x1, x2 = center of mass for the bodies.\n31/// v = [v1, w1, v2, w2].\n32/// v1, v2 = linear velocity of body 1 and 2.\n33/// w1, w2 = angular velocity of body 1 and 2.\n34/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n35/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n36/// b = velocity bias.\n37/// \f$\beta\f$ = baumgarte constant.\n38/// E = identity matrix.39class PointConstraintPart40{41JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const42{43// Apply impulse if delta is not zero44if (inLambda != Vec3::sZero())45{46// Calculate velocity change due to constraint47//48// Impulse:49// P = J^T lambda50//51// Euler velocity integration:52// v' = v + M^-1 P53if (ioBody1.IsDynamic())54{55MotionProperties *mp1 = ioBody1.GetMotionProperties();56mp1->SubLinearVelocityStep(mp1->GetInverseMass() * inLambda);57mp1->SubAngularVelocityStep(mInvI1_R1X * inLambda);58}59if (ioBody2.IsDynamic())60{61MotionProperties *mp2 = ioBody2.GetMotionProperties();62mp2->AddLinearVelocityStep(mp2->GetInverseMass() * inLambda);63mp2->AddAngularVelocityStep(mInvI2_R2X * inLambda);64}65return true;66}6768return false;69}7071public:72/// Calculate properties used during the functions below73/// @param inBody1 The first body that this constraint is attached to74/// @param inBody2 The second body that this constraint is attached to75/// @param inRotation1 The 3x3 rotation matrix for body 1 (translation part is ignored)76/// @param inRotation2 The 3x3 rotation matrix for body 2 (translation part is ignored)77/// @param inR1 Local space vector from center of mass to constraint point for body 178/// @param inR2 Local space vector from center of mass to constraint point for body 279inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2)80{81// Positions where the point constraint acts on (middle point between center of masses) in world space82mR1 = inRotation1.Multiply3x3(inR1);83mR2 = inRotation2.Multiply3x3(inR2);8485// Calculate effective mass: K^-1 = (J M^-1 J^T)^-186// Using: I^-1 = R * Ibody^-1 * R^T87float summed_inv_mass;88Mat44 inv_effective_mass;89if (inBody1.IsDynamic())90{91const MotionProperties *mp1 = inBody1.GetMotionProperties();92Mat44 inv_i1 = mp1->GetInverseInertiaForRotation(inRotation1);93summed_inv_mass = mp1->GetInverseMass();9495Mat44 r1x = Mat44::sCrossProduct(mR1);96mInvI1_R1X = inv_i1.Multiply3x3(r1x);97inv_effective_mass = r1x.Multiply3x3(inv_i1).Multiply3x3RightTransposed(r1x);98}99else100{101JPH_IF_DEBUG(mInvI1_R1X = Mat44::sNaN();)102103summed_inv_mass = 0.0f;104inv_effective_mass = Mat44::sZero();105}106107if (inBody2.IsDynamic())108{109const MotionProperties *mp2 = inBody2.GetMotionProperties();110Mat44 inv_i2 = mp2->GetInverseInertiaForRotation(inRotation2);111summed_inv_mass += mp2->GetInverseMass();112113Mat44 r2x = Mat44::sCrossProduct(mR2);114mInvI2_R2X = inv_i2.Multiply3x3(r2x);115inv_effective_mass += r2x.Multiply3x3(inv_i2).Multiply3x3RightTransposed(r2x);116}117else118{119JPH_IF_DEBUG(mInvI2_R2X = Mat44::sNaN();)120}121122inv_effective_mass += Mat44::sScale(summed_inv_mass);123if (!mEffectiveMass.SetInversed3x3(inv_effective_mass))124Deactivate();125}126127/// Deactivate this constraint128inline void Deactivate()129{130mEffectiveMass = Mat44::sZero();131mTotalLambda = Vec3::sZero();132}133134/// Check if constraint is active135inline bool IsActive() const136{137return mEffectiveMass(3, 3) != 0.0f;138}139140/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses141/// @param ioBody1 The first body that this constraint is attached to142/// @param ioBody2 The second body that this constraint is attached to143/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame144inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)145{146mTotalLambda *= inWarmStartImpulseRatio;147ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);148}149150/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.151/// @param ioBody1 The first body that this constraint is attached to152/// @param ioBody2 The second body that this constraint is attached to153inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)154{155// Calculate lagrange multiplier:156//157// lambda = -K^-1 (J v + b)158Vec3 lambda = mEffectiveMass * (ioBody1.GetLinearVelocity() - mR1.Cross(ioBody1.GetAngularVelocity()) - ioBody2.GetLinearVelocity() + mR2.Cross(ioBody2.GetAngularVelocity()));159mTotalLambda += lambda; // Store accumulated lambda160return ApplyVelocityStep(ioBody1, ioBody2, lambda);161}162163/// Iteratively update the position constraint. Makes sure C(...) = 0.164/// @param ioBody1 The first body that this constraint is attached to165/// @param ioBody2 The second body that this constraint is attached to166/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)167inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const168{169Vec3 separation = (Vec3(ioBody2.GetCenterOfMassPosition() - ioBody1.GetCenterOfMassPosition()) + mR2 - mR1);170if (separation != Vec3::sZero())171{172// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:173//174// lambda = -K^-1 * beta / dt * C175//176// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out177Vec3 lambda = mEffectiveMass * -inBaumgarte * separation;178179// Directly integrate velocity change for one time step180//181// Euler velocity integration:182// dv = M^-1 P183//184// Impulse:185// P = J^T lambda186//187// Euler position integration:188// x' = x + dv * dt189//190// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and191// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte192// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity193// integrate + a position integrate and then discard the velocity change.194if (ioBody1.IsDynamic())195{196ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * lambda);197ioBody1.SubRotationStep(mInvI1_R1X * lambda);198}199if (ioBody2.IsDynamic())200{201ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * lambda);202ioBody2.AddRotationStep(mInvI2_R2X * lambda);203}204205return true;206}207208return false;209}210211/// Return lagrange multiplier212Vec3 GetTotalLambda() const213{214return mTotalLambda;215}216217/// Save state of this constraint part218void SaveState(StateRecorder &inStream) const219{220inStream.Write(mTotalLambda);221}222223/// Restore state of this constraint part224void RestoreState(StateRecorder &inStream)225{226inStream.Read(mTotalLambda);227}228229private:230Vec3 mR1;231Vec3 mR2;232Mat44 mInvI1_R1X;233Mat44 mInvI2_R2X;234Mat44 mEffectiveMass;235Vec3 mTotalLambda { Vec3::sZero() };236};237238JPH_NAMESPACE_END239240241