Quaternion.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Runtime.InteropServices;
  5. namespace BansheeEngine
  6. {
  7. /// <summary>
  8. /// Quaternion used for representing rotations.
  9. /// </summary>
  10. [StructLayout(LayoutKind.Sequential), SerializeObject]
  11. public struct Quaternion // Note: Must match C++ class Quaternion
  12. {
  13. /// <summary>
  14. /// Contains constant data that is used when calculating euler angles in a certain order.
  15. /// </summary>
  16. private struct EulerAngleOrderData
  17. {
  18. public EulerAngleOrderData(int a, int b, int c)
  19. {
  20. this.a = a;
  21. this.b = b;
  22. this.c = c;
  23. }
  24. public int a, b, c;
  25. };
  26. /// <summary>
  27. /// Quaternion with all zero elements.
  28. /// </summary>
  29. public static readonly Quaternion Zero = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
  30. /// <summary>
  31. /// Quaternion representing no rotation.
  32. /// </summary>
  33. public static readonly Quaternion Identity = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
  34. private static readonly float epsilon = 1e-03f;
  35. private static readonly EulerAngleOrderData[] EA_LOOKUP = new EulerAngleOrderData[6]
  36. { new EulerAngleOrderData(0, 1, 2), new EulerAngleOrderData(0, 2, 1), new EulerAngleOrderData(1, 0, 2),
  37. new EulerAngleOrderData(1, 2, 0), new EulerAngleOrderData(2, 0, 1), new EulerAngleOrderData(2, 1, 0) };
  38. public float x;
  39. public float y;
  40. public float z;
  41. public float w;
  42. /// <summary>
  43. /// Accesses a specific component of the quaternion.
  44. /// </summary>
  45. /// <param name="index">Index of the component (0 - x, 1 - y, 2 - z, 3 - w).</param>
  46. /// <returns>Value of the specific component.</returns>
  47. public float this[int index]
  48. {
  49. get
  50. {
  51. switch (index)
  52. {
  53. case 0:
  54. return x;
  55. case 1:
  56. return y;
  57. case 2:
  58. return z;
  59. case 3:
  60. return w;
  61. default:
  62. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  63. }
  64. }
  65. set
  66. {
  67. switch (index)
  68. {
  69. case 0:
  70. x = value;
  71. break;
  72. case 1:
  73. y = value;
  74. break;
  75. case 2:
  76. z = value;
  77. break;
  78. case 3:
  79. w = value;
  80. break;
  81. default:
  82. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  83. }
  84. }
  85. }
  86. /// <summary>
  87. /// Gets the positive x-axis of the coordinate system transformed by this quaternion.
  88. /// </summary>
  89. public Vector3 Right
  90. {
  91. get
  92. {
  93. float fTy = 2.0f*y;
  94. float fTz = 2.0f*z;
  95. float fTwy = fTy*w;
  96. float fTwz = fTz*w;
  97. float fTxy = fTy*x;
  98. float fTxz = fTz*x;
  99. float fTyy = fTy*y;
  100. float fTzz = fTz*z;
  101. return new Vector3(1.0f - (fTyy + fTzz), fTxy + fTwz, fTxz - fTwy);
  102. }
  103. }
  104. /// <summary>
  105. /// Gets the positive y-axis of the coordinate system transformed by this quaternion.
  106. /// </summary>
  107. public Vector3 Up
  108. {
  109. get
  110. {
  111. float fTx = 2.0f * x;
  112. float fTy = 2.0f * y;
  113. float fTz = 2.0f * z;
  114. float fTwx = fTx * w;
  115. float fTwz = fTz * w;
  116. float fTxx = fTx * x;
  117. float fTxy = fTy * x;
  118. float fTyz = fTz * y;
  119. float fTzz = fTz * z;
  120. return new Vector3(fTxy - fTwz, 1.0f - (fTxx + fTzz), fTyz + fTwx);
  121. }
  122. }
  123. /// <summary>
  124. /// Gets the positive z-axis of the coordinate system transformed by this quaternion.
  125. /// </summary>
  126. public Vector3 Forward
  127. {
  128. get
  129. {
  130. float fTx = 2.0f * x;
  131. float fTy = 2.0f * y;
  132. float fTz = 2.0f * z;
  133. float fTwx = fTx * w;
  134. float fTwy = fTy * w;
  135. float fTxx = fTx * x;
  136. float fTxz = fTz * x;
  137. float fTyy = fTy * y;
  138. float fTyz = fTz * y;
  139. return new Vector3(fTxz + fTwy, fTyz - fTwx, 1.0f - (fTxx + fTyy));
  140. }
  141. }
  142. /// <summary>
  143. /// Returns the inverse of the quaternion. Quaternion must be non-zero. Inverse quaternion has the opposite
  144. /// rotation of the original.
  145. /// </summary>
  146. public Quaternion Inverse
  147. {
  148. get
  149. {
  150. Quaternion copy = this;
  151. copy.Invert();
  152. return copy;
  153. }
  154. }
  155. /// <summary>
  156. /// Returns a normalized copy of the quaternion.
  157. /// </summary>
  158. public Quaternion Normalized
  159. {
  160. get
  161. {
  162. Quaternion copy = this;
  163. copy.Normalize();
  164. return copy;
  165. }
  166. }
  167. /// <summary>
  168. /// Constructs a new quaternion with the specified components.
  169. /// </summary>
  170. public Quaternion(float x, float y, float z, float w)
  171. {
  172. this.x = x;
  173. this.y = y;
  174. this.z = z;
  175. this.w = w;
  176. }
  177. public static Quaternion operator* (Quaternion lhs, Quaternion rhs)
  178. {
  179. return new Quaternion((lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y),
  180. (lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z),
  181. (lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x),
  182. (lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z));
  183. }
  184. public static Quaternion operator* (float lhs, Quaternion rhs)
  185. {
  186. return new Quaternion(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w);
  187. }
  188. public static Quaternion operator+ (Quaternion lhs, Quaternion rhs)
  189. {
  190. return new Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
  191. }
  192. public static Quaternion operator- (Quaternion lhs, Quaternion rhs)
  193. {
  194. return new Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
  195. }
  196. public static Quaternion operator- (Quaternion quat)
  197. {
  198. return new Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  199. }
  200. public static bool operator== (Quaternion lhs, Quaternion rhs)
  201. {
  202. return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
  203. }
  204. public static bool operator!= (Quaternion lhs, Quaternion rhs)
  205. {
  206. return !(lhs == rhs);
  207. }
  208. /// <summary>
  209. /// Calculates a dot product between two quaternions.
  210. /// </summary>
  211. /// <param name="a">First quaternion.</param>
  212. /// <param name="b">Second quaternion.</param>
  213. /// <returns>Dot product between the two quaternions.</returns>
  214. public static float Dot(Quaternion a, Quaternion b)
  215. {
  216. return (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
  217. }
  218. /// <summary>
  219. /// Applies quaternion rotation to the specified point.
  220. /// </summary>
  221. /// <param name="point">Point to rotate.</param>
  222. /// <returns>Point rotated by the quaternion.</returns>
  223. public Vector3 Rotate(Vector3 point)
  224. {
  225. return ToRotationMatrix().Transform(point);
  226. }
  227. /// <summary>
  228. /// Initializes the quaternion with rotation that rotates from one direction to another.
  229. /// </summary>
  230. /// <param name="fromDirection">Rotation to start at.</param>
  231. /// <param name="toDirection">Rotation to end at.</param>
  232. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection)
  233. {
  234. SetFromToRotation(fromDirection, toDirection, Vector3.Zero);
  235. }
  236. /// <summary>
  237. /// Initializes the quaternion with rotation that rotates from one direction to another.
  238. /// </summary>
  239. /// <param name="fromDirection">Rotation to start at.</param>
  240. /// <param name="toDirection">Rotation to end at.</param>
  241. /// <param name="fallbackAxis">Fallback axis to use if the from/to vectors are almost completely opposite.
  242. /// Fallback axis should be perpendicular to both vectors.</param>
  243. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  244. {
  245. fromDirection.Normalize();
  246. toDirection.Normalize();
  247. float d = Vector3.Dot(fromDirection, toDirection);
  248. // If dot == 1, vectors are the same
  249. if (d >= 1.0f)
  250. {
  251. this = Identity;
  252. return;
  253. }
  254. if (d < (1e-6f - 1.0f))
  255. {
  256. if (fallbackAxis != Vector3.Zero)
  257. {
  258. // Rotate 180 degrees about the fallback axis
  259. this = FromAxisAngle(fallbackAxis, MathEx.Pi);
  260. }
  261. else
  262. {
  263. // Generate an axis
  264. Vector3 axis = Vector3.Cross(Vector3.XAxis, fromDirection);
  265. if (axis.SqrdLength < ((1e-06f * 1e-06f))) // Pick another if collinear
  266. axis = Vector3.Cross(Vector3.YAxis, fromDirection);
  267. axis.Normalize();
  268. this = FromAxisAngle(axis, MathEx.Pi);
  269. }
  270. }
  271. else
  272. {
  273. float s = MathEx.Sqrt((1+d)*2);
  274. float invs = 1 / s;
  275. Vector3 c = Vector3.Cross(fromDirection, toDirection);
  276. x = c.x * invs;
  277. y = c.y * invs;
  278. z = c.z * invs;
  279. w = s * 0.5f;
  280. Normalize();
  281. }
  282. }
  283. /// <summary>
  284. /// Normalizes the quaternion.
  285. /// </summary>
  286. /// <returns>Length of the quaternion prior to normalization.</returns>
  287. public float Normalize()
  288. {
  289. float len = w*w+x*x+y*y+z*z;
  290. float factor = 1.0f / (float)MathEx.Sqrt(len);
  291. x *= factor;
  292. y *= factor;
  293. z *= factor;
  294. w *= factor;
  295. return len;
  296. }
  297. /// <summary>
  298. /// Calculates the inverse of the quaternion. Inverse quaternion has the opposite rotation of the original.
  299. /// </summary>
  300. public void Invert()
  301. {
  302. float fNorm = w * w + x * x + y * y + z * z;
  303. if (fNorm > 0.0f)
  304. {
  305. float fInvNorm = 1.0f / fNorm;
  306. x *= -fInvNorm;
  307. y *= -fInvNorm;
  308. z *= -fInvNorm;
  309. w *= fInvNorm;
  310. }
  311. else
  312. {
  313. this = Zero;
  314. }
  315. }
  316. /// <summary>
  317. /// Initializes the quaternion so that it orients an object so it faces in te provided direction.
  318. /// </summary>
  319. /// <param name="forward">Direction to orient the object towards.</param>
  320. public void SetLookRotation(Vector3 forward)
  321. {
  322. FromToRotation(-Vector3.ZAxis, forward);
  323. }
  324. /// <summary>
  325. /// Initializes the quaternion so that it orients an object so it faces in te provided direction.
  326. /// </summary>
  327. /// <param name="forward">Direction to orient the object towards.</param>
  328. /// <param name="up">Axis that determines the upward direction of the object.</param>
  329. public void SetLookRotation(Vector3 forward, Vector3 up)
  330. {
  331. Vector3 forwardNrm = Vector3.Normalize(forward);
  332. Vector3 upNrm = Vector3.Normalize(up);
  333. if (MathEx.ApproxEquals(Vector3.Dot(forwardNrm, upNrm), 1.0f))
  334. {
  335. SetLookRotation(forwardNrm);
  336. return;
  337. }
  338. Vector3 x = Vector3.Cross(forwardNrm, upNrm);
  339. Vector3 y = Vector3.Cross(x, forwardNrm);
  340. x.Normalize();
  341. y.Normalize();
  342. this = Quaternion.FromAxes(x, y, -forwardNrm);
  343. }
  344. /// <summary>
  345. /// Performs spherical interpolation between two quaternions. Spherical interpolation neatly interpolates between
  346. /// two rotations without modifying the size of the vector it is applied to (unlike linear interpolation).
  347. /// </summary>
  348. /// <param name="from">Start quaternion.</param>
  349. /// <param name="to">End quaternion.</param>
  350. /// <param name="t">Interpolation factor in range [0, 1] that determines how much to interpolate between
  351. /// <paramref name="from"/> and <paramref name="to"/>.</param>
  352. /// <param name="shortestPath">Should the interpolation be performed between the shortest or longest path between
  353. /// the two quaternions.</param>
  354. /// <returns>Interpolated quaternion representing a rotation between <paramref name="from"/> and
  355. /// <paramref name="to"/>.</returns>
  356. public static Quaternion Slerp(Quaternion from, Quaternion to, float t, bool shortestPath = true)
  357. {
  358. float dot = Dot(from, to);
  359. Quaternion quat;
  360. if (dot < 0.0f && shortestPath)
  361. {
  362. dot = -dot;
  363. quat = -to;
  364. }
  365. else
  366. {
  367. quat = to;
  368. }
  369. if (MathEx.Abs(dot) < (1 - epsilon))
  370. {
  371. float sin = MathEx.Sqrt(1 - (dot*dot));
  372. Radian angle = MathEx.Atan2(sin, dot);
  373. float invSin = 1.0f / sin;
  374. float a = MathEx.Sin((1.0f - t) * angle) * invSin;
  375. float b = MathEx.Sin(t * angle) * invSin;
  376. return a * from + b * quat;
  377. }
  378. else
  379. {
  380. Quaternion ret = (1.0f - t) * from + t * quat;
  381. ret.Normalize();
  382. return ret;
  383. }
  384. }
  385. /// <summary>
  386. /// Returns the inverse of the quaternion. Quaternion must be non-zero. Inverse quaternion has the opposite
  387. /// rotation of the original.
  388. /// </summary>
  389. /// <param name="rotation">Quaternion to calculate the inverse for.</param>
  390. /// <returns>Inverse of the provided quaternion.</returns>
  391. public static Quaternion Invert(Quaternion rotation)
  392. {
  393. Quaternion copy = rotation;
  394. copy.Invert();
  395. return copy;
  396. }
  397. /// <summary>
  398. /// Calculates an angle between two rotations.
  399. /// </summary>
  400. /// <param name="a">First rotation.</param>
  401. /// <param name="b">Second rotation.</param>
  402. /// <returns>Angle between the rotations, in degrees.</returns>
  403. public static Degree Angle(Quaternion a, Quaternion b)
  404. {
  405. return (MathEx.Acos(MathEx.Min(MathEx.Abs(Dot(a, b)), 1.0f)) * 2.0f);
  406. }
  407. /// <summary>
  408. /// Converts the quaternion rotation into axis/angle rotation.
  409. /// </summary>
  410. /// <param name="axis">Axis around which the rotation is performed.</param>
  411. /// <param name="angle">Amount of rotation.</param>
  412. public void ToAxisAngle(out Vector3 axis, out Degree angle)
  413. {
  414. float fSqrLength = x*x+y*y+z*z;
  415. if (fSqrLength > 0.0f)
  416. {
  417. angle = 2.0f * MathEx.Acos(w);
  418. float fInvLength = MathEx.InvSqrt(fSqrLength);
  419. axis.x = x*fInvLength;
  420. axis.y = y*fInvLength;
  421. axis.z = z*fInvLength;
  422. }
  423. else
  424. {
  425. // Angle is 0, so any axis will do
  426. angle = (Degree)0.0f;
  427. axis.x = 1.0f;
  428. axis.y = 0.0f;
  429. axis.z = 0.0f;
  430. }
  431. }
  432. /// <summary>
  433. /// Converts a quaternion into an orthonormal set of axes.
  434. /// </summary>
  435. /// <param name="xAxis">Output normalized x axis.</param>
  436. /// <param name="yAxis">Output normalized y axis.</param>
  437. /// <param name="zAxis">Output normalized z axis.</param>
  438. public void ToAxes(ref Vector3 xAxis, ref Vector3 yAxis, ref Vector3 zAxis)
  439. {
  440. Matrix3 matRot = ToRotationMatrix();
  441. xAxis.x = matRot[0, 0];
  442. xAxis.y = matRot[1, 0];
  443. xAxis.z = matRot[2, 0];
  444. yAxis.x = matRot[0, 1];
  445. yAxis.y = matRot[1, 1];
  446. yAxis.z = matRot[2, 1];
  447. zAxis.x = matRot[0, 2];
  448. zAxis.y = matRot[1, 2];
  449. zAxis.z = matRot[2, 2];
  450. }
  451. /// <summary>
  452. /// Converts the quaternion rotation into euler angle (pitch/yaw/roll) rotation.
  453. /// </summary>
  454. /// <returns>Rotation as euler angles, in degrees.</returns>
  455. public Vector3 ToEuler()
  456. {
  457. Matrix3 matRot = ToRotationMatrix();
  458. return matRot.ToEulerAngles();
  459. }
  460. /// <summary>
  461. /// Converts a quaternion rotation into a rotation matrix.
  462. /// </summary>
  463. /// <returns>Matrix representing the rotation.</returns>
  464. public Matrix3 ToRotationMatrix()
  465. {
  466. Matrix3 mat = new Matrix3();
  467. float tx = x + x;
  468. float ty = y + y;
  469. float fTz = z + z;
  470. float twx = tx * w;
  471. float twy = ty * w;
  472. float twz = fTz * w;
  473. float txx = tx * x;
  474. float txy = ty * x;
  475. float txz = fTz * x;
  476. float tyy = ty * y;
  477. float tyz = fTz * y;
  478. float tzz = fTz * z;
  479. mat[0, 0] = 1.0f - (tyy + tzz);
  480. mat[0, 1] = txy - twz;
  481. mat[0, 2] = txz + twy;
  482. mat[1, 0] = txy + twz;
  483. mat[1, 1] = 1.0f - (txx + tzz);
  484. mat[1, 2] = tyz - twx;
  485. mat[2, 0] = txz - twy;
  486. mat[2, 1] = tyz + twx;
  487. mat[2, 2] = 1.0f - (txx + tyy);
  488. return mat;
  489. }
  490. /// <summary>
  491. /// Creates a quaternion with rotation that rotates from one direction to another.
  492. /// </summary>
  493. /// <param name="fromDirection">Rotation to start at.</param>
  494. /// <param name="toDirection">Rotation to end at.</param>
  495. /// <returns>Quaternion that rotates an object from <paramref name="fromDirection"/> to
  496. /// <paramref name="toDirection"/></returns>
  497. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection)
  498. {
  499. Quaternion q = new Quaternion();
  500. q.SetFromToRotation(fromDirection, toDirection);
  501. return q;
  502. }
  503. /// <summary>
  504. /// Creates a quaternion with rotation that rotates from one direction to another.
  505. /// </summary>
  506. /// <param name="fromDirection">Rotation to start at.</param>
  507. /// <param name="toDirection">Rotation to end at.</param>
  508. /// <param name="fallbackAxis">Fallback axis to use if the from/to vectors are almost completely opposite.
  509. /// Fallback axis should be perpendicular to both vectors.</param>
  510. /// <returns>Quaternion that rotates an object from <paramref name="fromDirection"/> to
  511. /// <paramref name="toDirection"/></returns>
  512. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  513. {
  514. Quaternion q = new Quaternion();
  515. q.SetFromToRotation(fromDirection, toDirection, fallbackAxis);
  516. return q;
  517. }
  518. /// <summary>
  519. /// Creates a quaternion that orients an object so it faces in te provided direction.
  520. /// </summary>
  521. /// <param name="forward">Direction to orient the object towards.</param>
  522. public static Quaternion LookRotation(Vector3 forward)
  523. {
  524. Quaternion quat = new Quaternion();
  525. quat.SetLookRotation(forward);
  526. return quat;
  527. }
  528. /// <summary>
  529. /// Creates a quaternion that orients an object so it faces in te provided direction.
  530. /// </summary>
  531. /// <param name="forward">Direction to orient the object towards.</param>
  532. /// <param name="up">Axis that determines the upward direction of the object.</param>
  533. public static Quaternion LookRotation(Vector3 forward, Vector3 up)
  534. {
  535. Quaternion quat = new Quaternion();
  536. quat.SetLookRotation(forward, up);
  537. return quat;
  538. }
  539. /// <summary>
  540. /// Converts the quaternion rotation into euler angle (pitch/yaw/roll) rotation.
  541. /// </summary>
  542. /// <param name="rotation">Quaternion to convert.</param>
  543. /// <returns>Rotation as euler angles, in degrees.</returns>
  544. public static Vector3 ToEuler(Quaternion rotation)
  545. {
  546. return rotation.ToEuler();
  547. }
  548. /// <summary>
  549. /// Converts the quaternion rotation into axis/angle rotation.
  550. /// </summary>
  551. /// <param name="rotation">Quaternion to convert.</param>
  552. /// <param name="axis">Axis around which the rotation is performed.</param>
  553. /// <param name="angle">Amount of rotation.</param>
  554. public static void ToAxisAngle(Quaternion rotation, out Vector3 axis, out Degree angle)
  555. {
  556. rotation.ToAxisAngle(out axis, out angle);
  557. }
  558. /// <summary>
  559. /// Creates a quaternion from a rotation matrix.
  560. /// </summary>
  561. /// <param name="rotMatrix">Rotation matrix to convert to quaternion.</param>
  562. /// <returns>Newly created quaternion that has equivalent rotation as the provided rotation matrix.</returns>
  563. public static Quaternion FromRotationMatrix(Matrix3 rotMatrix)
  564. {
  565. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  566. // article "Quaternion Calculus and Fast Animation".
  567. Quaternion quat = new Quaternion();
  568. float trace = rotMatrix.m00 + rotMatrix.m11 + rotMatrix.m22;
  569. float root;
  570. if (trace > 0.0f)
  571. {
  572. // |w| > 1/2, may as well choose w > 1/2
  573. root = MathEx.Sqrt(trace + 1.0f); // 2w
  574. quat.w = 0.5f*root;
  575. root = 0.5f/root; // 1/(4w)
  576. quat.x = (rotMatrix.m21 - rotMatrix.m12) * root;
  577. quat.y = (rotMatrix.m02 - rotMatrix.m20) * root;
  578. quat.z = (rotMatrix.m10 - rotMatrix.m01) * root;
  579. }
  580. else
  581. {
  582. // |w| <= 1/2
  583. int[] nextLookup = { 1, 2, 0 };
  584. int i = 0;
  585. if (rotMatrix.m11 > rotMatrix.m00)
  586. i = 1;
  587. if (rotMatrix.m22 > rotMatrix[i, i])
  588. i = 2;
  589. int j = nextLookup[i];
  590. int k = nextLookup[j];
  591. root = MathEx.Sqrt(rotMatrix[i,i] - rotMatrix[j, j] - rotMatrix[k, k] + 1.0f);
  592. quat[i] = 0.5f*root;
  593. root = 0.5f/root;
  594. quat.w = (rotMatrix[k, j] - rotMatrix[j, k]) * root;
  595. quat[j] = (rotMatrix[j, i] + rotMatrix[i, j]) * root;
  596. quat[k] = (rotMatrix[k, i] + rotMatrix[i, k]) * root;
  597. }
  598. quat.Normalize();
  599. return quat;
  600. }
  601. /// <summary>
  602. /// Creates a quaternion from axis/angle rotation.
  603. /// </summary>
  604. /// <param name="axis">Axis around which the rotation is performed.</param>
  605. /// <param name="angle">Amount of rotation.</param>
  606. /// <returns>Quaternion that rotates an object around the specified axis for the specified amount.</returns>
  607. public static Quaternion FromAxisAngle(Vector3 axis, Degree angle)
  608. {
  609. Quaternion quat;
  610. float halfAngle = (float)(0.5f*angle.Radians);
  611. float sin = (float)MathEx.Sin(halfAngle);
  612. quat.w = (float)MathEx.Cos(halfAngle);
  613. quat.x = sin * axis.x;
  614. quat.y = sin * axis.y;
  615. quat.z = sin * axis.z;
  616. return quat;
  617. }
  618. /// <summary>
  619. /// Initializes the quaternion from orthonormal set of axes.
  620. /// </summary>
  621. /// <param name="xAxis">Normalized x axis.</param>
  622. /// <param name="yAxis">Normalized y axis.</param>
  623. /// <param name="zAxis">Normalized z axis.</param>
  624. /// <returns>Quaternion that represents a rotation from base axes to the specified set of axes.</returns>
  625. public static Quaternion FromAxes(Vector3 xAxis, Vector3 yAxis, Vector3 zAxis)
  626. {
  627. Matrix3 mat;
  628. mat.m00 = xAxis.x;
  629. mat.m10 = xAxis.y;
  630. mat.m20 = xAxis.z;
  631. mat.m01 = yAxis.x;
  632. mat.m11 = yAxis.y;
  633. mat.m21 = yAxis.z;
  634. mat.m02 = zAxis.x;
  635. mat.m12 = zAxis.y;
  636. mat.m22 = zAxis.z;
  637. return FromRotationMatrix(mat);
  638. }
  639. /// <summary>
  640. /// Creates a quaternion from the provided euler angle (pitch/yaw/roll) rotation.
  641. /// </summary>
  642. /// <param name="xAngle">Pitch angle of rotation.</param>
  643. /// <param name="yAngle">Yar angle of rotation.</param>
  644. /// <param name="zAngle">Roll angle of rotation.</param>
  645. /// <param name="order">The order in which rotations will be applied. Different rotations can be created depending
  646. /// on the order.</param>
  647. /// <returns>Quaternion that can rotate an object to the specified angles.</returns>
  648. public static Quaternion FromEuler(Degree xAngle, Degree yAngle, Degree zAngle,
  649. EulerAngleOrder order = EulerAngleOrder.YXZ)
  650. {
  651. EulerAngleOrderData l = EA_LOOKUP[(int)order];
  652. Radian halfXAngle = xAngle * 0.5f;
  653. Radian halfYAngle = yAngle * 0.5f;
  654. Radian halfZAngle = zAngle * 0.5f;
  655. float cx = MathEx.Cos(halfXAngle);
  656. float sx = MathEx.Sin(halfXAngle);
  657. float cy = MathEx.Cos(halfYAngle);
  658. float sy = MathEx.Sin(halfYAngle);
  659. float cz = MathEx.Cos(halfZAngle);
  660. float sz = MathEx.Sin(halfZAngle);
  661. Quaternion[] quats = new Quaternion[3];
  662. quats[0] = new Quaternion(sx, 0.0f, 0.0f, cx);
  663. quats[1] = new Quaternion(0.0f, sy, 0.0f, cy);
  664. quats[2] = new Quaternion(0.0f, 0.0f, sz, cz);
  665. return (quats[l.a] * quats[l.b]) * quats[l.c];
  666. }
  667. /// <summary>
  668. /// Creates a quaternion from the provided euler angle (pitch/yaw/roll) rotation.
  669. /// </summary>
  670. /// <param name="euler">Euler angles in degrees.</param>
  671. /// <param name="order">The order in which rotations will be applied. Different rotations can be created depending
  672. /// on the order.</param>
  673. /// <returns>Quaternion that can rotate an object to the specified angles.</returns>
  674. public static Quaternion FromEuler(Vector3 euler, EulerAngleOrder order = EulerAngleOrder.YXZ)
  675. {
  676. return FromEuler((Degree)euler.x, (Degree)euler.y, (Degree)euler.z, order);
  677. }
  678. /// <inheritdoc/>
  679. public override int GetHashCode()
  680. {
  681. return x.GetHashCode() ^ y.GetHashCode() << 2 ^ z.GetHashCode() >> 2 ^ w.GetHashCode() >> 1;
  682. }
  683. /// <inheritdoc/>
  684. public override bool Equals(object other)
  685. {
  686. if (!(other is Quaternion))
  687. return false;
  688. Quaternion quat = (Quaternion)other;
  689. if (x.Equals(quat.x) && y.Equals(quat.y) && z.Equals(quat.z) && w.Equals(quat.w))
  690. return true;
  691. return false;
  692. }
  693. /// <inheritdoc/>
  694. public override string ToString()
  695. {
  696. return String.Format("({0}, {1}, {2}, {3})", x, y, z, w);
  697. }
  698. }
  699. }