transform_interpolator.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /**************************************************************************/
  2. /* transform_interpolator.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "transform_interpolator.h"
  31. #include "core/math/transform_2d.h"
  32. #include "core/math/transform_3d.h"
  33. void TransformInterpolator::interpolate_transform_2d(const Transform2D &p_prev, const Transform2D &p_curr, Transform2D &r_result, real_t p_fraction) {
  34. // Special case for physics interpolation, if flipping, don't interpolate basis.
  35. // If the determinant polarity changes, the handedness of the coordinate system changes.
  36. if (_sign(p_prev.determinant()) != _sign(p_curr.determinant())) {
  37. r_result.columns[0] = p_curr.columns[0];
  38. r_result.columns[1] = p_curr.columns[1];
  39. r_result.set_origin(p_prev.get_origin().lerp(p_curr.get_origin(), p_fraction));
  40. return;
  41. }
  42. r_result = p_prev.interpolate_with(p_curr, p_fraction);
  43. }
  44. void TransformInterpolator::interpolate_transform_3d(const Transform3D &p_prev, const Transform3D &p_curr, Transform3D &r_result, real_t p_fraction) {
  45. r_result.origin = p_prev.origin + ((p_curr.origin - p_prev.origin) * p_fraction);
  46. interpolate_basis(p_prev.basis, p_curr.basis, r_result.basis, p_fraction);
  47. }
  48. void TransformInterpolator::interpolate_basis(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction) {
  49. Method method = find_method(p_prev, p_curr);
  50. interpolate_basis_via_method(p_prev, p_curr, r_result, p_fraction, method);
  51. }
  52. void TransformInterpolator::interpolate_transform_3d_via_method(const Transform3D &p_prev, const Transform3D &p_curr, Transform3D &r_result, real_t p_fraction, Method p_method) {
  53. r_result.origin = p_prev.origin + ((p_curr.origin - p_prev.origin) * p_fraction);
  54. interpolate_basis_via_method(p_prev.basis, p_curr.basis, r_result.basis, p_fraction, p_method);
  55. }
  56. void TransformInterpolator::interpolate_basis_via_method(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction, Method p_method) {
  57. switch (p_method) {
  58. default: {
  59. interpolate_basis_linear(p_prev, p_curr, r_result, p_fraction);
  60. } break;
  61. case INTERP_SLERP: {
  62. r_result = _basis_slerp_unchecked(p_prev, p_curr, p_fraction);
  63. } break;
  64. case INTERP_SCALED_SLERP: {
  65. interpolate_basis_scaled_slerp(p_prev, p_curr, r_result, p_fraction);
  66. } break;
  67. }
  68. }
  69. Quaternion TransformInterpolator::_basis_to_quat_unchecked(const Basis &p_basis) {
  70. Basis m = p_basis;
  71. real_t trace = m.rows[0][0] + m.rows[1][1] + m.rows[2][2];
  72. real_t temp[4];
  73. if (trace > 0.0) {
  74. real_t s = Math::sqrt(trace + 1.0f);
  75. temp[3] = (s * 0.5f);
  76. s = 0.5f / s;
  77. temp[0] = ((m.rows[2][1] - m.rows[1][2]) * s);
  78. temp[1] = ((m.rows[0][2] - m.rows[2][0]) * s);
  79. temp[2] = ((m.rows[1][0] - m.rows[0][1]) * s);
  80. } else {
  81. int i = m.rows[0][0] < m.rows[1][1]
  82. ? (m.rows[1][1] < m.rows[2][2] ? 2 : 1)
  83. : (m.rows[0][0] < m.rows[2][2] ? 2 : 0);
  84. int j = (i + 1) % 3;
  85. int k = (i + 2) % 3;
  86. real_t s = Math::sqrt(m.rows[i][i] - m.rows[j][j] - m.rows[k][k] + 1.0f);
  87. temp[i] = s * 0.5f;
  88. s = 0.5f / s;
  89. temp[3] = (m.rows[k][j] - m.rows[j][k]) * s;
  90. temp[j] = (m.rows[j][i] + m.rows[i][j]) * s;
  91. temp[k] = (m.rows[k][i] + m.rows[i][k]) * s;
  92. }
  93. return Quaternion(temp[0], temp[1], temp[2], temp[3]);
  94. }
  95. Quaternion TransformInterpolator::_quat_slerp_unchecked(const Quaternion &p_from, const Quaternion &p_to, real_t p_fraction) {
  96. Quaternion to1;
  97. real_t omega, cosom, sinom, scale0, scale1;
  98. // Calculate cosine.
  99. cosom = p_from.dot(p_to);
  100. // Adjust signs (if necessary)
  101. if (cosom < 0.0f) {
  102. cosom = -cosom;
  103. to1.x = -p_to.x;
  104. to1.y = -p_to.y;
  105. to1.z = -p_to.z;
  106. to1.w = -p_to.w;
  107. } else {
  108. to1.x = p_to.x;
  109. to1.y = p_to.y;
  110. to1.z = p_to.z;
  111. to1.w = p_to.w;
  112. }
  113. // Calculate coefficients.
  114. // This check could possibly be removed as we dealt with this
  115. // case in the find_method() function, but is left for safety, it probably
  116. // isn't a bottleneck.
  117. if ((1.0f - cosom) > (real_t)CMP_EPSILON) {
  118. // standard case (slerp)
  119. omega = Math::acos(cosom);
  120. sinom = Math::sin(omega);
  121. scale0 = Math::sin((1.0f - p_fraction) * omega) / sinom;
  122. scale1 = Math::sin(p_fraction * omega) / sinom;
  123. } else {
  124. // "from" and "to" quaternions are very close
  125. // ... so we can do a linear interpolation
  126. scale0 = 1.0f - p_fraction;
  127. scale1 = p_fraction;
  128. }
  129. // Calculate final values.
  130. return Quaternion(
  131. scale0 * p_from.x + scale1 * to1.x,
  132. scale0 * p_from.y + scale1 * to1.y,
  133. scale0 * p_from.z + scale1 * to1.z,
  134. scale0 * p_from.w + scale1 * to1.w);
  135. }
  136. Basis TransformInterpolator::_basis_slerp_unchecked(Basis p_from, Basis p_to, real_t p_fraction) {
  137. Quaternion from = _basis_to_quat_unchecked(p_from);
  138. Quaternion to = _basis_to_quat_unchecked(p_to);
  139. Basis b(_quat_slerp_unchecked(from, to, p_fraction));
  140. return b;
  141. }
  142. void TransformInterpolator::interpolate_basis_scaled_slerp(Basis p_prev, Basis p_curr, Basis &r_result, real_t p_fraction) {
  143. // Normalize both and find lengths.
  144. Vector3 lengths_prev = _basis_orthonormalize(p_prev);
  145. Vector3 lengths_curr = _basis_orthonormalize(p_curr);
  146. r_result = _basis_slerp_unchecked(p_prev, p_curr, p_fraction);
  147. // Now the result is unit length basis, we need to scale.
  148. Vector3 lengths_lerped = lengths_prev + ((lengths_curr - lengths_prev) * p_fraction);
  149. // Keep a note that the column / row order of the basis is weird,
  150. // so keep an eye for bugs with this.
  151. r_result[0] *= lengths_lerped;
  152. r_result[1] *= lengths_lerped;
  153. r_result[2] *= lengths_lerped;
  154. }
  155. void TransformInterpolator::interpolate_basis_linear(const Basis &p_prev, const Basis &p_curr, Basis &r_result, real_t p_fraction) {
  156. // Interpolate basis.
  157. r_result = p_prev.lerp(p_curr, p_fraction);
  158. // It turns out we need to guard against zero scale basis.
  159. // This is kind of silly, as we should probably fix the bugs elsewhere in Godot that can't deal with
  160. // zero scale, but until that time...
  161. for (int n = 0; n < 3; n++) {
  162. Vector3 &axis = r_result[n];
  163. // Not ok, this could cause errors due to bugs elsewhere,
  164. // so we will bodge set this to a small value.
  165. const real_t smallest = 0.0001f;
  166. const real_t smallest_squared = smallest * smallest;
  167. if (axis.length_squared() < smallest_squared) {
  168. // Setting a different component to the smallest
  169. // helps prevent the situation where all the axes are pointing in the same direction,
  170. // which could be a problem for e.g. cross products...
  171. axis[n] = smallest;
  172. }
  173. }
  174. }
  175. // Returns length.
  176. real_t TransformInterpolator::_vec3_normalize(Vector3 &p_vec) {
  177. real_t lengthsq = p_vec.length_squared();
  178. if (lengthsq == 0.0f) {
  179. p_vec.x = p_vec.y = p_vec.z = 0.0f;
  180. return 0.0f;
  181. }
  182. real_t length = Math::sqrt(lengthsq);
  183. p_vec.x /= length;
  184. p_vec.y /= length;
  185. p_vec.z /= length;
  186. return length;
  187. }
  188. // Returns lengths.
  189. Vector3 TransformInterpolator::_basis_orthonormalize(Basis &r_basis) {
  190. // Gram-Schmidt Process.
  191. Vector3 x = r_basis.get_column(0);
  192. Vector3 y = r_basis.get_column(1);
  193. Vector3 z = r_basis.get_column(2);
  194. Vector3 lengths;
  195. lengths.x = _vec3_normalize(x);
  196. y = (y - x * (x.dot(y)));
  197. lengths.y = _vec3_normalize(y);
  198. z = (z - x * (x.dot(z)) - y * (y.dot(z)));
  199. lengths.z = _vec3_normalize(z);
  200. r_basis.set_column(0, x);
  201. r_basis.set_column(1, y);
  202. r_basis.set_column(2, z);
  203. return lengths;
  204. }
  205. TransformInterpolator::Method TransformInterpolator::_test_basis(Basis p_basis, bool r_needed_normalize, Quaternion &r_quat) {
  206. // Axis lengths.
  207. Vector3 al = Vector3(p_basis.get_column(0).length_squared(),
  208. p_basis.get_column(1).length_squared(),
  209. p_basis.get_column(2).length_squared());
  210. // Non unit scale?
  211. if (r_needed_normalize || !_vec3_is_equal_approx(al, Vector3(1.0, 1.0, 1.0), (real_t)0.001f)) {
  212. // If the basis is not normalized (at least approximately), it will fail the checks needed for slerp.
  213. // So we try to detect a scaled (but not sheared) basis, which we *can* slerp by normalizing first,
  214. // and lerping the scales separately.
  215. // If any of the axes are really small, it is unlikely to be a valid rotation, or is scaled too small to deal with float error.
  216. const real_t sl_epsilon = 0.00001f;
  217. if ((al.x < sl_epsilon) ||
  218. (al.y < sl_epsilon) ||
  219. (al.z < sl_epsilon)) {
  220. return INTERP_LERP;
  221. }
  222. // Normalize the basis.
  223. Basis norm_basis = p_basis;
  224. al.x = Math::sqrt(al.x);
  225. al.y = Math::sqrt(al.y);
  226. al.z = Math::sqrt(al.z);
  227. norm_basis.set_column(0, norm_basis.get_column(0) / al.x);
  228. norm_basis.set_column(1, norm_basis.get_column(1) / al.y);
  229. norm_basis.set_column(2, norm_basis.get_column(2) / al.z);
  230. // This doesn't appear necessary, as the later checks will catch it.
  231. // if (!_basis_is_orthogonal_any_scale(norm_basis)) {
  232. // return INTERP_LERP;
  233. // }
  234. p_basis = norm_basis;
  235. // Orthonormalize not necessary as normal normalization(!) works if the
  236. // axes are orthonormal.
  237. // p_basis.orthonormalize();
  238. // If we needed to normalize one of the two bases, we will need to normalize both,
  239. // regardless of whether the 2nd needs it, just to make sure it takes the path to return
  240. // INTERP_SCALED_LERP on the 2nd call of _test_basis.
  241. r_needed_normalize = true;
  242. }
  243. // Apply less stringent tests than the built in slerp, the standard Godot slerp
  244. // is too susceptible to float error to be useful.
  245. real_t det = p_basis.determinant();
  246. if (!Math::is_equal_approx(det, 1, (real_t)0.01f)) {
  247. return INTERP_LERP;
  248. }
  249. if (!_basis_is_orthogonal(p_basis)) {
  250. return INTERP_LERP;
  251. }
  252. // TODO: This could possibly be less stringent too, check this.
  253. r_quat = _basis_to_quat_unchecked(p_basis);
  254. if (!r_quat.is_normalized()) {
  255. return INTERP_LERP;
  256. }
  257. return r_needed_normalize ? INTERP_SCALED_SLERP : INTERP_SLERP;
  258. }
  259. // This check doesn't seem to be needed but is preserved in case of bugs.
  260. bool TransformInterpolator::_basis_is_orthogonal_any_scale(const Basis &p_basis) {
  261. Vector3 cross = p_basis.get_column(0).cross(p_basis.get_column(1));
  262. real_t l = _vec3_normalize(cross);
  263. // Too small numbers, revert to lerp.
  264. if (l < 0.001f) {
  265. return false;
  266. }
  267. const real_t epsilon = 0.9995f;
  268. real_t dot = cross.dot(p_basis.get_column(2));
  269. if (dot < epsilon) {
  270. return false;
  271. }
  272. cross = p_basis.get_column(1).cross(p_basis.get_column(2));
  273. l = _vec3_normalize(cross);
  274. // Too small numbers, revert to lerp.
  275. if (l < 0.001f) {
  276. return false;
  277. }
  278. dot = cross.dot(p_basis.get_column(0));
  279. if (dot < epsilon) {
  280. return false;
  281. }
  282. return true;
  283. }
  284. bool TransformInterpolator::_basis_is_orthogonal(const Basis &p_basis, real_t p_epsilon) {
  285. Basis identity;
  286. Basis m = p_basis * p_basis.transposed();
  287. // Less stringent tests than the standard Godot slerp.
  288. if (!_vec3_is_equal_approx(m[0], identity[0], p_epsilon) || !_vec3_is_equal_approx(m[1], identity[1], p_epsilon) || !_vec3_is_equal_approx(m[2], identity[2], p_epsilon)) {
  289. return false;
  290. }
  291. return true;
  292. }
  293. real_t TransformInterpolator::checksum_transform_3d(const Transform3D &p_transform) {
  294. // just a really basic checksum, this can probably be improved
  295. real_t sum = _vec3_sum(p_transform.origin);
  296. sum -= _vec3_sum(p_transform.basis.rows[0]);
  297. sum += _vec3_sum(p_transform.basis.rows[1]);
  298. sum -= _vec3_sum(p_transform.basis.rows[2]);
  299. return sum;
  300. }
  301. TransformInterpolator::Method TransformInterpolator::find_method(const Basis &p_a, const Basis &p_b) {
  302. bool needed_normalize = false;
  303. Quaternion q0;
  304. Method method = _test_basis(p_a, needed_normalize, q0);
  305. if (method == INTERP_LERP) {
  306. return method;
  307. }
  308. Quaternion q1;
  309. method = _test_basis(p_b, needed_normalize, q1);
  310. if (method == INTERP_LERP) {
  311. return method;
  312. }
  313. // Are they close together?
  314. // Apply the same test that will revert to lerp as is present in the slerp routine.
  315. // Calculate cosine.
  316. real_t cosom = Math::abs(q0.dot(q1));
  317. if ((1.0f - cosom) <= (real_t)CMP_EPSILON) {
  318. return INTERP_LERP;
  319. }
  320. return method;
  321. }