Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.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/Constraints/ConstraintPart/SpringPart.h>8#include <Jolt/Physics/Constraints/SpringSettings.h>9#include <Jolt/Physics/StateRecorder.h>10#include <Jolt/Physics/DeterminismLog.h>1112JPH_NAMESPACE_BEGIN1314/// Constraint that constrains motion along 1 axis15///16/// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.1.117/// (we're not using the approximation of eq 27 but instead add the U term as in eq 55)18///19/// Constraint equation (eq 25):20///21/// \f[C = (p_2 - p_1) \cdot n\f]22///23/// Jacobian (eq 28):24///25/// \f[J = \begin{bmatrix} -n^T & (-(r_1 + u) \times n)^T & n^T & (r_2 \times n)^T \end{bmatrix}\f]26///27/// Used terms (here and below, everything in world space):\n28/// n = constraint axis (normalized).\n29/// p1, p2 = constraint points.\n30/// r1 = p1 - x1.\n31/// r2 = p2 - x2.\n32/// u = x2 + r2 - x1 - r1 = p2 - p1.\n33/// x1, x2 = center of mass for the bodies.\n34/// v = [v1, w1, v2, w2].\n35/// v1, v2 = linear velocity of body 1 and 2.\n36/// w1, w2 = angular velocity of body 1 and 2.\n37/// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n38/// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n39/// b = velocity bias.\n40/// \f$\beta\f$ = baumgarte constant.41class AxisConstraintPart42{43/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated44template <EMotionType Type1, EMotionType Type2>45JPH_INLINE bool ApplyVelocityStep(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inLambda) const46{47// Apply impulse if delta is not zero48if (inLambda != 0.0f)49{50// Calculate velocity change due to constraint51//52// Impulse:53// P = J^T lambda54//55// Euler velocity integration:56// v' = v + M^-1 P57if constexpr (Type1 == EMotionType::Dynamic)58{59ioMotionProperties1->SubLinearVelocityStep((inLambda * inInvMass1) * inWorldSpaceAxis);60ioMotionProperties1->SubAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));61}62if constexpr (Type2 == EMotionType::Dynamic)63{64ioMotionProperties2->AddLinearVelocityStep((inLambda * inInvMass2) * inWorldSpaceAxis);65ioMotionProperties2->AddAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));66}67return true;68}6970return false;71}7273/// Internal helper function to calculate the inverse effective mass74template <EMotionType Type1, EMotionType Type2>75JPH_INLINE float TemplatedCalculateInverseEffectiveMass(float inInvMass1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, float inInvMass2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)76{77JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-5f));7879// Calculate properties used below80Vec3 r1_plus_u_x_axis;81if constexpr (Type1 != EMotionType::Static)82{83r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);84r1_plus_u_x_axis.StoreFloat3(&mR1PlusUxAxis);85}86else87{88#ifdef JPH_DEBUG89Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis);90#endif91}9293Vec3 r2_x_axis;94if constexpr (Type2 != EMotionType::Static)95{96r2_x_axis = inR2.Cross(inWorldSpaceAxis);97r2_x_axis.StoreFloat3(&mR2xAxis);98}99else100{101#ifdef JPH_DEBUG102Vec3::sNaN().StoreFloat3(&mR2xAxis);103#endif104}105106// Calculate inverse effective mass: K = J M^-1 J^T107float inv_effective_mass;108109if constexpr (Type1 == EMotionType::Dynamic)110{111Vec3 invi1_r1_plus_u_x_axis = inInvI1.Multiply3x3(r1_plus_u_x_axis);112invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);113inv_effective_mass = inInvMass1 + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);114}115else116{117(void)r1_plus_u_x_axis; // Fix compiler warning: Not using this (it's not calculated either)118JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)119inv_effective_mass = 0.0f;120}121122if constexpr (Type2 == EMotionType::Dynamic)123{124Vec3 invi2_r2_x_axis = inInvI2.Multiply3x3(r2_x_axis);125invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);126inv_effective_mass += inInvMass2 + invi2_r2_x_axis.Dot(r2_x_axis);127}128else129{130(void)r2_x_axis; // Fix compiler warning: Not using this (it's not calculated either)131JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)132}133134return inv_effective_mass;135}136137/// Internal helper function to calculate the inverse effective mass138JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)139{140// Dispatch to the correct templated form141switch (inBody1.GetMotionType())142{143case EMotionType::Dynamic:144{145const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();146float inv_m1 = mp1->GetInverseMass();147Mat44 inv_i1 = inBody1.GetInverseInertia();148switch (inBody2.GetMotionType())149{150case EMotionType::Dynamic:151return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Dynamic>(inv_m1, inv_i1, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);152153case EMotionType::Kinematic:154return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Kinematic>(inv_m1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);155156case EMotionType::Static:157return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Static>(inv_m1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);158159default:160break;161}162break;163}164165case EMotionType::Kinematic:166JPH_ASSERT(inBody2.IsDynamic());167return TemplatedCalculateInverseEffectiveMass<EMotionType::Kinematic, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);168169case EMotionType::Static:170JPH_ASSERT(inBody2.IsDynamic());171return TemplatedCalculateInverseEffectiveMass<EMotionType::Static, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);172173default:174break;175}176177JPH_ASSERT(false);178return 0.0f;179}180181/// Internal helper function to calculate the inverse effective mass, version that supports mass scaling182JPH_INLINE float CalculateInverseEffectiveMassWithMassOverride(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, Vec3Arg inR1PlusU, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)183{184// Dispatch to the correct templated form185switch (inBody1.GetMotionType())186{187case EMotionType::Dynamic:188{189Mat44 inv_i1 = inInvInertiaScale1 * inBody1.GetInverseInertia();190switch (inBody2.GetMotionType())191{192case EMotionType::Dynamic:193return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Dynamic>(inInvMass1, inv_i1, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);194195case EMotionType::Kinematic:196return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Kinematic>(inInvMass1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);197198case EMotionType::Static:199return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Static>(inInvMass1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);200201default:202break;203}204break;205}206207case EMotionType::Kinematic:208JPH_ASSERT(inBody2.IsDynamic());209return TemplatedCalculateInverseEffectiveMass<EMotionType::Kinematic, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);210211case EMotionType::Static:212JPH_ASSERT(inBody2.IsDynamic());213return TemplatedCalculateInverseEffectiveMass<EMotionType::Static, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);214215default:216break;217}218219JPH_ASSERT(false);220return 0.0f;221}222223public:224/// Templated form of CalculateConstraintProperties with the motion types baked in225template <EMotionType Type1, EMotionType Type2>226JPH_INLINE void TemplatedCalculateConstraintProperties(float inInvMass1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, float inInvMass2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)227{228float inv_effective_mass = TemplatedCalculateInverseEffectiveMass<Type1, Type2>(inInvMass1, inInvI1, inR1PlusU, inInvMass2, inInvI2, inR2, inWorldSpaceAxis);229230if (inv_effective_mass == 0.0f)231Deactivate();232else233{234mEffectiveMass = 1.0f / inv_effective_mass;235mSpringPart.CalculateSpringPropertiesWithBias(inBias);236}237238JPH_DET_LOG("TemplatedCalculateConstraintProperties: invM1: " << inInvMass1 << " invI1: " << inInvI1 << " r1PlusU: " << inR1PlusU << " invM2: " << inInvMass2 << " invI2: " << inInvI2 << " r2: " << inR2 << " bias: " << inBias << " r1PlusUxAxis: " << mR1PlusUxAxis << " r2xAxis: " << mR2xAxis << " invI1_R1PlusUxAxis: " << mInvI1_R1PlusUxAxis << " invI2_R2xAxis: " << mInvI2_R2xAxis << " effectiveMass: " << mEffectiveMass << " totalLambda: " << mTotalLambda);239}240241/// Calculate properties used during the functions below242/// @param inBody1 The first body that this constraint is attached to243/// @param inBody2 The second body that this constraint is attached to244/// @param inR1PlusU See equations above (r1 + u)245/// @param inR2 See equations above (r2)246/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)247/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b248inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)249{250float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);251252if (inv_effective_mass == 0.0f)253Deactivate();254else255{256mEffectiveMass = 1.0f / inv_effective_mass;257mSpringPart.CalculateSpringPropertiesWithBias(inBias);258}259}260261/// Calculate properties used during the functions below, version that supports mass scaling262/// @param inBody1 The first body that this constraint is attached to263/// @param inBody2 The second body that this constraint is attached to264/// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)265/// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)266/// @param inInvInertiaScale1 Scale factor for the inverse inertia of body 1267/// @param inInvInertiaScale2 Scale factor for the inverse inertia of body 2268/// @param inR1PlusU See equations above (r1 + u)269/// @param inR2 See equations above (r2)270/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)271/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b272inline void CalculateConstraintPropertiesWithMassOverride(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, Vec3Arg inR1PlusU, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)273{274float inv_effective_mass = CalculateInverseEffectiveMassWithMassOverride(inBody1, inInvMass1, inInvInertiaScale1, inR1PlusU, inBody2, inInvMass2, inInvInertiaScale2, inR2, inWorldSpaceAxis);275276if (inv_effective_mass == 0.0f)277Deactivate();278else279{280mEffectiveMass = 1.0f / inv_effective_mass;281mSpringPart.CalculateSpringPropertiesWithBias(inBias);282}283}284285/// Calculate properties used during the functions below286/// @param inDeltaTime Time step287/// @param inBody1 The first body that this constraint is attached to288/// @param inBody2 The second body that this constraint is attached to289/// @param inR1PlusU See equations above (r1 + u)290/// @param inR2 See equations above (r2)291/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)292/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b293/// @param inC Value of the constraint equation (C).294/// @param inFrequency Oscillation frequency (Hz).295/// @param inDamping Damping factor (0 = no damping, 1 = critical damping).296inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping)297{298float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);299300if (inv_effective_mass == 0.0f)301Deactivate();302else303mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);304}305306/// Calculate properties used during the functions below307/// @param inDeltaTime Time step308/// @param inBody1 The first body that this constraint is attached to309/// @param inBody2 The second body that this constraint is attached to310/// @param inR1PlusU See equations above (r1 + u)311/// @param inR2 See equations above (r2)312/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)313/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b314/// @param inC Value of the constraint equation (C).315/// @param inStiffness Spring stiffness k.316/// @param inDamping Spring damping coefficient c.317inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping)318{319float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);320321if (inv_effective_mass == 0.0f)322Deactivate();323else324mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);325}326327/// Selects one of the above functions based on the spring settings328inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)329{330float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);331332if (inv_effective_mass == 0.0f)333Deactivate();334else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)335mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);336else337mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);338}339340/// Deactivate this constraint341inline void Deactivate()342{343mEffectiveMass = 0.0f;344mTotalLambda = 0.0f;345}346347/// Check if constraint is active348inline bool IsActive() const349{350return mEffectiveMass != 0.0f;351}352353/// Templated form of WarmStart with the motion types baked in354template <EMotionType Type1, EMotionType Type2>355inline void TemplatedWarmStart(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)356{357mTotalLambda *= inWarmStartImpulseRatio;358359ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, mTotalLambda);360}361362/// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses363/// @param ioBody1 The first body that this constraint is attached to364/// @param ioBody2 The second body that this constraint is attached to365/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)366/// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame367inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)368{369EMotionType motion_type1 = ioBody1.GetMotionType();370MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();371372EMotionType motion_type2 = ioBody2.GetMotionType();373MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();374375// Dispatch to the correct templated form376// Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies377if (motion_type1 == EMotionType::Dynamic)378{379if (motion_type2 == EMotionType::Dynamic)380TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inWarmStartImpulseRatio);381else382TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inWarmStartImpulseRatio);383}384else385{386JPH_ASSERT(motion_type2 == EMotionType::Dynamic);387TemplatedWarmStart<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inWarmStartImpulseRatio);388}389}390391/// Templated form of SolveVelocityConstraint with the motion types baked in, part 1: get the total lambda392template <EMotionType Type1, EMotionType Type2>393JPH_INLINE float TemplatedSolveVelocityConstraintGetTotalLambda(const MotionProperties *ioMotionProperties1, const MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis) const394{395// Calculate jacobian multiplied by linear velocity396float jv;397if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)398jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity() - ioMotionProperties2->GetLinearVelocity());399else if constexpr (Type1 != EMotionType::Static)400jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity());401else if constexpr (Type2 != EMotionType::Static)402jv = inWorldSpaceAxis.Dot(-ioMotionProperties2->GetLinearVelocity());403else404JPH_ASSERT(false); // Static vs static is nonsensical!405406// Calculate jacobian multiplied by angular velocity407if constexpr (Type1 != EMotionType::Static)408jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(ioMotionProperties1->GetAngularVelocity());409if constexpr (Type2 != EMotionType::Static)410jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(ioMotionProperties2->GetAngularVelocity());411412// Lagrange multiplier is:413//414// lambda = -K^-1 (J v + b)415float lambda = mEffectiveMass * (jv - mSpringPart.GetBias(mTotalLambda));416417// Return the total accumulated lambda418return mTotalLambda + lambda;419}420421/// Templated form of SolveVelocityConstraint with the motion types baked in, part 2: apply new lambda422template <EMotionType Type1, EMotionType Type2>423JPH_INLINE bool TemplatedSolveVelocityConstraintApplyLambda(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inTotalLambda)424{425float delta_lambda = inTotalLambda - mTotalLambda; // Calculate change in lambda426mTotalLambda = inTotalLambda; // Store accumulated impulse427428return ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, delta_lambda);429}430431/// Templated form of SolveVelocityConstraint with the motion types baked in432template <EMotionType Type1, EMotionType Type2>433inline bool TemplatedSolveVelocityConstraint(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)434{435float total_lambda = TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis);436437// Clamp impulse to specified range438total_lambda = Clamp(total_lambda, inMinLambda, inMaxLambda);439440return TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, total_lambda);441}442443/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.444/// @param ioBody1 The first body that this constraint is attached to445/// @param ioBody2 The second body that this constraint is attached to446/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)447/// @param inMinLambda Minimum value of constraint impulse to apply (N s)448/// @param inMaxLambda Maximum value of constraint impulse to apply (N s)449inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)450{451EMotionType motion_type1 = ioBody1.GetMotionType();452MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();453454EMotionType motion_type2 = ioBody2.GetMotionType();455MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();456457// Dispatch to the correct templated form458switch (motion_type1)459{460case EMotionType::Dynamic:461switch (motion_type2)462{463case EMotionType::Dynamic:464return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);465466case EMotionType::Kinematic:467return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);468469case EMotionType::Static:470return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);471472default:473JPH_ASSERT(false);474break;475}476break;477478case EMotionType::Kinematic:479JPH_ASSERT(motion_type2 == EMotionType::Dynamic);480return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);481482case EMotionType::Static:483JPH_ASSERT(motion_type2 == EMotionType::Dynamic);484return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);485486default:487JPH_ASSERT(false);488break;489}490491return false;492}493494/// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.495/// @param ioBody1 The first body that this constraint is attached to496/// @param ioBody2 The second body that this constraint is attached to497/// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)498/// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)499/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)500/// @param inMinLambda Minimum value of constraint impulse to apply (N s)501/// @param inMaxLambda Maximum value of constraint impulse to apply (N s)502inline bool SolveVelocityConstraintWithMassOverride(Body &ioBody1, float inInvMass1, Body &ioBody2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)503{504EMotionType motion_type1 = ioBody1.GetMotionType();505MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();506507EMotionType motion_type2 = ioBody2.GetMotionType();508MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();509510// Dispatch to the correct templated form511switch (motion_type1)512{513case EMotionType::Dynamic:514switch (motion_type2)515{516case EMotionType::Dynamic:517return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, inInvMass1, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);518519case EMotionType::Kinematic:520return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, inInvMass1, motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);521522case EMotionType::Static:523return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, inInvMass1, motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);524525default:526JPH_ASSERT(false);527break;528}529break;530531case EMotionType::Kinematic:532JPH_ASSERT(motion_type2 == EMotionType::Dynamic);533return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);534535case EMotionType::Static:536JPH_ASSERT(motion_type2 == EMotionType::Dynamic);537return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);538539default:540JPH_ASSERT(false);541break;542}543544return false;545}546547/// Iteratively update the position constraint. Makes sure C(...) = 0.548/// @param ioBody1 The first body that this constraint is attached to549/// @param ioBody2 The second body that this constraint is attached to550/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)551/// @param inC Value of the constraint equation (C)552/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)553inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const554{555// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint556if (inC != 0.0f && !mSpringPart.IsActive())557{558// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:559//560// lambda = -K^-1 * beta / dt * C561//562// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out563float lambda = -mEffectiveMass * inBaumgarte * inC;564565// Directly integrate velocity change for one time step566//567// Euler velocity integration:568// dv = M^-1 P569//570// Impulse:571// P = J^T lambda572//573// Euler position integration:574// x' = x + dv * dt575//576// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and577// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte578// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity579// integrate + a position integrate and then discard the velocity change.580if (ioBody1.IsDynamic())581{582ioBody1.SubPositionStep((lambda * ioBody1.GetMotionProperties()->GetInverseMass()) * inWorldSpaceAxis);583ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));584}585if (ioBody2.IsDynamic())586{587ioBody2.AddPositionStep((lambda * ioBody2.GetMotionProperties()->GetInverseMass()) * inWorldSpaceAxis);588ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));589}590return true;591}592593return false;594}595596/// Iteratively update the position constraint. Makes sure C(...) = 0.597/// @param ioBody1 The first body that this constraint is attached to598/// @param ioBody2 The second body that this constraint is attached to599/// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)600/// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)601/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)602/// @param inC Value of the constraint equation (C)603/// @param inBaumgarte Baumgarte constant (fraction of the error to correct)604inline bool SolvePositionConstraintWithMassOverride(Body &ioBody1, float inInvMass1, Body &ioBody2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const605{606// Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint607if (inC != 0.0f && !mSpringPart.IsActive())608{609// Calculate lagrange multiplier (lambda) for Baumgarte stabilization:610//611// lambda = -K^-1 * beta / dt * C612//613// We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out614float lambda = -mEffectiveMass * inBaumgarte * inC;615616// Directly integrate velocity change for one time step617//618// Euler velocity integration:619// dv = M^-1 P620//621// Impulse:622// P = J^T lambda623//624// Euler position integration:625// x' = x + dv * dt626//627// Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and628// Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte629// stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity630// integrate + a position integrate and then discard the velocity change.631if (ioBody1.IsDynamic())632{633ioBody1.SubPositionStep((lambda * inInvMass1) * inWorldSpaceAxis);634ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));635}636if (ioBody2.IsDynamic())637{638ioBody2.AddPositionStep((lambda * inInvMass2) * inWorldSpaceAxis);639ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));640}641return true;642}643644return false;645}646647/// Override total lagrange multiplier, can be used to set the initial value for warm starting648inline void SetTotalLambda(float inLambda)649{650mTotalLambda = inLambda;651}652653/// Return lagrange multiplier654inline float GetTotalLambda() const655{656return mTotalLambda;657}658659/// Save state of this constraint part660void SaveState(StateRecorder &inStream) const661{662inStream.Write(mTotalLambda);663}664665/// Restore state of this constraint part666void RestoreState(StateRecorder &inStream)667{668inStream.Read(mTotalLambda);669}670671private:672Float3 mR1PlusUxAxis;673Float3 mR2xAxis;674Float3 mInvI1_R1PlusUxAxis;675Float3 mInvI2_R2xAxis;676float mEffectiveMass = 0.0f;677SpringPart mSpringPart;678float mTotalLambda = 0.0f;679};680681JPH_NAMESPACE_END682683684