RackAndPinionConstraintPart.h 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constraint that constrains a rotation to a translation
  9. ///
  10. /// Constraint equation:
  11. ///
  12. /// C = Theta(t) - r d(t)
  13. ///
  14. /// Derivative:
  15. ///
  16. /// d/dt C = 0
  17. /// <=> w1 . a - r v2 . b = 0
  18. ///
  19. /// Jacobian:
  20. ///
  21. /// \f[J = \begin{bmatrix}0 & a^T & -r b^T & 0\end{bmatrix}\f]
  22. ///
  23. /// Used terms (here and below, everything in world space):\n
  24. /// a = axis around which body 1 rotates (normalized).\n
  25. /// b = axis along which body 2 slides (normalized).\n
  26. /// Theta(t) = rotation around a of body 1.\n
  27. /// d(t) = distance body 2 slides.\n
  28. /// r = ratio between rotation and translation.\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. /// \f$\beta\f$ = baumgarte constant.
  35. class RackAndPinionConstraintPart
  36. {
  37. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  38. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  39. {
  40. // Apply impulse if delta is not zero
  41. if (inLambda != 0.0f)
  42. {
  43. // Calculate velocity change due to constraint
  44. //
  45. // Impulse:
  46. // P = J^T lambda
  47. //
  48. // Euler velocity integration:
  49. // v' = v + M^-1 P
  50. ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);
  51. ioBody2.GetMotionProperties()->SubLinearVelocityStep(inLambda * mRatio_InvM2_B);
  52. return true;
  53. }
  54. return false;
  55. }
  56. public:
  57. /// Calculate properties used during the functions below
  58. /// @param inBody1 The first body that this constraint is attached to
  59. /// @param inBody2 The second body that this constraint is attached to
  60. /// @param inWorldSpaceHingeAxis The axis around which body 1 rotates
  61. /// @param inWorldSpaceSliderAxis The axis along which body 2 slides
  62. /// @param inRatio The ratio between rotation and translation
  63. inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis, const Body &inBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)
  64. {
  65. JPH_ASSERT(inWorldSpaceHingeAxis.IsNormalized(1.0e-4f));
  66. JPH_ASSERT(inWorldSpaceSliderAxis.IsNormalized(1.0e-4f));
  67. // Calculate: I1^-1 a
  68. mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis);
  69. // Calculate: r/m2 b
  70. float inv_m2 = inBody2.GetMotionProperties()->GetInverseMass();
  71. mRatio_InvM2_B = inRatio * inv_m2 * inWorldSpaceSliderAxis;
  72. // K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + 1/m2 * r^2 * b . b)
  73. mEffectiveMass = 1.0f / (inWorldSpaceHingeAxis.Dot(mInvI1_A) + inv_m2 * Square(inRatio));
  74. }
  75. /// Deactivate this constraint
  76. inline void Deactivate()
  77. {
  78. mEffectiveMass = 0.0f;
  79. mTotalLambda = 0.0f;
  80. }
  81. /// Check if constraint is active
  82. inline bool IsActive() const
  83. {
  84. return mEffectiveMass != 0.0f;
  85. }
  86. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  87. /// @param ioBody1 The first body that this constraint is attached to
  88. /// @param ioBody2 The second body that this constraint is attached to
  89. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  90. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  91. {
  92. mTotalLambda *= inWarmStartImpulseRatio;
  93. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  94. }
  95. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  96. /// @param ioBody1 The first body that this constraint is attached to
  97. /// @param ioBody2 The second body that this constraint is attached to
  98. /// @param inWorldSpaceHingeAxis The axis around which body 1 rotates
  99. /// @param inWorldSpaceSliderAxis The axis along which body 2 slides
  100. /// @param inRatio The ratio between rotation and translation
  101. inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis, Body &ioBody2, Vec3Arg inWorldSpaceSliderAxis, float inRatio)
  102. {
  103. // Lagrange multiplier is:
  104. //
  105. // lambda = -K^-1 (J v + b)
  106. float lambda = mEffectiveMass * (inRatio * inWorldSpaceSliderAxis.Dot(ioBody2.GetLinearVelocity()) - inWorldSpaceHingeAxis.Dot(ioBody1.GetAngularVelocity()));
  107. mTotalLambda += lambda; // Store accumulated impulse
  108. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  109. }
  110. /// Return lagrange multiplier
  111. float GetTotalLambda() const
  112. {
  113. return mTotalLambda;
  114. }
  115. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  116. /// @param ioBody1 The first body that this constraint is attached to
  117. /// @param ioBody2 The second body that this constraint is attached to
  118. /// @param inC Value of the constraint equation (C)
  119. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  120. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  121. {
  122. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  123. if (inC != 0.0f)
  124. {
  125. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  126. //
  127. // lambda = -K^-1 * beta / dt * C
  128. //
  129. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  130. float lambda = -mEffectiveMass * inBaumgarte * inC;
  131. // Directly integrate velocity change for one time step
  132. //
  133. // Euler velocity integration:
  134. // dv = M^-1 P
  135. //
  136. // Impulse:
  137. // P = J^T lambda
  138. //
  139. // Euler position integration:
  140. // x' = x + dv * dt
  141. //
  142. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  143. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  144. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  145. // integrate + a position integrate and then discard the velocity change.
  146. if (ioBody1.IsDynamic())
  147. ioBody1.AddRotationStep(lambda * mInvI1_A);
  148. if (ioBody2.IsDynamic())
  149. ioBody2.SubPositionStep(lambda * mRatio_InvM2_B);
  150. return true;
  151. }
  152. return false;
  153. }
  154. /// Save state of this constraint part
  155. void SaveState(StateRecorder &inStream) const
  156. {
  157. inStream.Write(mTotalLambda);
  158. }
  159. /// Restore state of this constraint part
  160. void RestoreState(StateRecorder &inStream)
  161. {
  162. inStream.Read(mTotalLambda);
  163. }
  164. private:
  165. Vec3 mInvI1_A;
  166. Vec3 mRatio_InvM2_B;
  167. float mEffectiveMass = 0.0f;
  168. float mTotalLambda = 0.0f;
  169. };
  170. JPH_NAMESPACE_END