Quaternion.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace BansheeEngine
  4. {
  5. [StructLayout(LayoutKind.Sequential), SerializeObject]
  6. public struct Quaternion
  7. {
  8. private struct EulerAngleOrderData
  9. {
  10. public EulerAngleOrderData(int a, int b, int c)
  11. {
  12. this.a = a;
  13. this.b = b;
  14. this.c = c;
  15. }
  16. public int a, b, c;
  17. };
  18. public static readonly Quaternion zero = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
  19. public static readonly Quaternion identity = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
  20. private static readonly float epsilon = 1e-03f;
  21. private static readonly EulerAngleOrderData[] EA_LOOKUP = new EulerAngleOrderData[6]
  22. { new EulerAngleOrderData(0, 1, 2), new EulerAngleOrderData(0, 2, 1), new EulerAngleOrderData(1, 0, 2),
  23. new EulerAngleOrderData(1, 2, 0), new EulerAngleOrderData(2, 0, 1), new EulerAngleOrderData(2, 1, 0) };
  24. public float x;
  25. public float y;
  26. public float z;
  27. public float w;
  28. public float this[int index]
  29. {
  30. get
  31. {
  32. switch (index)
  33. {
  34. case 0:
  35. return x;
  36. case 1:
  37. return y;
  38. case 2:
  39. return z;
  40. case 3:
  41. return w;
  42. default:
  43. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  44. }
  45. }
  46. set
  47. {
  48. switch (index)
  49. {
  50. case 0:
  51. x = value;
  52. break;
  53. case 1:
  54. y = value;
  55. break;
  56. case 2:
  57. z = value;
  58. break;
  59. case 3:
  60. w = value;
  61. break;
  62. default:
  63. throw new IndexOutOfRangeException("Invalid Quaternion index.");
  64. }
  65. }
  66. }
  67. public Vector3 Right
  68. {
  69. get
  70. {
  71. float fTy = 2.0f*y;
  72. float fTz = 2.0f*z;
  73. float fTwy = fTy*w;
  74. float fTwz = fTz*w;
  75. float fTxy = fTy*x;
  76. float fTxz = fTz*x;
  77. float fTyy = fTy*y;
  78. float fTzz = fTz*z;
  79. return new Vector3(1.0f - (fTyy + fTzz), fTxy + fTwz, fTxz - fTwy);
  80. }
  81. }
  82. public Vector3 Up
  83. {
  84. get
  85. {
  86. float fTx = 2.0f * x;
  87. float fTy = 2.0f * y;
  88. float fTz = 2.0f * z;
  89. float fTwx = fTx * w;
  90. float fTwz = fTz * w;
  91. float fTxx = fTx * x;
  92. float fTxy = fTy * x;
  93. float fTyz = fTz * y;
  94. float fTzz = fTz * z;
  95. return new Vector3(fTxy - fTwz, 1.0f - (fTxx + fTzz), fTyz + fTwx);
  96. }
  97. }
  98. public Vector3 Forward
  99. {
  100. get
  101. {
  102. float fTx = 2.0f * x;
  103. float fTy = 2.0f * y;
  104. float fTz = 2.0f * z;
  105. float fTwx = fTx * w;
  106. float fTwy = fTy * w;
  107. float fTxx = fTx * x;
  108. float fTxz = fTz * x;
  109. float fTyy = fTy * y;
  110. float fTyz = fTz * y;
  111. return new Vector3(fTxz + fTwy, fTyz - fTwx, 1.0f - (fTxx + fTyy));
  112. }
  113. }
  114. public Quaternion Inverse
  115. {
  116. get
  117. {
  118. Quaternion copy = this;
  119. copy.Invert();
  120. return copy;
  121. }
  122. }
  123. public Quaternion Normalized
  124. {
  125. get
  126. {
  127. Quaternion copy = this;
  128. copy.Normalize();
  129. return copy;
  130. }
  131. }
  132. public Quaternion(float x, float y, float z, float w)
  133. {
  134. this.x = x;
  135. this.y = y;
  136. this.z = z;
  137. this.w = w;
  138. }
  139. public static Quaternion operator* (Quaternion lhs, Quaternion rhs)
  140. {
  141. return new Quaternion((lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y),
  142. (lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z),
  143. (lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x),
  144. (lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z));
  145. }
  146. public static Quaternion operator* (float lhs, Quaternion rhs)
  147. {
  148. return new Quaternion(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w);
  149. }
  150. public static Quaternion operator+ (Quaternion lhs, Quaternion rhs)
  151. {
  152. return new Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
  153. }
  154. public static Quaternion operator- (Quaternion lhs, Quaternion rhs)
  155. {
  156. return new Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
  157. }
  158. public static Quaternion operator- (Quaternion quat)
  159. {
  160. return new Quaternion(-quat.x, -quat.y, -quat.z, -quat.w);
  161. }
  162. public static bool operator== (Quaternion lhs, Quaternion rhs)
  163. {
  164. return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
  165. }
  166. public static bool operator!= (Quaternion lhs, Quaternion rhs)
  167. {
  168. return !(lhs == rhs);
  169. }
  170. public static float Dot(Quaternion a, Quaternion b)
  171. {
  172. return (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
  173. }
  174. public Vector3 Rotate(Vector3 point)
  175. {
  176. return ToRotationMatrix().Transform(point);
  177. }
  178. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection)
  179. {
  180. SetFromToRotation(fromDirection, toDirection, Vector3.zero);
  181. }
  182. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  183. {
  184. fromDirection.Normalize();
  185. toDirection.Normalize();
  186. float d = Vector3.Dot(fromDirection, toDirection);
  187. // If dot == 1, vectors are the same
  188. if (d >= 1.0f)
  189. {
  190. this = identity;
  191. return;
  192. }
  193. if (d < (1e-6f - 1.0f))
  194. {
  195. if (fallbackAxis != Vector3.zero)
  196. {
  197. // Rotate 180 degrees about the fallback axis
  198. this = FromAxisAngle(fallbackAxis, MathEx.Pi * MathEx.Rad2Deg);
  199. }
  200. else
  201. {
  202. // Generate an axis
  203. Vector3 axis = Vector3.Cross(Vector3.xAxis, fromDirection);
  204. if (axis.SqrdMagnitude < ((1e-06f * 1e-06f))) // Pick another if collinear
  205. axis = Vector3.Cross(Vector3.yAxis, fromDirection);
  206. axis.Normalize();
  207. this = FromAxisAngle(axis, MathEx.Pi * MathEx.Rad2Deg);
  208. }
  209. }
  210. else
  211. {
  212. float s = MathEx.Sqrt((1+d)*2);
  213. float invs = 1 / s;
  214. Vector3 c = Vector3.Cross(fromDirection, toDirection);
  215. x = c.x * invs;
  216. y = c.y * invs;
  217. z = c.z * invs;
  218. w = s * 0.5f;
  219. Normalize();
  220. }
  221. }
  222. public float Normalize()
  223. {
  224. float len = w*w+x*x+y*y+z*z;
  225. float factor = 1.0f / (float)MathEx.Sqrt(len);
  226. x *= factor;
  227. y *= factor;
  228. z *= factor;
  229. w *= factor;
  230. return len;
  231. }
  232. public void Invert()
  233. {
  234. float fNorm = w * w + x * x + y * y + z * z;
  235. if (fNorm > 0.0f)
  236. {
  237. float fInvNorm = 1.0f / fNorm;
  238. x *= -fInvNorm;
  239. y *= -fInvNorm;
  240. z *= -fInvNorm;
  241. w *= fInvNorm;
  242. }
  243. else
  244. {
  245. this = zero;
  246. }
  247. }
  248. public void SetLookRotation(Vector3 forward)
  249. {
  250. SetLookRotation(forward, Vector3.yAxis);
  251. }
  252. public void SetLookRotation(Vector3 forward, Vector3 up)
  253. {
  254. Quaternion forwardRot = FromToRotation(Vector3.zAxis, forward);
  255. Quaternion upRot = FromToRotation(Vector3.yAxis, up);
  256. this = forwardRot * upRot;
  257. }
  258. public static Quaternion Slerp(Quaternion from, Quaternion to, float t, bool shortestPath = false)
  259. {
  260. float cos = from.w*to.w + from.x*to.x + from.y*to.y + from.z*from.z;
  261. Quaternion quat;
  262. if (cos < 0.0f && shortestPath)
  263. {
  264. cos = -cos;
  265. quat = -to;
  266. }
  267. else
  268. {
  269. quat = to;
  270. }
  271. if (MathEx.Abs(cos) < (1 - epsilon))
  272. {
  273. // Standard case (slerp)
  274. float sin = MathEx.Sqrt(1 - (cos*cos));
  275. float angle = MathEx.Atan2(sin, cos);
  276. float invSin = 1.0f / sin;
  277. float coeff0 = MathEx.Sin((1.0f - t) * angle) * invSin;
  278. float coeff1 = MathEx.Sin(t * angle) * invSin;
  279. return coeff0 * from + coeff1 * quat;
  280. }
  281. else
  282. {
  283. // There are two situations:
  284. // 1. "p" and "q" are very close (fCos ~= +1), so we can do a linear
  285. // interpolation safely.
  286. // 2. "p" and "q" are almost inverse of each other (fCos ~= -1), there
  287. // are an infinite number of possibilities interpolation. but we haven't
  288. // have method to fix this case, so just use linear interpolation here.
  289. Quaternion ret = (1.0f - t) * from + t * quat;
  290. // Taking the complement requires renormalization
  291. ret.Normalize();
  292. return ret;
  293. }
  294. }
  295. public static Quaternion RotateTowards(Quaternion from, Quaternion to, Degree maxDeg)
  296. {
  297. Degree num = Angle(from, to);
  298. if (num == 0.0f)
  299. return to;
  300. float t = MathEx.Min(1f, (float)(maxDeg / num));
  301. return Slerp(from, to, t);
  302. }
  303. public static Quaternion Invert(Quaternion rotation)
  304. {
  305. Quaternion copy = rotation;
  306. copy.Invert();
  307. return copy;
  308. }
  309. public static Degree Angle(Quaternion a, Quaternion b)
  310. {
  311. return (MathEx.Acos(MathEx.Min(MathEx.Abs(Dot(a, b)), 1.0f)) * 2.0f * MathEx.Rad2Deg);
  312. }
  313. public void ToAxisAngle(out Vector3 axis, out Degree angle)
  314. {
  315. float fSqrLength = x*x+y*y+z*z;
  316. if (fSqrLength > 0.0f)
  317. {
  318. angle = 2.0f * MathEx.Acos(w) * MathEx.Rad2Deg;
  319. float fInvLength = MathEx.InvSqrt(fSqrLength);
  320. axis.x = x*fInvLength;
  321. axis.y = y*fInvLength;
  322. axis.z = z*fInvLength;
  323. }
  324. else
  325. {
  326. // Angle is 0, so any axis will do
  327. angle = 0.0f;
  328. axis.x = 1.0f;
  329. axis.y = 0.0f;
  330. axis.z = 0.0f;
  331. }
  332. }
  333. // Returns angles in degrees
  334. public Vector3 ToEuler()
  335. {
  336. Matrix3 matRot = ToRotationMatrix();
  337. return matRot.ToEulerAngles();
  338. }
  339. public Matrix3 ToRotationMatrix()
  340. {
  341. Matrix3 mat = new Matrix3();
  342. float tx = x + x;
  343. float ty = y + y;
  344. float fTz = z + z;
  345. float twx = tx * w;
  346. float twy = ty * w;
  347. float twz = fTz * w;
  348. float txx = tx * x;
  349. float txy = ty * x;
  350. float txz = fTz * x;
  351. float tyy = ty * y;
  352. float tyz = fTz * y;
  353. float tzz = fTz * z;
  354. mat[0, 0] = 1.0f - (tyy + tzz);
  355. mat[0, 1] = txy - twz;
  356. mat[0, 2] = txz + twy;
  357. mat[1, 0] = txy + twz;
  358. mat[1, 1] = 1.0f - (txx + tzz);
  359. mat[1, 2] = tyz - twx;
  360. mat[2, 0] = txz - twy;
  361. mat[2, 1] = tyz + twx;
  362. mat[2, 2] = 1.0f - (txx + tyy);
  363. return mat;
  364. }
  365. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection)
  366. {
  367. Quaternion q = new Quaternion();
  368. q.SetFromToRotation(fromDirection, toDirection);
  369. return q;
  370. }
  371. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  372. {
  373. Quaternion q = new Quaternion();
  374. q.SetFromToRotation(fromDirection, toDirection, fallbackAxis);
  375. return q;
  376. }
  377. public static Quaternion LookRotation(Vector3 forward)
  378. {
  379. Quaternion quat = new Quaternion();
  380. quat.SetLookRotation(forward);
  381. return quat;
  382. }
  383. public static Quaternion LookRotation(Vector3 forward, Vector3 up)
  384. {
  385. Quaternion quat = new Quaternion();
  386. quat.SetLookRotation(forward, up);
  387. return quat;
  388. }
  389. public static Vector3 ToEuler(Quaternion rotation)
  390. {
  391. return rotation.ToEuler();
  392. }
  393. public static void ToAxisAngle(Quaternion rotation, out Vector3 axis, out Degree angleDeg)
  394. {
  395. rotation.ToAxisAngle(out axis, out angleDeg);
  396. }
  397. public static Quaternion FromRotationMatrix(Matrix3 rotMatrix)
  398. {
  399. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  400. // article "Quaternion Calculus and Fast Animation".
  401. Quaternion quat = new Quaternion();
  402. float trace = rotMatrix.m00 + rotMatrix.m11 + rotMatrix.m22;
  403. float root;
  404. if (trace > 0.0f)
  405. {
  406. // |w| > 1/2, may as well choose w > 1/2
  407. root = MathEx.Sqrt(trace + 1.0f); // 2w
  408. quat.w = 0.5f*root;
  409. root = 0.5f/root; // 1/(4w)
  410. quat.x = (rotMatrix.m21 - rotMatrix.m12) * root;
  411. quat.y = (rotMatrix.m02 - rotMatrix.m20) * root;
  412. quat.z = (rotMatrix.m10 - rotMatrix.m01) * root;
  413. }
  414. else
  415. {
  416. // |w| <= 1/2
  417. int[] nextLookup = { 1, 2, 0 };
  418. int i = 0;
  419. if (rotMatrix.m11 > rotMatrix.m00)
  420. i = 1;
  421. if (rotMatrix.m22 > rotMatrix[i, i])
  422. i = 2;
  423. int j = nextLookup[i];
  424. int k = nextLookup[j];
  425. root = MathEx.Sqrt(rotMatrix[i,i] - rotMatrix[j, j] - rotMatrix[k, k] + 1.0f);
  426. quat[i] = 0.5f*root;
  427. root = 0.5f/root;
  428. quat.w = (rotMatrix[k, j] - rotMatrix[j, k]) * root;
  429. quat[j] = (rotMatrix[j, i] + rotMatrix[i, j]) * root;
  430. quat[k] = (rotMatrix[k, i] + rotMatrix[i, k]) * root;
  431. }
  432. quat.Normalize();
  433. return quat;
  434. }
  435. public static Quaternion FromAxisAngle(Vector3 axis, Degree angleDeg)
  436. {
  437. Quaternion quat;
  438. float halfAngle = (float)(0.5f*angleDeg*MathEx.Deg2Rad);
  439. float sin = (float)MathEx.Sin(halfAngle);
  440. quat.w = (float)MathEx.Cos(halfAngle);
  441. quat.x = sin * axis.x;
  442. quat.y = sin * axis.y;
  443. quat.z = sin * axis.z;
  444. return quat;
  445. }
  446. public static Quaternion FromEuler(Degree xDeg, Degree yDeg, Degree zDeg, EulerAngleOrder order = EulerAngleOrder.YXZ)
  447. {
  448. EulerAngleOrderData l = EA_LOOKUP[(int)order];
  449. Radian halfXAngle = xDeg * 0.5f;
  450. Radian halfYAngle = yDeg * 0.5f;
  451. Radian halfZAngle = zDeg * 0.5f;
  452. float cx = MathEx.Cos(halfXAngle);
  453. float sx = MathEx.Sin(halfXAngle);
  454. float cy = MathEx.Cos(halfYAngle);
  455. float sy = MathEx.Sin(halfYAngle);
  456. float cz = MathEx.Cos(halfZAngle);
  457. float sz = MathEx.Sin(halfZAngle);
  458. Quaternion[] quats = new Quaternion[3];
  459. quats[0] = new Quaternion(sx, 0.0f, 0.0f, cx);
  460. quats[1] = new Quaternion(0.0f, sy, 0.0f, cy);
  461. quats[2] = new Quaternion(0.0f, 0.0f, sz, cz);
  462. return (quats[l.a] * quats[l.b]) * quats[l.c];
  463. }
  464. /**
  465. * @note Angles in degrees.
  466. */
  467. public static Quaternion FromEuler(Vector3 euler, EulerAngleOrder order = EulerAngleOrder.YXZ)
  468. {
  469. return FromEuler(euler.x, euler.y, euler.z, order);
  470. }
  471. public override int GetHashCode()
  472. {
  473. return x.GetHashCode() ^ y.GetHashCode() << 2 ^ z.GetHashCode() >> 2 ^ w.GetHashCode() >> 1;
  474. }
  475. public override bool Equals(object other)
  476. {
  477. if (!(other is Quaternion))
  478. return false;
  479. Quaternion quat = (Quaternion)other;
  480. if (x.Equals(quat.x) && y.Equals(quat.y) && z.Equals(quat.z) && w.Equals(quat.w))
  481. return true;
  482. return false;
  483. }
  484. public override string ToString()
  485. {
  486. return String.Format("({0}, {1}, {2}, {3})", x, y, z, w);
  487. }
  488. }
  489. }