MassProperties.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Body/MassProperties.h>
  5. #include <Jolt/Math/Matrix.h>
  6. #include <Jolt/Math/Vector.h>
  7. #include <Jolt/Math/EigenValueSymmetric.h>
  8. #include <Jolt/ObjectStream/TypeDeclarations.h>
  9. #include <Jolt/Core/StreamIn.h>
  10. #include <Jolt/Core/StreamOut.h>
  11. #include <Jolt/Core/InsertionSort.h>
  12. JPH_NAMESPACE_BEGIN
  13. JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(MassProperties)
  14. {
  15. JPH_ADD_ATTRIBUTE(MassProperties, mMass)
  16. JPH_ADD_ATTRIBUTE(MassProperties, mInertia)
  17. }
  18. bool MassProperties::DecomposePrincipalMomentsOfInertia(Mat44 &outRotation, Vec3 &outDiagonal) const
  19. {
  20. // Using eigendecomposition to get the principal components of the inertia tensor
  21. // See: https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix
  22. Matrix<3, 3> inertia;
  23. inertia.CopyPart(mInertia, 0, 0, 3, 3, 0, 0);
  24. Matrix<3, 3> eigen_vec = Matrix<3, 3>::sIdentity();
  25. Vector<3> eigen_val;
  26. if (!EigenValueSymmetric(inertia, eigen_vec, eigen_val))
  27. return false;
  28. // Sort so that the biggest value goes first
  29. int indices[] = { 0, 1, 2 };
  30. InsertionSort(indices, indices + 3, [&eigen_val](int inLeft, int inRight) { return eigen_val[inLeft] > eigen_val[inRight]; });
  31. // Convert to a regular Mat44 and Vec3
  32. outRotation = Mat44::sIdentity();
  33. for (int i = 0; i < 3; ++i)
  34. {
  35. outRotation.SetColumn3(i, Vec3(reinterpret_cast<Float3 &>(eigen_vec.GetColumn(indices[i]))));
  36. outDiagonal.SetComponent(i, eigen_val[indices[i]]);
  37. }
  38. // Make sure that the rotation matrix is a right handed matrix
  39. if (outRotation.GetAxisX().Cross(outRotation.GetAxisY()).Dot(outRotation.GetAxisZ()) < 0.0f)
  40. outRotation.SetAxisZ(-outRotation.GetAxisZ());
  41. #ifdef JPH_ENABLE_ASSERTS
  42. // Validate that the solution is correct, for each axis we want to make sure that the difference in inertia is
  43. // smaller than some fraction of the inertia itself in that axis
  44. Mat44 new_inertia = outRotation * Mat44::sScale(outDiagonal) * outRotation.Inversed();
  45. for (int i = 0; i < 3; ++i)
  46. JPH_ASSERT(new_inertia.GetColumn3(i).IsClose(mInertia.GetColumn3(i), mInertia.GetColumn3(i).LengthSq() * 1.0e-10f));
  47. #endif
  48. return true;
  49. }
  50. void MassProperties::SetMassAndInertiaOfSolidBox(Vec3Arg inBoxSize, float inDensity)
  51. {
  52. // Calculate mass
  53. mMass = inBoxSize.GetX() * inBoxSize.GetY() * inBoxSize.GetZ() * inDensity;
  54. // Calculate inertia
  55. Vec3 size_sq = inBoxSize * inBoxSize;
  56. Vec3 scale = (size_sq.Swizzle<SWIZZLE_Y, SWIZZLE_X, SWIZZLE_X>() + size_sq.Swizzle<SWIZZLE_Z, SWIZZLE_Z, SWIZZLE_Y>()) * (mMass / 12.0f);
  57. mInertia = Mat44::sScale(scale);
  58. }
  59. void MassProperties::ScaleToMass(float inMass)
  60. {
  61. if (mMass > 0.0f)
  62. {
  63. // Calculate how much we have to scale the inertia tensor
  64. float mass_scale = inMass / mMass;
  65. // Update mass
  66. mMass = inMass;
  67. // Update inertia tensor
  68. for (int i = 0; i < 3; ++i)
  69. mInertia.SetColumn4(i, mInertia.GetColumn4(i) * mass_scale);
  70. }
  71. else
  72. {
  73. // Just set the mass
  74. mMass = inMass;
  75. }
  76. }
  77. Vec3 MassProperties::sGetEquivalentSolidBoxSize(float inMass, Vec3Arg inInertiaDiagonal)
  78. {
  79. // Moment of inertia of a solid box has diagonal:
  80. // mass / 12 * [size_y^2 + size_z^2, size_x^2 + size_z^2, size_x^2 + size_y^2]
  81. // Solving for size_x, size_y and size_y (diagonal and mass are known):
  82. Vec3 diagonal = inInertiaDiagonal * (12.0f / inMass);
  83. return Vec3(sqrt(0.5f * (-diagonal[0] + diagonal[1] + diagonal[2])), sqrt(0.5f * (diagonal[0] - diagonal[1] + diagonal[2])), sqrt(0.5f * (diagonal[0] + diagonal[1] - diagonal[2])));
  84. }
  85. void MassProperties::Scale(Vec3Arg inScale)
  86. {
  87. // See: https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor
  88. // The diagonal of the inertia tensor can be calculated like this:
  89. // Ixx = sum_{k = 1 to n}(m_k * (y_k^2 + z_k^2))
  90. // Iyy = sum_{k = 1 to n}(m_k * (x_k^2 + z_k^2))
  91. // Izz = sum_{k = 1 to n}(m_k * (x_k^2 + y_k^2))
  92. //
  93. // We want to isolate the terms x_k, y_k and z_k:
  94. // d = [0.5, 0.5, 0.5].[Ixx, Iyy, Izz]
  95. // [sum_{k = 1 to n}(m_k * x_k^2), sum_{k = 1 to n}(m_k * y_k^2), sum_{k = 1 to n}(m_k * z_k^2)] = [d, d, d] - [Ixx, Iyy, Izz]
  96. Vec3 diagonal = mInertia.GetDiagonal3();
  97. Vec3 xyz_sq = Vec3::sReplicate(Vec3::sReplicate(0.5f).Dot(diagonal)) - diagonal;
  98. // When scaling a shape these terms change like this:
  99. // sum_{k = 1 to n}(m_k * (scale_x * x_k)^2) = scale_x^2 * sum_{k = 1 to n}(m_k * x_k^2)
  100. // Same for y_k and z_k
  101. // Using these terms we can calculate the new diagonal of the inertia tensor:
  102. Vec3 xyz_scaled_sq = inScale * inScale * xyz_sq;
  103. float i_xx = xyz_scaled_sq.GetY() + xyz_scaled_sq.GetZ();
  104. float i_yy = xyz_scaled_sq.GetX() + xyz_scaled_sq.GetZ();
  105. float i_zz = xyz_scaled_sq.GetX() + xyz_scaled_sq.GetY();
  106. // The off diagonal elements are calculated like:
  107. // Ixy = -sum_{k = 1 to n}(x_k y_k)
  108. // Ixz = -sum_{k = 1 to n}(x_k z_k)
  109. // Iyz = -sum_{k = 1 to n}(y_k z_k)
  110. // Scaling these is simple:
  111. float i_xy = inScale.GetX() * inScale.GetY() * mInertia(0, 1);
  112. float i_xz = inScale.GetX() * inScale.GetZ() * mInertia(0, 2);
  113. float i_yz = inScale.GetY() * inScale.GetZ() * mInertia(1, 2);
  114. // Update inertia tensor
  115. mInertia(0, 0) = i_xx;
  116. mInertia(0, 1) = i_xy;
  117. mInertia(1, 0) = i_xy;
  118. mInertia(1, 1) = i_yy;
  119. mInertia(0, 2) = i_xz;
  120. mInertia(2, 0) = i_xz;
  121. mInertia(1, 2) = i_yz;
  122. mInertia(2, 1) = i_yz;
  123. mInertia(2, 2) = i_zz;
  124. // Mass scales linear with volume (note that the scaling can be negative and we don't want the mass to become negative)
  125. float mass_scale = abs(inScale.GetX() * inScale.GetY() * inScale.GetZ());
  126. mMass *= mass_scale;
  127. // Inertia scales linear with mass. This updates the m_k terms above.
  128. mInertia *= mass_scale;
  129. // Ensure that the bottom right element is a 1 again
  130. mInertia(3, 3) = 1.0f;
  131. }
  132. void MassProperties::Rotate(Mat44Arg inRotation)
  133. {
  134. mInertia = inRotation.Multiply3x3(mInertia).Multiply3x3RightTransposed(inRotation);
  135. }
  136. void MassProperties::Translate(Vec3Arg inTranslation)
  137. {
  138. // Transform the inertia using the parallel axis theorem: I' = I + m * (translation^2 E - translation translation^T)
  139. // Where I is the original body's inertia and E the identity matrix
  140. // See: https://en.wikipedia.org/wiki/Parallel_axis_theorem
  141. mInertia += mMass * (Mat44::sScale(inTranslation.Dot(inTranslation)) - Mat44::sOuterProduct(inTranslation, inTranslation));
  142. // Ensure that inertia is a 3x3 matrix, adding inertias causes the bottom right element to change
  143. mInertia.SetColumn4(3, Vec4(0, 0, 0, 1));
  144. }
  145. void MassProperties::SaveBinaryState(StreamOut &inStream) const
  146. {
  147. inStream.Write(mMass);
  148. inStream.Write(mInertia);
  149. }
  150. void MassProperties::RestoreBinaryState(StreamIn &inStream)
  151. {
  152. inStream.Read(mMass);
  153. inStream.Read(mInertia);
  154. }
  155. JPH_NAMESPACE_END