AxisConstraintPart.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Body/Body.h>
  5. #include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. #include <Jolt/Physics/DeterminismLog.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// Constraint that constrains motion along 1 axis
  10. ///
  11. /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.1.1
  12. /// (we're not using the approximation of eq 27 but instead add the U term as in eq 55)
  13. ///
  14. /// Constraint equation (eq 25):
  15. ///
  16. /// \f[C = (p_2 - p_1) \cdot n\f]
  17. ///
  18. /// Jacobian (eq 28):
  19. ///
  20. /// \f[J = \begin{bmatrix} -n^T & (-(r_1 + u) \times n)^T & n^T & (r_2 \times n)^T \end{bmatrix}\f]
  21. ///
  22. /// Used terms (here and below, everything in world space):\n
  23. /// n = constraint axis (normalized).\n
  24. /// p1, p2 = constraint points.\n
  25. /// r1 = p1 - x1.\n
  26. /// r2 = p2 - x2.\n
  27. /// u = x2 + r2 - x1 - r1 = p2 - p1.\n
  28. /// x1, x2 = center of mass for the bodies.\n
  29. /// v = [v1, w1, v2, w2].\n
  30. /// v1, v2 = linear velocity of body 1 and 2.\n
  31. /// w1, w2 = angular velocity of body 1 and 2.\n
  32. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  33. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  34. /// b = velocity bias.\n
  35. /// \f$\beta\f$ = baumgarte constant.
  36. class AxisConstraintPart
  37. {
  38. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  39. template <EMotionType Type1, EMotionType Type2>
  40. JPH_INLINE bool ApplyVelocityStep(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inLambda) const
  41. {
  42. // Apply impulse if delta is not zero
  43. if (inLambda != 0.0f)
  44. {
  45. // Calculate velocity change due to constraint
  46. //
  47. // Impulse:
  48. // P = J^T lambda
  49. //
  50. // Euler velocity integration:
  51. // v' = v + M^-1 P
  52. if constexpr (Type1 == EMotionType::Dynamic)
  53. {
  54. ioMotionProperties1->SubLinearVelocityStep((inLambda * ioMotionProperties1->GetInverseMass()) * inWorldSpaceAxis);
  55. ioMotionProperties1->SubAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));
  56. }
  57. if constexpr (Type2 == EMotionType::Dynamic)
  58. {
  59. ioMotionProperties2->AddLinearVelocityStep((inLambda * ioMotionProperties2->GetInverseMass()) * inWorldSpaceAxis);
  60. ioMotionProperties2->AddAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));
  61. }
  62. return true;
  63. }
  64. return false;
  65. }
  66. public:
  67. /// Templated form of CalculateConstraintProperties with the motion types baked in
  68. template <EMotionType Type1, EMotionType Type2>
  69. JPH_INLINE void TemplatedCalculateConstraintProperties(float inDeltaTime, const MotionProperties *inMotionProperties1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, const MotionProperties *inMotionProperties2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f, float inC = 0.0f, float inFrequency = 0.0f, float inDamping = 0.0f)
  70. {
  71. JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-5f));
  72. // Calculate properties used below
  73. Vec3 r1_plus_u_x_axis;
  74. if constexpr (Type1 != EMotionType::Static)
  75. {
  76. r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);
  77. r1_plus_u_x_axis.StoreFloat3(&mR1PlusUxAxis);
  78. }
  79. else
  80. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis));
  81. Vec3 r2_x_axis;
  82. if constexpr (Type2 != EMotionType::Static)
  83. {
  84. r2_x_axis = inR2.Cross(inWorldSpaceAxis);
  85. r2_x_axis.StoreFloat3(&mR2xAxis);
  86. }
  87. else
  88. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR2xAxis));
  89. // Calculate inverse effective mass: K = J M^-1 J^T
  90. float inv_effective_mass;
  91. if constexpr (Type1 == EMotionType::Dynamic)
  92. {
  93. Vec3 invi1_r1_plus_u_x_axis = inInvI1 * r1_plus_u_x_axis;
  94. invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);
  95. inv_effective_mass = inMotionProperties1->GetInverseMass() + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);
  96. }
  97. else
  98. {
  99. (void)r1_plus_u_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  100. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)
  101. inv_effective_mass = 0.0f;
  102. }
  103. if constexpr (Type2 == EMotionType::Dynamic)
  104. {
  105. Vec3 invi2_r2_x_axis = inInvI2 * r2_x_axis;
  106. invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);
  107. inv_effective_mass += inMotionProperties2->GetInverseMass() + invi2_r2_x_axis.Dot(r2_x_axis);
  108. }
  109. else
  110. {
  111. (void)r2_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  112. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)
  113. }
  114. // Calculate effective mass and spring properties
  115. mSpringPart.CalculateSpringProperties(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  116. JPH_DET_LOG("TemplatedCalculateConstraintProperties: dt: " << inDeltaTime << " invI1: " << inInvI1 << " r1PlusU: " << inR1PlusU << " invI2: " << inInvI2 << " r2: " << inR2 << " bias: " << inBias << ", c: " << inC << ", frequency: " << inFrequency << ", damping: " << inDamping << " r1PlusUxAxis: " << mR1PlusUxAxis << " r2xAxis: " << mR2xAxis << " invI1_R1PlusUxAxis: " << mInvI1_R1PlusUxAxis << " invI2_R2xAxis: " << mInvI2_R2xAxis << " effectiveMass: " << mEffectiveMass << " totalLambda: " << mTotalLambda);
  117. }
  118. /// Calculate properties used during the functions below
  119. /// @param inDeltaTime Time step
  120. /// @param inBody1 The first body that this constraint is attached to
  121. /// @param inBody2 The second body that this constraint is attached to
  122. /// @param inR1PlusU See equations above (r1 + u)
  123. /// @param inR2 See equations above (r2)
  124. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)
  125. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  126. /// @param inC Value of the constraint equation (C). Set to zero if you don't want to drive the constraint to zero with a spring.
  127. /// @param inFrequency Oscillation frequency (Hz). Set to zero if you don't want to drive the constraint to zero with a spring.
  128. /// @param inDamping Damping factor (0 = no damping, 1 = critical damping). Set to zero if you don't want to drive the constraint to zero with a spring.
  129. inline void CalculateConstraintProperties(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f, float inC = 0.0f, float inFrequency = 0.0f, float inDamping = 0.0f)
  130. {
  131. // Dispatch to the correct templated form
  132. switch (inBody1.GetMotionType())
  133. {
  134. case EMotionType::Dynamic:
  135. {
  136. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  137. Mat44 invi1 = inBody1.GetInverseInertia();
  138. switch (inBody2.GetMotionType())
  139. {
  140. case EMotionType::Dynamic:
  141. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(inDeltaTime, mp1, invi1, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  142. break;
  143. case EMotionType::Kinematic:
  144. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  145. break;
  146. case EMotionType::Static:
  147. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  148. break;
  149. default:
  150. JPH_ASSERT(false);
  151. break;
  152. }
  153. break;
  154. }
  155. case EMotionType::Kinematic:
  156. JPH_ASSERT(inBody2.IsDynamic());
  157. TemplatedCalculateConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  158. break;
  159. case EMotionType::Static:
  160. JPH_ASSERT(inBody2.IsDynamic());
  161. TemplatedCalculateConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  162. break;
  163. default:
  164. JPH_ASSERT(false);
  165. break;
  166. }
  167. }
  168. /// Deactivate this constraint
  169. inline void Deactivate()
  170. {
  171. mEffectiveMass = 0.0f;
  172. mTotalLambda = 0.0f;
  173. }
  174. /// Check if constraint is active
  175. inline bool IsActive() const
  176. {
  177. return mEffectiveMass != 0.0f;
  178. }
  179. /// Templated form of WarmStart with the motion types baked in
  180. template <EMotionType Type1, EMotionType Type2>
  181. inline void TemplatedWarmStart(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  182. {
  183. mTotalLambda *= inWarmStartImpulseRatio;
  184. ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, mTotalLambda);
  185. }
  186. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  187. /// @param ioBody1 The first body that this constraint is attached to
  188. /// @param ioBody2 The second body that this constraint is attached to
  189. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  190. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  191. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  192. {
  193. EMotionType motion_type1 = ioBody1.GetMotionType();
  194. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  195. EMotionType motion_type2 = ioBody2.GetMotionType();
  196. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  197. // Dispatch to the correct templated form
  198. // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies
  199. if (motion_type1 == EMotionType::Dynamic)
  200. {
  201. if (motion_type2 == EMotionType::Dynamic)
  202. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  203. else
  204. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  205. }
  206. else
  207. {
  208. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  209. TemplatedWarmStart<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  210. }
  211. }
  212. /// Templated form of SolveVelocityConstraint with the motion types baked in
  213. template <EMotionType Type1, EMotionType Type2>
  214. inline bool TemplatedSolveVelocityConstraint(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  215. {
  216. // Calculate jacobian multiplied by linear velocity
  217. float jv;
  218. if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)
  219. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity() - ioMotionProperties2->GetLinearVelocity());
  220. else if constexpr (Type1 != EMotionType::Static)
  221. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity());
  222. else if constexpr (Type2 != EMotionType::Static)
  223. jv = inWorldSpaceAxis.Dot(-ioMotionProperties2->GetLinearVelocity());
  224. else
  225. JPH_ASSERT(false); // Static vs static is nonsensical!
  226. // Calculate jacobian multiplied by angular velocity
  227. if constexpr (Type1 != EMotionType::Static)
  228. jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(ioMotionProperties1->GetAngularVelocity());
  229. if constexpr (Type2 != EMotionType::Static)
  230. jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(ioMotionProperties2->GetAngularVelocity());
  231. // Lagrange multiplier is:
  232. //
  233. // lambda = -K^-1 (J v + b)
  234. float lambda = mEffectiveMass * (jv - mSpringPart.GetBias(mTotalLambda));
  235. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  236. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  237. mTotalLambda = new_lambda; // Store accumulated impulse
  238. return ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, lambda);
  239. }
  240. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  241. /// @param ioBody1 The first body that this constraint is attached to
  242. /// @param ioBody2 The second body that this constraint is attached to
  243. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  244. /// @param inMinLambda Minimum value of constraint impulse to apply (N s)
  245. /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)
  246. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  247. {
  248. EMotionType motion_type1 = ioBody1.GetMotionType();
  249. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  250. EMotionType motion_type2 = ioBody2.GetMotionType();
  251. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  252. // Dispatch to the correct templated form
  253. switch (motion_type1)
  254. {
  255. case EMotionType::Dynamic:
  256. switch (motion_type2)
  257. {
  258. case EMotionType::Dynamic:
  259. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  260. case EMotionType::Kinematic:
  261. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  262. case EMotionType::Static:
  263. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  264. default:
  265. JPH_ASSERT(false);
  266. break;
  267. }
  268. break;
  269. case EMotionType::Kinematic:
  270. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  271. return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  272. case EMotionType::Static:
  273. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  274. return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  275. default:
  276. JPH_ASSERT(false);
  277. break;
  278. }
  279. return false;
  280. }
  281. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  282. /// @param ioBody1 The first body that this constraint is attached to
  283. /// @param ioBody2 The second body that this constraint is attached to
  284. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  285. /// @param inC Value of the constraint equation (C)
  286. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  287. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const
  288. {
  289. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  290. if (inC != 0.0f && !mSpringPart.IsActive())
  291. {
  292. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  293. //
  294. // lambda = -K^-1 * beta / dt * C
  295. //
  296. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  297. float lambda = -mEffectiveMass * inBaumgarte * inC;
  298. // Directly integrate velocity change for one time step
  299. //
  300. // Euler velocity integration:
  301. // dv = M^-1 P
  302. //
  303. // Impulse:
  304. // P = J^T lambda
  305. //
  306. // Euler position integration:
  307. // x' = x + dv * dt
  308. //
  309. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  310. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  311. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  312. // integrate + a position integrate and then discard the velocity change.
  313. if (ioBody1.IsDynamic())
  314. {
  315. ioBody1.SubPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  316. ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));
  317. }
  318. if (ioBody2.IsDynamic())
  319. {
  320. ioBody2.AddPositionStep((lambda * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  321. ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));
  322. }
  323. return true;
  324. }
  325. return false;
  326. }
  327. /// Override total lagrange multiplier, can be used to set the initial value for warm starting
  328. inline void SetTotalLambda(float inLambda)
  329. {
  330. mTotalLambda = inLambda;
  331. }
  332. /// Return lagrange multiplier
  333. inline float GetTotalLambda() const
  334. {
  335. return mTotalLambda;
  336. }
  337. /// Save state of this constraint part
  338. void SaveState(StateRecorder &inStream) const
  339. {
  340. inStream.Write(mTotalLambda);
  341. }
  342. /// Restore state of this constraint part
  343. void RestoreState(StateRecorder &inStream)
  344. {
  345. inStream.Read(mTotalLambda);
  346. }
  347. private:
  348. Float3 mR1PlusUxAxis;
  349. Float3 mR2xAxis;
  350. Float3 mInvI1_R1PlusUxAxis;
  351. Float3 mInvI2_R2xAxis;
  352. float mEffectiveMass = 0.0f;
  353. SpringPart mSpringPart;
  354. float mTotalLambda = 0.0f;
  355. };
  356. JPH_NAMESPACE_END