basis.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /**************************************************************************/
  2. /* basis.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 "basis.h"
  31. #include "core/math/math_funcs.h"
  32. #include "core/string/ustring.h"
  33. #define cofac(row1, col1, row2, col2) \
  34. (rows[row1][col1] * rows[row2][col2] - rows[row1][col2] * rows[row2][col1])
  35. void Basis::invert() {
  36. real_t co[3] = {
  37. cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1)
  38. };
  39. real_t det = rows[0][0] * co[0] +
  40. rows[0][1] * co[1] +
  41. rows[0][2] * co[2];
  42. #ifdef MATH_CHECKS
  43. ERR_FAIL_COND(det == 0);
  44. #endif
  45. real_t s = 1.0f / det;
  46. set(co[0] * s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s,
  47. co[1] * s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s,
  48. co[2] * s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s);
  49. }
  50. void Basis::orthonormalize() {
  51. // Gram-Schmidt Process
  52. Vector3 x = get_column(0);
  53. Vector3 y = get_column(1);
  54. Vector3 z = get_column(2);
  55. x.normalize();
  56. y = (y - x * (x.dot(y)));
  57. y.normalize();
  58. z = (z - x * (x.dot(z)) - y * (y.dot(z)));
  59. z.normalize();
  60. set_column(0, x);
  61. set_column(1, y);
  62. set_column(2, z);
  63. }
  64. Basis Basis::orthonormalized() const {
  65. Basis c = *this;
  66. c.orthonormalize();
  67. return c;
  68. }
  69. void Basis::orthogonalize() {
  70. Vector3 scl = get_scale();
  71. orthonormalize();
  72. scale_local(scl);
  73. }
  74. Basis Basis::orthogonalized() const {
  75. Basis c = *this;
  76. c.orthogonalize();
  77. return c;
  78. }
  79. bool Basis::is_orthogonal() const {
  80. Basis identity;
  81. Basis m = (*this) * transposed();
  82. return m.is_equal_approx(identity);
  83. }
  84. bool Basis::is_diagonal() const {
  85. return (
  86. Math::is_zero_approx(rows[0][1]) && Math::is_zero_approx(rows[0][2]) &&
  87. Math::is_zero_approx(rows[1][0]) && Math::is_zero_approx(rows[1][2]) &&
  88. Math::is_zero_approx(rows[2][0]) && Math::is_zero_approx(rows[2][1]));
  89. }
  90. bool Basis::is_rotation() const {
  91. return Math::is_equal_approx(determinant(), 1, (real_t)UNIT_EPSILON) && is_orthogonal();
  92. }
  93. #ifdef MATH_CHECKS
  94. // This method is only used once, in diagonalize. If it's desired elsewhere, feel free to remove the #ifdef.
  95. bool Basis::is_symmetric() const {
  96. if (!Math::is_equal_approx(rows[0][1], rows[1][0])) {
  97. return false;
  98. }
  99. if (!Math::is_equal_approx(rows[0][2], rows[2][0])) {
  100. return false;
  101. }
  102. if (!Math::is_equal_approx(rows[1][2], rows[2][1])) {
  103. return false;
  104. }
  105. return true;
  106. }
  107. #endif
  108. Basis Basis::diagonalize() {
  109. // NOTE: only implemented for symmetric matrices
  110. // with the Jacobi iterative method
  111. #ifdef MATH_CHECKS
  112. ERR_FAIL_COND_V(!is_symmetric(), Basis());
  113. #endif
  114. const int ite_max = 1024;
  115. real_t off_matrix_norm_2 = rows[0][1] * rows[0][1] + rows[0][2] * rows[0][2] + rows[1][2] * rows[1][2];
  116. int ite = 0;
  117. Basis acc_rot;
  118. while (off_matrix_norm_2 > (real_t)CMP_EPSILON2 && ite++ < ite_max) {
  119. real_t el01_2 = rows[0][1] * rows[0][1];
  120. real_t el02_2 = rows[0][2] * rows[0][2];
  121. real_t el12_2 = rows[1][2] * rows[1][2];
  122. // Find the pivot element
  123. int i, j;
  124. if (el01_2 > el02_2) {
  125. if (el12_2 > el01_2) {
  126. i = 1;
  127. j = 2;
  128. } else {
  129. i = 0;
  130. j = 1;
  131. }
  132. } else {
  133. if (el12_2 > el02_2) {
  134. i = 1;
  135. j = 2;
  136. } else {
  137. i = 0;
  138. j = 2;
  139. }
  140. }
  141. // Compute the rotation angle
  142. real_t angle;
  143. if (Math::is_equal_approx(rows[j][j], rows[i][i])) {
  144. angle = Math_PI / 4;
  145. } else {
  146. angle = 0.5f * Math::atan(2 * rows[i][j] / (rows[j][j] - rows[i][i]));
  147. }
  148. // Compute the rotation matrix
  149. Basis rot;
  150. rot.rows[i][i] = rot.rows[j][j] = Math::cos(angle);
  151. rot.rows[i][j] = -(rot.rows[j][i] = Math::sin(angle));
  152. // Update the off matrix norm
  153. off_matrix_norm_2 -= rows[i][j] * rows[i][j];
  154. // Apply the rotation
  155. *this = rot * *this * rot.transposed();
  156. acc_rot = rot * acc_rot;
  157. }
  158. return acc_rot;
  159. }
  160. Basis Basis::inverse() const {
  161. Basis inv = *this;
  162. inv.invert();
  163. return inv;
  164. }
  165. void Basis::transpose() {
  166. SWAP(rows[0][1], rows[1][0]);
  167. SWAP(rows[0][2], rows[2][0]);
  168. SWAP(rows[1][2], rows[2][1]);
  169. }
  170. Basis Basis::transposed() const {
  171. Basis tr = *this;
  172. tr.transpose();
  173. return tr;
  174. }
  175. Basis Basis::from_scale(const Vector3 &p_scale) {
  176. return Basis(p_scale.x, 0, 0, 0, p_scale.y, 0, 0, 0, p_scale.z);
  177. }
  178. // Multiplies the matrix from left by the scaling matrix: M -> S.M
  179. // See the comment for Basis::rotated for further explanation.
  180. void Basis::scale(const Vector3 &p_scale) {
  181. rows[0][0] *= p_scale.x;
  182. rows[0][1] *= p_scale.x;
  183. rows[0][2] *= p_scale.x;
  184. rows[1][0] *= p_scale.y;
  185. rows[1][1] *= p_scale.y;
  186. rows[1][2] *= p_scale.y;
  187. rows[2][0] *= p_scale.z;
  188. rows[2][1] *= p_scale.z;
  189. rows[2][2] *= p_scale.z;
  190. }
  191. Basis Basis::scaled(const Vector3 &p_scale) const {
  192. Basis m = *this;
  193. m.scale(p_scale);
  194. return m;
  195. }
  196. void Basis::scale_local(const Vector3 &p_scale) {
  197. // performs a scaling in object-local coordinate system:
  198. // M -> (M.S.Minv).M = M.S.
  199. *this = scaled_local(p_scale);
  200. }
  201. void Basis::scale_orthogonal(const Vector3 &p_scale) {
  202. *this = scaled_orthogonal(p_scale);
  203. }
  204. Basis Basis::scaled_orthogonal(const Vector3 &p_scale) const {
  205. Basis m = *this;
  206. Vector3 s = Vector3(-1, -1, -1) + p_scale;
  207. bool sign = signbit(s.x + s.y + s.z);
  208. Basis b = m.orthonormalized();
  209. s = b.xform_inv(s);
  210. Vector3 dots;
  211. for (int i = 0; i < 3; i++) {
  212. for (int j = 0; j < 3; j++) {
  213. dots[j] += s[i] * abs(m.get_column(i).normalized().dot(b.get_column(j)));
  214. }
  215. }
  216. if (sign != signbit(dots.x + dots.y + dots.z)) {
  217. dots = -dots;
  218. }
  219. m.scale_local(Vector3(1, 1, 1) + dots);
  220. return m;
  221. }
  222. float Basis::get_uniform_scale() const {
  223. return (rows[0].length() + rows[1].length() + rows[2].length()) / 3.0f;
  224. }
  225. Basis Basis::scaled_local(const Vector3 &p_scale) const {
  226. return (*this) * Basis::from_scale(p_scale);
  227. }
  228. Vector3 Basis::get_scale_abs() const {
  229. return Vector3(
  230. Vector3(rows[0][0], rows[1][0], rows[2][0]).length(),
  231. Vector3(rows[0][1], rows[1][1], rows[2][1]).length(),
  232. Vector3(rows[0][2], rows[1][2], rows[2][2]).length());
  233. }
  234. Vector3 Basis::get_scale_local() const {
  235. real_t det_sign = SIGN(determinant());
  236. return det_sign * Vector3(rows[0].length(), rows[1].length(), rows[2].length());
  237. }
  238. // get_scale works with get_rotation, use get_scale_abs if you need to enforce positive signature.
  239. Vector3 Basis::get_scale() const {
  240. // FIXME: We are assuming M = R.S (R is rotation and S is scaling), and use polar decomposition to extract R and S.
  241. // A polar decomposition is M = O.P, where O is an orthogonal matrix (meaning rotation and reflection) and
  242. // P is a positive semi-definite matrix (meaning it contains absolute values of scaling along its diagonal).
  243. //
  244. // Despite being different from what we want to achieve, we can nevertheless make use of polar decomposition
  245. // here as follows. We can split O into a rotation and a reflection as O = R.Q, and obtain M = R.S where
  246. // we defined S = Q.P. Now, R is a proper rotation matrix and S is a (signed) scaling matrix,
  247. // which can involve negative scalings. However, there is a catch: unlike the polar decomposition of M = O.P,
  248. // the decomposition of O into a rotation and reflection matrix as O = R.Q is not unique.
  249. // Therefore, we are going to do this decomposition by sticking to a particular convention.
  250. // This may lead to confusion for some users though.
  251. //
  252. // The convention we use here is to absorb the sign flip into the scaling matrix.
  253. // The same convention is also used in other similar functions such as get_rotation_axis_angle, get_rotation, ...
  254. //
  255. // A proper way to get rid of this issue would be to store the scaling values (or at least their signs)
  256. // as a part of Basis. However, if we go that path, we need to disable direct (write) access to the
  257. // matrix elements.
  258. //
  259. // The rotation part of this decomposition is returned by get_rotation* functions.
  260. real_t det_sign = SIGN(determinant());
  261. return det_sign * get_scale_abs();
  262. }
  263. // Decomposes a Basis into a rotation-reflection matrix (an element of the group O(3)) and a positive scaling matrix as B = O.S.
  264. // Returns the rotation-reflection matrix via reference argument, and scaling information is returned as a Vector3.
  265. // This (internal) function is too specific and named too ugly to expose to users, and probably there's no need to do so.
  266. Vector3 Basis::rotref_posscale_decomposition(Basis &rotref) const {
  267. #ifdef MATH_CHECKS
  268. ERR_FAIL_COND_V(determinant() == 0, Vector3());
  269. Basis m = transposed() * (*this);
  270. ERR_FAIL_COND_V(!m.is_diagonal(), Vector3());
  271. #endif
  272. Vector3 scale = get_scale();
  273. Basis inv_scale = Basis().scaled(scale.inverse()); // this will also absorb the sign of scale
  274. rotref = (*this) * inv_scale;
  275. #ifdef MATH_CHECKS
  276. ERR_FAIL_COND_V(!rotref.is_orthogonal(), Vector3());
  277. #endif
  278. return scale.abs();
  279. }
  280. // Multiplies the matrix from left by the rotation matrix: M -> R.M
  281. // Note that this does *not* rotate the matrix itself.
  282. //
  283. // The main use of Basis is as Transform.basis, which is used by the transformation matrix
  284. // of 3D object. Rotate here refers to rotation of the object (which is R * (*this)),
  285. // not the matrix itself (which is R * (*this) * R.transposed()).
  286. Basis Basis::rotated(const Vector3 &p_axis, real_t p_angle) const {
  287. return Basis(p_axis, p_angle) * (*this);
  288. }
  289. void Basis::rotate(const Vector3 &p_axis, real_t p_angle) {
  290. *this = rotated(p_axis, p_angle);
  291. }
  292. void Basis::rotate_local(const Vector3 &p_axis, real_t p_angle) {
  293. // performs a rotation in object-local coordinate system:
  294. // M -> (M.R.Minv).M = M.R.
  295. *this = rotated_local(p_axis, p_angle);
  296. }
  297. Basis Basis::rotated_local(const Vector3 &p_axis, real_t p_angle) const {
  298. return (*this) * Basis(p_axis, p_angle);
  299. }
  300. Basis Basis::rotated(const Vector3 &p_euler, EulerOrder p_order) const {
  301. return Basis::from_euler(p_euler, p_order) * (*this);
  302. }
  303. void Basis::rotate(const Vector3 &p_euler, EulerOrder p_order) {
  304. *this = rotated(p_euler, p_order);
  305. }
  306. Basis Basis::rotated(const Quaternion &p_quaternion) const {
  307. return Basis(p_quaternion) * (*this);
  308. }
  309. void Basis::rotate(const Quaternion &p_quaternion) {
  310. *this = rotated(p_quaternion);
  311. }
  312. Vector3 Basis::get_euler_normalized(EulerOrder p_order) const {
  313. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  314. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  315. // See the comment in get_scale() for further information.
  316. Basis m = orthonormalized();
  317. real_t det = m.determinant();
  318. if (det < 0) {
  319. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  320. m.scale(Vector3(-1, -1, -1));
  321. }
  322. return m.get_euler(p_order);
  323. }
  324. Quaternion Basis::get_rotation_quaternion() const {
  325. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  326. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  327. // See the comment in get_scale() for further information.
  328. Basis m = orthonormalized();
  329. real_t det = m.determinant();
  330. if (det < 0) {
  331. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  332. m.scale(Vector3(-1, -1, -1));
  333. }
  334. return m.get_quaternion();
  335. }
  336. void Basis::rotate_to_align(Vector3 p_start_direction, Vector3 p_end_direction) {
  337. // Takes two vectors and rotates the basis from the first vector to the second vector.
  338. // Adopted from: https://gist.github.com/kevinmoran/b45980723e53edeb8a5a43c49f134724
  339. const Vector3 axis = p_start_direction.cross(p_end_direction).normalized();
  340. if (axis.length_squared() != 0) {
  341. real_t dot = p_start_direction.dot(p_end_direction);
  342. dot = CLAMP(dot, -1.0f, 1.0f);
  343. const real_t angle_rads = Math::acos(dot);
  344. *this = Basis(axis, angle_rads) * (*this);
  345. }
  346. }
  347. void Basis::get_rotation_axis_angle(Vector3 &p_axis, real_t &p_angle) const {
  348. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  349. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  350. // See the comment in get_scale() for further information.
  351. Basis m = orthonormalized();
  352. real_t det = m.determinant();
  353. if (det < 0) {
  354. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  355. m.scale(Vector3(-1, -1, -1));
  356. }
  357. m.get_axis_angle(p_axis, p_angle);
  358. }
  359. void Basis::get_rotation_axis_angle_local(Vector3 &p_axis, real_t &p_angle) const {
  360. // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S,
  361. // and returns the Euler angles corresponding to the rotation part, complementing get_scale().
  362. // See the comment in get_scale() for further information.
  363. Basis m = transposed();
  364. m.orthonormalize();
  365. real_t det = m.determinant();
  366. if (det < 0) {
  367. // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles.
  368. m.scale(Vector3(-1, -1, -1));
  369. }
  370. m.get_axis_angle(p_axis, p_angle);
  371. p_angle = -p_angle;
  372. }
  373. Vector3 Basis::get_euler(EulerOrder p_order) const {
  374. switch (p_order) {
  375. case EulerOrder::XYZ: {
  376. // Euler angles in XYZ convention.
  377. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  378. //
  379. // rot = cy*cz -cy*sz sy
  380. // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx
  381. // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy
  382. Vector3 euler;
  383. real_t sy = rows[0][2];
  384. if (sy < (1.0f - (real_t)CMP_EPSILON)) {
  385. if (sy > -(1.0f - (real_t)CMP_EPSILON)) {
  386. // is this a pure Y rotation?
  387. if (rows[1][0] == 0 && rows[0][1] == 0 && rows[1][2] == 0 && rows[2][1] == 0 && rows[1][1] == 1) {
  388. // return the simplest form (human friendlier in editor and scripts)
  389. euler.x = 0;
  390. euler.y = atan2(rows[0][2], rows[0][0]);
  391. euler.z = 0;
  392. } else {
  393. euler.x = Math::atan2(-rows[1][2], rows[2][2]);
  394. euler.y = Math::asin(sy);
  395. euler.z = Math::atan2(-rows[0][1], rows[0][0]);
  396. }
  397. } else {
  398. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  399. euler.y = -Math_PI / 2.0f;
  400. euler.z = 0.0f;
  401. }
  402. } else {
  403. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  404. euler.y = Math_PI / 2.0f;
  405. euler.z = 0.0f;
  406. }
  407. return euler;
  408. }
  409. case EulerOrder::XZY: {
  410. // Euler angles in XZY convention.
  411. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  412. //
  413. // rot = cz*cy -sz cz*sy
  414. // sx*sy+cx*cy*sz cx*cz cx*sz*sy-cy*sx
  415. // cy*sx*sz cz*sx cx*cy+sx*sz*sy
  416. Vector3 euler;
  417. real_t sz = rows[0][1];
  418. if (sz < (1.0f - (real_t)CMP_EPSILON)) {
  419. if (sz > -(1.0f - (real_t)CMP_EPSILON)) {
  420. euler.x = Math::atan2(rows[2][1], rows[1][1]);
  421. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  422. euler.z = Math::asin(-sz);
  423. } else {
  424. // It's -1
  425. euler.x = -Math::atan2(rows[1][2], rows[2][2]);
  426. euler.y = 0.0f;
  427. euler.z = Math_PI / 2.0f;
  428. }
  429. } else {
  430. // It's 1
  431. euler.x = -Math::atan2(rows[1][2], rows[2][2]);
  432. euler.y = 0.0f;
  433. euler.z = -Math_PI / 2.0f;
  434. }
  435. return euler;
  436. }
  437. case EulerOrder::YXZ: {
  438. // Euler angles in YXZ convention.
  439. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  440. //
  441. // rot = cy*cz+sy*sx*sz cz*sy*sx-cy*sz cx*sy
  442. // cx*sz cx*cz -sx
  443. // cy*sx*sz-cz*sy cy*cz*sx+sy*sz cy*cx
  444. Vector3 euler;
  445. real_t m12 = rows[1][2];
  446. if (m12 < (1 - (real_t)CMP_EPSILON)) {
  447. if (m12 > -(1 - (real_t)CMP_EPSILON)) {
  448. // is this a pure X rotation?
  449. if (rows[1][0] == 0 && rows[0][1] == 0 && rows[0][2] == 0 && rows[2][0] == 0 && rows[0][0] == 1) {
  450. // return the simplest form (human friendlier in editor and scripts)
  451. euler.x = atan2(-m12, rows[1][1]);
  452. euler.y = 0;
  453. euler.z = 0;
  454. } else {
  455. euler.x = asin(-m12);
  456. euler.y = atan2(rows[0][2], rows[2][2]);
  457. euler.z = atan2(rows[1][0], rows[1][1]);
  458. }
  459. } else { // m12 == -1
  460. euler.x = Math_PI * 0.5f;
  461. euler.y = atan2(rows[0][1], rows[0][0]);
  462. euler.z = 0;
  463. }
  464. } else { // m12 == 1
  465. euler.x = -Math_PI * 0.5f;
  466. euler.y = -atan2(rows[0][1], rows[0][0]);
  467. euler.z = 0;
  468. }
  469. return euler;
  470. }
  471. case EulerOrder::YZX: {
  472. // Euler angles in YZX convention.
  473. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  474. //
  475. // rot = cy*cz sy*sx-cy*cx*sz cx*sy+cy*sz*sx
  476. // sz cz*cx -cz*sx
  477. // -cz*sy cy*sx+cx*sy*sz cy*cx-sy*sz*sx
  478. Vector3 euler;
  479. real_t sz = rows[1][0];
  480. if (sz < (1.0f - (real_t)CMP_EPSILON)) {
  481. if (sz > -(1.0f - (real_t)CMP_EPSILON)) {
  482. euler.x = Math::atan2(-rows[1][2], rows[1][1]);
  483. euler.y = Math::atan2(-rows[2][0], rows[0][0]);
  484. euler.z = Math::asin(sz);
  485. } else {
  486. // It's -1
  487. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  488. euler.y = 0.0f;
  489. euler.z = -Math_PI / 2.0f;
  490. }
  491. } else {
  492. // It's 1
  493. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  494. euler.y = 0.0f;
  495. euler.z = Math_PI / 2.0f;
  496. }
  497. return euler;
  498. } break;
  499. case EulerOrder::ZXY: {
  500. // Euler angles in ZXY convention.
  501. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  502. //
  503. // rot = cz*cy-sz*sx*sy -cx*sz cz*sy+cy*sz*sx
  504. // cy*sz+cz*sx*sy cz*cx sz*sy-cz*cy*sx
  505. // -cx*sy sx cx*cy
  506. Vector3 euler;
  507. real_t sx = rows[2][1];
  508. if (sx < (1.0f - (real_t)CMP_EPSILON)) {
  509. if (sx > -(1.0f - (real_t)CMP_EPSILON)) {
  510. euler.x = Math::asin(sx);
  511. euler.y = Math::atan2(-rows[2][0], rows[2][2]);
  512. euler.z = Math::atan2(-rows[0][1], rows[1][1]);
  513. } else {
  514. // It's -1
  515. euler.x = -Math_PI / 2.0f;
  516. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  517. euler.z = 0;
  518. }
  519. } else {
  520. // It's 1
  521. euler.x = Math_PI / 2.0f;
  522. euler.y = Math::atan2(rows[0][2], rows[0][0]);
  523. euler.z = 0;
  524. }
  525. return euler;
  526. } break;
  527. case EulerOrder::ZYX: {
  528. // Euler angles in ZYX convention.
  529. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix
  530. //
  531. // rot = cz*cy cz*sy*sx-cx*sz sz*sx+cz*cx*cy
  532. // cy*sz cz*cx+sz*sy*sx cx*sz*sy-cz*sx
  533. // -sy cy*sx cy*cx
  534. Vector3 euler;
  535. real_t sy = rows[2][0];
  536. if (sy < (1.0f - (real_t)CMP_EPSILON)) {
  537. if (sy > -(1.0f - (real_t)CMP_EPSILON)) {
  538. euler.x = Math::atan2(rows[2][1], rows[2][2]);
  539. euler.y = Math::asin(-sy);
  540. euler.z = Math::atan2(rows[1][0], rows[0][0]);
  541. } else {
  542. // It's -1
  543. euler.x = 0;
  544. euler.y = Math_PI / 2.0f;
  545. euler.z = -Math::atan2(rows[0][1], rows[1][1]);
  546. }
  547. } else {
  548. // It's 1
  549. euler.x = 0;
  550. euler.y = -Math_PI / 2.0f;
  551. euler.z = -Math::atan2(rows[0][1], rows[1][1]);
  552. }
  553. return euler;
  554. }
  555. default: {
  556. ERR_FAIL_V_MSG(Vector3(), "Invalid parameter for get_euler(order)");
  557. }
  558. }
  559. return Vector3();
  560. }
  561. void Basis::set_euler(const Vector3 &p_euler, EulerOrder p_order) {
  562. real_t c, s;
  563. c = Math::cos(p_euler.x);
  564. s = Math::sin(p_euler.x);
  565. Basis xmat(1, 0, 0, 0, c, -s, 0, s, c);
  566. c = Math::cos(p_euler.y);
  567. s = Math::sin(p_euler.y);
  568. Basis ymat(c, 0, s, 0, 1, 0, -s, 0, c);
  569. c = Math::cos(p_euler.z);
  570. s = Math::sin(p_euler.z);
  571. Basis zmat(c, -s, 0, s, c, 0, 0, 0, 1);
  572. switch (p_order) {
  573. case EulerOrder::XYZ: {
  574. *this = xmat * (ymat * zmat);
  575. } break;
  576. case EulerOrder::XZY: {
  577. *this = xmat * zmat * ymat;
  578. } break;
  579. case EulerOrder::YXZ: {
  580. *this = ymat * xmat * zmat;
  581. } break;
  582. case EulerOrder::YZX: {
  583. *this = ymat * zmat * xmat;
  584. } break;
  585. case EulerOrder::ZXY: {
  586. *this = zmat * xmat * ymat;
  587. } break;
  588. case EulerOrder::ZYX: {
  589. *this = zmat * ymat * xmat;
  590. } break;
  591. default: {
  592. ERR_FAIL_MSG("Invalid order parameter for set_euler(vec3,order)");
  593. }
  594. }
  595. }
  596. bool Basis::is_equal_approx(const Basis &p_basis) const {
  597. return rows[0].is_equal_approx(p_basis.rows[0]) && rows[1].is_equal_approx(p_basis.rows[1]) && rows[2].is_equal_approx(p_basis.rows[2]);
  598. }
  599. bool Basis::is_finite() const {
  600. return rows[0].is_finite() && rows[1].is_finite() && rows[2].is_finite();
  601. }
  602. bool Basis::operator==(const Basis &p_matrix) const {
  603. for (int i = 0; i < 3; i++) {
  604. for (int j = 0; j < 3; j++) {
  605. if (rows[i][j] != p_matrix.rows[i][j]) {
  606. return false;
  607. }
  608. }
  609. }
  610. return true;
  611. }
  612. bool Basis::operator!=(const Basis &p_matrix) const {
  613. return (!(*this == p_matrix));
  614. }
  615. Basis::operator String() const {
  616. return "[X: " + get_column(0).operator String() +
  617. ", Y: " + get_column(1).operator String() +
  618. ", Z: " + get_column(2).operator String() + "]";
  619. }
  620. Quaternion Basis::get_quaternion() const {
  621. #ifdef MATH_CHECKS
  622. ERR_FAIL_COND_V_MSG(!is_rotation(), Quaternion(), "Basis must be normalized in order to be casted to a Quaternion. Use get_rotation_quaternion() or call orthonormalized() if the Basis contains linearly independent vectors.");
  623. #endif
  624. /* Allow getting a quaternion from an unnormalized transform */
  625. Basis m = *this;
  626. real_t trace = m.rows[0][0] + m.rows[1][1] + m.rows[2][2];
  627. real_t temp[4];
  628. if (trace > 0.0f) {
  629. real_t s = Math::sqrt(trace + 1.0f);
  630. temp[3] = (s * 0.5f);
  631. s = 0.5f / s;
  632. temp[0] = ((m.rows[2][1] - m.rows[1][2]) * s);
  633. temp[1] = ((m.rows[0][2] - m.rows[2][0]) * s);
  634. temp[2] = ((m.rows[1][0] - m.rows[0][1]) * s);
  635. } else {
  636. int i = m.rows[0][0] < m.rows[1][1]
  637. ? (m.rows[1][1] < m.rows[2][2] ? 2 : 1)
  638. : (m.rows[0][0] < m.rows[2][2] ? 2 : 0);
  639. int j = (i + 1) % 3;
  640. int k = (i + 2) % 3;
  641. real_t s = Math::sqrt(m.rows[i][i] - m.rows[j][j] - m.rows[k][k] + 1.0f);
  642. temp[i] = s * 0.5f;
  643. s = 0.5f / s;
  644. temp[3] = (m.rows[k][j] - m.rows[j][k]) * s;
  645. temp[j] = (m.rows[j][i] + m.rows[i][j]) * s;
  646. temp[k] = (m.rows[k][i] + m.rows[i][k]) * s;
  647. }
  648. return Quaternion(temp[0], temp[1], temp[2], temp[3]);
  649. }
  650. void Basis::get_axis_angle(Vector3 &r_axis, real_t &r_angle) const {
  651. /* checking this is a bad idea, because obtaining from scaled transform is a valid use case
  652. #ifdef MATH_CHECKS
  653. ERR_FAIL_COND(!is_rotation());
  654. #endif
  655. */
  656. // https://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  657. real_t x, y, z; // Variables for result.
  658. if (Math::is_zero_approx(rows[0][1] - rows[1][0]) && Math::is_zero_approx(rows[0][2] - rows[2][0]) && Math::is_zero_approx(rows[1][2] - rows[2][1])) {
  659. // Singularity found.
  660. // First check for identity matrix which must have +1 for all terms in leading diagonal and zero in other terms.
  661. if (is_diagonal() && (Math::abs(rows[0][0] + rows[1][1] + rows[2][2] - 3) < 3 * CMP_EPSILON)) {
  662. // This singularity is identity matrix so angle = 0.
  663. r_axis = Vector3(0, 1, 0);
  664. r_angle = 0;
  665. return;
  666. }
  667. // Otherwise this singularity is angle = 180.
  668. real_t xx = (rows[0][0] + 1) / 2;
  669. real_t yy = (rows[1][1] + 1) / 2;
  670. real_t zz = (rows[2][2] + 1) / 2;
  671. real_t xy = (rows[0][1] + rows[1][0]) / 4;
  672. real_t xz = (rows[0][2] + rows[2][0]) / 4;
  673. real_t yz = (rows[1][2] + rows[2][1]) / 4;
  674. if ((xx > yy) && (xx > zz)) { // rows[0][0] is the largest diagonal term.
  675. if (xx < CMP_EPSILON) {
  676. x = 0;
  677. y = Math_SQRT12;
  678. z = Math_SQRT12;
  679. } else {
  680. x = Math::sqrt(xx);
  681. y = xy / x;
  682. z = xz / x;
  683. }
  684. } else if (yy > zz) { // rows[1][1] is the largest diagonal term.
  685. if (yy < CMP_EPSILON) {
  686. x = Math_SQRT12;
  687. y = 0;
  688. z = Math_SQRT12;
  689. } else {
  690. y = Math::sqrt(yy);
  691. x = xy / y;
  692. z = yz / y;
  693. }
  694. } else { // rows[2][2] is the largest diagonal term so base result on this.
  695. if (zz < CMP_EPSILON) {
  696. x = Math_SQRT12;
  697. y = Math_SQRT12;
  698. z = 0;
  699. } else {
  700. z = Math::sqrt(zz);
  701. x = xz / z;
  702. y = yz / z;
  703. }
  704. }
  705. r_axis = Vector3(x, y, z);
  706. r_angle = Math_PI;
  707. return;
  708. }
  709. // As we have reached here there are no singularities so we can handle normally.
  710. double s = Math::sqrt((rows[2][1] - rows[1][2]) * (rows[2][1] - rows[1][2]) + (rows[0][2] - rows[2][0]) * (rows[0][2] - rows[2][0]) + (rows[1][0] - rows[0][1]) * (rows[1][0] - rows[0][1])); // Used to normalize.
  711. if (Math::abs(s) < CMP_EPSILON) {
  712. // Prevent divide by zero, should not happen if matrix is orthogonal and should be caught by singularity test above.
  713. s = 1;
  714. }
  715. x = (rows[2][1] - rows[1][2]) / s;
  716. y = (rows[0][2] - rows[2][0]) / s;
  717. z = (rows[1][0] - rows[0][1]) / s;
  718. r_axis = Vector3(x, y, z);
  719. // acos does clamping.
  720. r_angle = Math::acos((rows[0][0] + rows[1][1] + rows[2][2] - 1) / 2);
  721. }
  722. void Basis::set_quaternion(const Quaternion &p_quaternion) {
  723. real_t d = p_quaternion.length_squared();
  724. real_t s = 2.0f / d;
  725. real_t xs = p_quaternion.x * s, ys = p_quaternion.y * s, zs = p_quaternion.z * s;
  726. real_t wx = p_quaternion.w * xs, wy = p_quaternion.w * ys, wz = p_quaternion.w * zs;
  727. real_t xx = p_quaternion.x * xs, xy = p_quaternion.x * ys, xz = p_quaternion.x * zs;
  728. real_t yy = p_quaternion.y * ys, yz = p_quaternion.y * zs, zz = p_quaternion.z * zs;
  729. set(1.0f - (yy + zz), xy - wz, xz + wy,
  730. xy + wz, 1.0f - (xx + zz), yz - wx,
  731. xz - wy, yz + wx, 1.0f - (xx + yy));
  732. }
  733. void Basis::set_axis_angle(const Vector3 &p_axis, real_t p_angle) {
  734. // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_angle
  735. #ifdef MATH_CHECKS
  736. ERR_FAIL_COND_MSG(!p_axis.is_normalized(), "The axis Vector3 must be normalized.");
  737. #endif
  738. Vector3 axis_sq(p_axis.x * p_axis.x, p_axis.y * p_axis.y, p_axis.z * p_axis.z);
  739. real_t cosine = Math::cos(p_angle);
  740. rows[0][0] = axis_sq.x + cosine * (1.0f - axis_sq.x);
  741. rows[1][1] = axis_sq.y + cosine * (1.0f - axis_sq.y);
  742. rows[2][2] = axis_sq.z + cosine * (1.0f - axis_sq.z);
  743. real_t sine = Math::sin(p_angle);
  744. real_t t = 1 - cosine;
  745. real_t xyzt = p_axis.x * p_axis.y * t;
  746. real_t zyxs = p_axis.z * sine;
  747. rows[0][1] = xyzt - zyxs;
  748. rows[1][0] = xyzt + zyxs;
  749. xyzt = p_axis.x * p_axis.z * t;
  750. zyxs = p_axis.y * sine;
  751. rows[0][2] = xyzt + zyxs;
  752. rows[2][0] = xyzt - zyxs;
  753. xyzt = p_axis.y * p_axis.z * t;
  754. zyxs = p_axis.x * sine;
  755. rows[1][2] = xyzt - zyxs;
  756. rows[2][1] = xyzt + zyxs;
  757. }
  758. void Basis::set_axis_angle_scale(const Vector3 &p_axis, real_t p_angle, const Vector3 &p_scale) {
  759. _set_diagonal(p_scale);
  760. rotate(p_axis, p_angle);
  761. }
  762. void Basis::set_euler_scale(const Vector3 &p_euler, const Vector3 &p_scale, EulerOrder p_order) {
  763. _set_diagonal(p_scale);
  764. rotate(p_euler, p_order);
  765. }
  766. void Basis::set_quaternion_scale(const Quaternion &p_quaternion, const Vector3 &p_scale) {
  767. _set_diagonal(p_scale);
  768. rotate(p_quaternion);
  769. }
  770. // This also sets the non-diagonal elements to 0, which is misleading from the
  771. // name, so we want this method to be private. Use `from_scale` externally.
  772. void Basis::_set_diagonal(const Vector3 &p_diag) {
  773. rows[0][0] = p_diag.x;
  774. rows[0][1] = 0;
  775. rows[0][2] = 0;
  776. rows[1][0] = 0;
  777. rows[1][1] = p_diag.y;
  778. rows[1][2] = 0;
  779. rows[2][0] = 0;
  780. rows[2][1] = 0;
  781. rows[2][2] = p_diag.z;
  782. }
  783. Basis Basis::lerp(const Basis &p_to, const real_t &p_weight) const {
  784. Basis b;
  785. b.rows[0] = rows[0].lerp(p_to.rows[0], p_weight);
  786. b.rows[1] = rows[1].lerp(p_to.rows[1], p_weight);
  787. b.rows[2] = rows[2].lerp(p_to.rows[2], p_weight);
  788. return b;
  789. }
  790. Basis Basis::slerp(const Basis &p_to, const real_t &p_weight) const {
  791. //consider scale
  792. Quaternion from(*this);
  793. Quaternion to(p_to);
  794. Basis b(from.slerp(to, p_weight));
  795. b.rows[0] *= Math::lerp(rows[0].length(), p_to.rows[0].length(), p_weight);
  796. b.rows[1] *= Math::lerp(rows[1].length(), p_to.rows[1].length(), p_weight);
  797. b.rows[2] *= Math::lerp(rows[2].length(), p_to.rows[2].length(), p_weight);
  798. return b;
  799. }
  800. void Basis::rotate_sh(real_t *p_values) {
  801. // code by John Hable
  802. // http://filmicworlds.com/blog/simple-and-fast-spherical-harmonic-rotation/
  803. // this code is Public Domain
  804. const static real_t s_c3 = 0.94617469575; // (3*sqrt(5))/(4*sqrt(pi))
  805. const static real_t s_c4 = -0.31539156525; // (-sqrt(5))/(4*sqrt(pi))
  806. const static real_t s_c5 = 0.54627421529; // (sqrt(15))/(4*sqrt(pi))
  807. const static real_t s_c_scale = 1.0 / 0.91529123286551084;
  808. const static real_t s_c_scale_inv = 0.91529123286551084;
  809. const static real_t s_rc2 = 1.5853309190550713 * s_c_scale;
  810. const static real_t s_c4_div_c3 = s_c4 / s_c3;
  811. const static real_t s_c4_div_c3_x2 = (s_c4 / s_c3) * 2.0;
  812. const static real_t s_scale_dst2 = s_c3 * s_c_scale_inv;
  813. const static real_t s_scale_dst4 = s_c5 * s_c_scale_inv;
  814. const real_t src[9] = { p_values[0], p_values[1], p_values[2], p_values[3], p_values[4], p_values[5], p_values[6], p_values[7], p_values[8] };
  815. real_t m00 = rows[0][0];
  816. real_t m01 = rows[0][1];
  817. real_t m02 = rows[0][2];
  818. real_t m10 = rows[1][0];
  819. real_t m11 = rows[1][1];
  820. real_t m12 = rows[1][2];
  821. real_t m20 = rows[2][0];
  822. real_t m21 = rows[2][1];
  823. real_t m22 = rows[2][2];
  824. p_values[0] = src[0];
  825. p_values[1] = m11 * src[1] - m12 * src[2] + m10 * src[3];
  826. p_values[2] = -m21 * src[1] + m22 * src[2] - m20 * src[3];
  827. p_values[3] = m01 * src[1] - m02 * src[2] + m00 * src[3];
  828. real_t sh0 = src[7] + src[8] + src[8] - src[5];
  829. real_t sh1 = src[4] + s_rc2 * src[6] + src[7] + src[8];
  830. real_t sh2 = src[4];
  831. real_t sh3 = -src[7];
  832. real_t sh4 = -src[5];
  833. // Rotations. R0 and R1 just use the raw matrix columns
  834. real_t r2x = m00 + m01;
  835. real_t r2y = m10 + m11;
  836. real_t r2z = m20 + m21;
  837. real_t r3x = m00 + m02;
  838. real_t r3y = m10 + m12;
  839. real_t r3z = m20 + m22;
  840. real_t r4x = m01 + m02;
  841. real_t r4y = m11 + m12;
  842. real_t r4z = m21 + m22;
  843. // dense matrix multiplication one column at a time
  844. // column 0
  845. real_t sh0_x = sh0 * m00;
  846. real_t sh0_y = sh0 * m10;
  847. real_t d0 = sh0_x * m10;
  848. real_t d1 = sh0_y * m20;
  849. real_t d2 = sh0 * (m20 * m20 + s_c4_div_c3);
  850. real_t d3 = sh0_x * m20;
  851. real_t d4 = sh0_x * m00 - sh0_y * m10;
  852. // column 1
  853. real_t sh1_x = sh1 * m02;
  854. real_t sh1_y = sh1 * m12;
  855. d0 += sh1_x * m12;
  856. d1 += sh1_y * m22;
  857. d2 += sh1 * (m22 * m22 + s_c4_div_c3);
  858. d3 += sh1_x * m22;
  859. d4 += sh1_x * m02 - sh1_y * m12;
  860. // column 2
  861. real_t sh2_x = sh2 * r2x;
  862. real_t sh2_y = sh2 * r2y;
  863. d0 += sh2_x * r2y;
  864. d1 += sh2_y * r2z;
  865. d2 += sh2 * (r2z * r2z + s_c4_div_c3_x2);
  866. d3 += sh2_x * r2z;
  867. d4 += sh2_x * r2x - sh2_y * r2y;
  868. // column 3
  869. real_t sh3_x = sh3 * r3x;
  870. real_t sh3_y = sh3 * r3y;
  871. d0 += sh3_x * r3y;
  872. d1 += sh3_y * r3z;
  873. d2 += sh3 * (r3z * r3z + s_c4_div_c3_x2);
  874. d3 += sh3_x * r3z;
  875. d4 += sh3_x * r3x - sh3_y * r3y;
  876. // column 4
  877. real_t sh4_x = sh4 * r4x;
  878. real_t sh4_y = sh4 * r4y;
  879. d0 += sh4_x * r4y;
  880. d1 += sh4_y * r4z;
  881. d2 += sh4 * (r4z * r4z + s_c4_div_c3_x2);
  882. d3 += sh4_x * r4z;
  883. d4 += sh4_x * r4x - sh4_y * r4y;
  884. // extra multipliers
  885. p_values[4] = d0;
  886. p_values[5] = -d1;
  887. p_values[6] = d2 * s_scale_dst2;
  888. p_values[7] = -d3;
  889. p_values[8] = d4 * s_scale_dst4;
  890. }
  891. Basis Basis::looking_at(const Vector3 &p_target, const Vector3 &p_up, bool p_use_model_front) {
  892. #ifdef MATH_CHECKS
  893. ERR_FAIL_COND_V_MSG(p_target.is_zero_approx(), Basis(), "The target vector can't be zero.");
  894. ERR_FAIL_COND_V_MSG(p_up.is_zero_approx(), Basis(), "The up vector can't be zero.");
  895. #endif
  896. Vector3 v_z = p_target.normalized();
  897. if (!p_use_model_front) {
  898. v_z = -v_z;
  899. }
  900. Vector3 v_x = p_up.cross(v_z);
  901. #ifdef MATH_CHECKS
  902. ERR_FAIL_COND_V_MSG(v_x.is_zero_approx(), Basis(), "The target vector and up vector can't be parallel to each other.");
  903. #endif
  904. v_x.normalize();
  905. Vector3 v_y = v_z.cross(v_x);
  906. Basis basis;
  907. basis.set_columns(v_x, v_y, v_z);
  908. return basis;
  909. }