basis.cpp 31 KB

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