basis.cpp 33 KB

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