Quaternion.cs 27 KB

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