2
0

AxisConstraintPart.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. JPH_IF_DEBUG(else Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis);)
  80. Vec3 r2_x_axis;
  81. if constexpr (Type2 != EMotionType::Static)
  82. {
  83. r2_x_axis = inR2.Cross(inWorldSpaceAxis);
  84. r2_x_axis.StoreFloat3(&mR2xAxis);
  85. }
  86. JPH_IF_DEBUG(else Vec3::sNaN().StoreFloat3(&mR2xAxis);)
  87. // Calculate inverse effective mass: K = J M^-1 J^T
  88. float inv_effective_mass;
  89. if constexpr (Type1 == EMotionType::Dynamic)
  90. {
  91. Vec3 invi1_r1_plus_u_x_axis = inInvI1.Multiply3x3(r1_plus_u_x_axis);
  92. invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);
  93. inv_effective_mass = inMotionProperties1->GetInverseMass() + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);
  94. }
  95. else
  96. {
  97. (void)r1_plus_u_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  98. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)
  99. inv_effective_mass = 0.0f;
  100. }
  101. if constexpr (Type2 == EMotionType::Dynamic)
  102. {
  103. Vec3 invi2_r2_x_axis = inInvI2.Multiply3x3(r2_x_axis);
  104. invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);
  105. inv_effective_mass += inMotionProperties2->GetInverseMass() + invi2_r2_x_axis.Dot(r2_x_axis);
  106. }
  107. else
  108. {
  109. (void)r2_x_axis; // Fix compiler warning: Not using this (it's not calculated either)
  110. JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)
  111. }
  112. // Calculate effective mass and spring properties
  113. mSpringPart.CalculateSpringProperties(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  114. 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);
  115. }
  116. /// Calculate properties used during the functions below
  117. /// @param inDeltaTime Time step
  118. /// @param inBody1 The first body that this constraint is attached to
  119. /// @param inBody2 The second body that this constraint is attached to
  120. /// @param inR1PlusU See equations above (r1 + u)
  121. /// @param inR2 See equations above (r2)
  122. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)
  123. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  124. /// @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.
  125. /// @param inFrequency Oscillation frequency (Hz). Set to zero if you don't want to drive the constraint to zero with a spring.
  126. /// @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.
  127. 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)
  128. {
  129. // Dispatch to the correct templated form
  130. switch (inBody1.GetMotionType())
  131. {
  132. case EMotionType::Dynamic:
  133. {
  134. const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();
  135. Mat44 invi1 = inBody1.GetInverseInertia();
  136. switch (inBody2.GetMotionType())
  137. {
  138. case EMotionType::Dynamic:
  139. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(inDeltaTime, mp1, invi1, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  140. break;
  141. case EMotionType::Kinematic:
  142. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  143. break;
  144. case EMotionType::Static:
  145. TemplatedCalculateConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(inDeltaTime, mp1, invi1, inR1PlusU, nullptr, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  146. break;
  147. default:
  148. JPH_ASSERT(false);
  149. break;
  150. }
  151. break;
  152. }
  153. case EMotionType::Kinematic:
  154. JPH_ASSERT(inBody2.IsDynamic());
  155. TemplatedCalculateConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  156. break;
  157. case EMotionType::Static:
  158. JPH_ASSERT(inBody2.IsDynamic());
  159. TemplatedCalculateConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(inDeltaTime, nullptr, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis, inBias, inC, inFrequency, inDamping);
  160. break;
  161. default:
  162. JPH_ASSERT(false);
  163. break;
  164. }
  165. }
  166. /// Deactivate this constraint
  167. inline void Deactivate()
  168. {
  169. mEffectiveMass = 0.0f;
  170. mTotalLambda = 0.0f;
  171. }
  172. /// Check if constraint is active
  173. inline bool IsActive() const
  174. {
  175. return mEffectiveMass != 0.0f;
  176. }
  177. /// Templated form of WarmStart with the motion types baked in
  178. template <EMotionType Type1, EMotionType Type2>
  179. inline void TemplatedWarmStart(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  180. {
  181. mTotalLambda *= inWarmStartImpulseRatio;
  182. ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, mTotalLambda);
  183. }
  184. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  185. /// @param ioBody1 The first body that this constraint is attached to
  186. /// @param ioBody2 The second body that this constraint is attached to
  187. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  188. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  189. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)
  190. {
  191. EMotionType motion_type1 = ioBody1.GetMotionType();
  192. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  193. EMotionType motion_type2 = ioBody2.GetMotionType();
  194. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  195. // Dispatch to the correct templated form
  196. // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies
  197. if (motion_type1 == EMotionType::Dynamic)
  198. {
  199. if (motion_type2 == EMotionType::Dynamic)
  200. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  201. else
  202. TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  203. }
  204. else
  205. {
  206. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  207. TemplatedWarmStart<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inWarmStartImpulseRatio);
  208. }
  209. }
  210. /// Templated form of SolveVelocityConstraint with the motion types baked in
  211. template <EMotionType Type1, EMotionType Type2>
  212. inline bool TemplatedSolveVelocityConstraint(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  213. {
  214. // Calculate jacobian multiplied by linear velocity
  215. float jv;
  216. if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)
  217. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity() - ioMotionProperties2->GetLinearVelocity());
  218. else if constexpr (Type1 != EMotionType::Static)
  219. jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity());
  220. else if constexpr (Type2 != EMotionType::Static)
  221. jv = inWorldSpaceAxis.Dot(-ioMotionProperties2->GetLinearVelocity());
  222. else
  223. JPH_ASSERT(false); // Static vs static is nonsensical!
  224. // Calculate jacobian multiplied by angular velocity
  225. if constexpr (Type1 != EMotionType::Static)
  226. jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(ioMotionProperties1->GetAngularVelocity());
  227. if constexpr (Type2 != EMotionType::Static)
  228. jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(ioMotionProperties2->GetAngularVelocity());
  229. // Lagrange multiplier is:
  230. //
  231. // lambda = -K^-1 (J v + b)
  232. float lambda = mEffectiveMass * (jv - mSpringPart.GetBias(mTotalLambda));
  233. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  234. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  235. mTotalLambda = new_lambda; // Store accumulated impulse
  236. return ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis, lambda);
  237. }
  238. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  239. /// @param ioBody1 The first body that this constraint is attached to
  240. /// @param ioBody2 The second body that this constraint is attached to
  241. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  242. /// @param inMinLambda Minimum value of constraint impulse to apply (N s)
  243. /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)
  244. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  245. {
  246. EMotionType motion_type1 = ioBody1.GetMotionType();
  247. MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();
  248. EMotionType motion_type2 = ioBody2.GetMotionType();
  249. MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();
  250. // Dispatch to the correct templated form
  251. switch (motion_type1)
  252. {
  253. case EMotionType::Dynamic:
  254. switch (motion_type2)
  255. {
  256. case EMotionType::Dynamic:
  257. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  258. case EMotionType::Kinematic:
  259. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  260. case EMotionType::Static:
  261. return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  262. default:
  263. JPH_ASSERT(false);
  264. break;
  265. }
  266. break;
  267. case EMotionType::Kinematic:
  268. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  269. return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  270. case EMotionType::Static:
  271. JPH_ASSERT(motion_type2 == EMotionType::Dynamic);
  272. return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, motion_properties2, inWorldSpaceAxis, inMinLambda, inMaxLambda);
  273. default:
  274. JPH_ASSERT(false);
  275. break;
  276. }
  277. return false;
  278. }
  279. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  280. /// @param ioBody1 The first body that this constraint is attached to
  281. /// @param ioBody2 The second body that this constraint is attached to
  282. /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)
  283. /// @param inC Value of the constraint equation (C)
  284. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  285. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const
  286. {
  287. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  288. if (inC != 0.0f && !mSpringPart.IsActive())
  289. {
  290. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  291. //
  292. // lambda = -K^-1 * beta / dt * C
  293. //
  294. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  295. float lambda = -mEffectiveMass * inBaumgarte * inC;
  296. // Directly integrate velocity change for one time step
  297. //
  298. // Euler velocity integration:
  299. // dv = M^-1 P
  300. //
  301. // Impulse:
  302. // P = J^T lambda
  303. //
  304. // Euler position integration:
  305. // x' = x + dv * dt
  306. //
  307. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  308. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  309. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  310. // integrate + a position integrate and then discard the velocity change.
  311. if (ioBody1.IsDynamic())
  312. {
  313. ioBody1.SubPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  314. ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));
  315. }
  316. if (ioBody2.IsDynamic())
  317. {
  318. ioBody2.AddPositionStep((lambda * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inWorldSpaceAxis);
  319. ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));
  320. }
  321. return true;
  322. }
  323. return false;
  324. }
  325. /// Override total lagrange multiplier, can be used to set the initial value for warm starting
  326. inline void SetTotalLambda(float inLambda)
  327. {
  328. mTotalLambda = inLambda;
  329. }
  330. /// Return lagrange multiplier
  331. inline float GetTotalLambda() const
  332. {
  333. return mTotalLambda;
  334. }
  335. /// Save state of this constraint part
  336. void SaveState(StateRecorder &inStream) const
  337. {
  338. inStream.Write(mTotalLambda);
  339. }
  340. /// Restore state of this constraint part
  341. void RestoreState(StateRecorder &inStream)
  342. {
  343. inStream.Read(mTotalLambda);
  344. }
  345. private:
  346. Float3 mR1PlusUxAxis;
  347. Float3 mR2xAxis;
  348. Float3 mInvI1_R1PlusUxAxis;
  349. Float3 mInvI2_R2xAxis;
  350. float mEffectiveMass = 0.0f;
  351. SpringPart mSpringPart;
  352. float mTotalLambda = 0.0f;
  353. };
  354. JPH_NAMESPACE_END