Quaternion.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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(float x, float y, float z, float w)
  115. {
  116. this.x = x;
  117. this.y = y;
  118. this.z = z;
  119. this.w = w;
  120. }
  121. public static Quaternion operator* (Quaternion lhs, Quaternion rhs)
  122. {
  123. return new Quaternion((lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y),
  124. (lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z),
  125. (lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x),
  126. (lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z));
  127. }
  128. public static Quaternion operator* (float lhs, Quaternion rhs)
  129. {
  130. return new Quaternion(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w);
  131. }
  132. public static Quaternion operator+ (Quaternion lhs, Quaternion rhs)
  133. {
  134. return new Quaternion(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
  135. }
  136. public static Quaternion operator- (Quaternion lhs, Quaternion rhs)
  137. {
  138. return new Quaternion(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
  139. }
  140. public static Quaternion operator- (Quaternion quat)
  141. {
  142. return new Quaternion(-quat.w, -quat.x, -quat.y, -quat.z);
  143. }
  144. public static bool operator== (Quaternion lhs, Quaternion rhs)
  145. {
  146. return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w;
  147. }
  148. public static bool operator!= (Quaternion lhs, Quaternion rhs)
  149. {
  150. return !(lhs == rhs);
  151. }
  152. public static float Dot(Quaternion a, Quaternion b)
  153. {
  154. return (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
  155. }
  156. public Vector3 Rotate(Vector3 point)
  157. {
  158. return ToRotationMatrix().Transform(point);
  159. }
  160. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection)
  161. {
  162. SetFromToRotation(fromDirection, toDirection, Vector3.zero);
  163. }
  164. public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  165. {
  166. fromDirection.Normalize();
  167. toDirection.Normalize();
  168. float d = Vector3.Dot(fromDirection, toDirection);
  169. // If dot == 1, vectors are the same
  170. if (d >= 1.0f)
  171. {
  172. this = identity;
  173. return;
  174. }
  175. if (d < (1e-6f - 1.0f))
  176. {
  177. if (fallbackAxis != Vector3.zero)
  178. {
  179. // Rotate 180 degrees about the fallback axis
  180. this = FromAxisAngle(fallbackAxis, MathEx.Pi * MathEx.Rad2Deg);
  181. }
  182. else
  183. {
  184. // Generate an axis
  185. Vector3 axis = Vector3.Cross(Vector3.xAxis, fromDirection);
  186. if (axis.SqrdMagnitude < ((1e-06f * 1e-06f))) // Pick another if collinear
  187. axis = Vector3.Cross(Vector3.yAxis, fromDirection);
  188. axis.Normalize();
  189. this = FromAxisAngle(axis, MathEx.Pi * MathEx.Rad2Deg);
  190. }
  191. }
  192. else
  193. {
  194. float s = MathEx.Sqrt((1+d)*2);
  195. float invs = 1 / s;
  196. Vector3 c = Vector3.Cross(fromDirection, toDirection);
  197. x = c.x * invs;
  198. y = c.y * invs;
  199. z = c.z * invs;
  200. w = s * 0.5f;
  201. Normalize();
  202. }
  203. }
  204. public float Normalize()
  205. {
  206. float len = w*w+x*x+y*y+z*z;
  207. float factor = 1.0f / (float)MathEx.Sqrt(len);
  208. x *= factor;
  209. y *= factor;
  210. z *= factor;
  211. w *= factor;
  212. return len;
  213. }
  214. public void Inverse()
  215. {
  216. float fNorm = w * w + x * x + y * y + z * z;
  217. if (fNorm > 0.0f)
  218. {
  219. float fInvNorm = 1.0f / fNorm;
  220. x *= -fInvNorm;
  221. y *= -fInvNorm;
  222. z *= -fInvNorm;
  223. w *= fInvNorm;
  224. }
  225. else
  226. {
  227. this = zero;
  228. }
  229. }
  230. public void SetLookRotation(Vector3 forward)
  231. {
  232. SetLookRotation(forward, Vector3.yAxis);
  233. }
  234. public void SetLookRotation(Vector3 forward, Vector3 up)
  235. {
  236. Quaternion forwardRot = FromToRotation(Vector3.zAxis, forward);
  237. Quaternion upRot = FromToRotation(Vector3.yAxis, up);
  238. this = forwardRot * upRot;
  239. }
  240. public static Quaternion Slerp(Quaternion from, Quaternion to, float t, bool shortestPath = false)
  241. {
  242. float cos = from.w*to.w + from.x*to.x + from.y*to.y + from.z*from.z;
  243. Quaternion quat;
  244. if (cos < 0.0f && shortestPath)
  245. {
  246. cos = -cos;
  247. quat = -to;
  248. }
  249. else
  250. {
  251. quat = to;
  252. }
  253. if (MathEx.Abs(cos) < (1 - epsilon))
  254. {
  255. // Standard case (slerp)
  256. float sin = MathEx.Sqrt(1 - (cos*cos));
  257. float angle = MathEx.Atan2(sin, cos);
  258. float invSin = 1.0f / sin;
  259. float coeff0 = MathEx.Sin((1.0f - t) * angle) * invSin;
  260. float coeff1 = MathEx.Sin(t * angle) * invSin;
  261. return coeff0 * from + coeff1 * quat;
  262. }
  263. else
  264. {
  265. // There are two situations:
  266. // 1. "p" and "q" are very close (fCos ~= +1), so we can do a linear
  267. // interpolation safely.
  268. // 2. "p" and "q" are almost inverse of each other (fCos ~= -1), there
  269. // are an infinite number of possibilities interpolation. but we haven't
  270. // have method to fix this case, so just use linear interpolation here.
  271. Quaternion ret = (1.0f - t) * from + t * quat;
  272. // Taking the complement requires renormalization
  273. ret.Normalize();
  274. return ret;
  275. }
  276. }
  277. public static Quaternion RotateTowards(Quaternion from, Quaternion to, Degree maxDeg)
  278. {
  279. Degree num = Angle(from, to);
  280. if (num == 0.0f)
  281. return to;
  282. float t = MathEx.Min(1f, (float)(maxDeg / num));
  283. return Slerp(from, to, t);
  284. }
  285. public static Quaternion Inverse(Quaternion rotation)
  286. {
  287. Quaternion copy = rotation;
  288. copy.Inverse();
  289. return copy;
  290. }
  291. public static Degree Angle(Quaternion a, Quaternion b)
  292. {
  293. return (MathEx.Acos(MathEx.Min(MathEx.Abs(Dot(a, b)), 1.0f)) * 2.0f * MathEx.Rad2Deg);
  294. }
  295. public void ToAxisAngle(out Vector3 axis, out Degree angle)
  296. {
  297. float fSqrLength = x*x+y*y+z*z;
  298. if (fSqrLength > 0.0f)
  299. {
  300. angle = 2.0f * MathEx.Acos(w) * MathEx.Rad2Deg;
  301. float fInvLength = MathEx.InvSqrt(fSqrLength);
  302. axis.x = x*fInvLength;
  303. axis.y = y*fInvLength;
  304. axis.z = z*fInvLength;
  305. }
  306. else
  307. {
  308. // Angle is 0, so any axis will do
  309. angle = 0.0f;
  310. axis.x = 1.0f;
  311. axis.y = 0.0f;
  312. axis.z = 0.0f;
  313. }
  314. }
  315. // Returns angles in degrees
  316. public Vector3 ToEuler(EulerAngleOrder order = EulerAngleOrder.XYZ)
  317. {
  318. Matrix3 matRot = ToRotationMatrix();
  319. return matRot.ToEulerAngles(order);
  320. }
  321. public Matrix3 ToRotationMatrix()
  322. {
  323. Matrix3 mat = new Matrix3();
  324. float tx = x + x;
  325. float ty = y + y;
  326. float fTz = z + z;
  327. float twx = tx * w;
  328. float twy = ty * w;
  329. float twz = fTz * w;
  330. float txx = tx * x;
  331. float txy = ty * x;
  332. float txz = fTz * x;
  333. float tyy = ty * y;
  334. float tyz = fTz * y;
  335. float tzz = fTz * z;
  336. mat[0, 0] = 1.0f - (tyy + tzz);
  337. mat[0, 1] = txy - twz;
  338. mat[0, 2] = txz + twy;
  339. mat[1, 0] = txy + twz;
  340. mat[1, 1] = 1.0f - (txx + tzz);
  341. mat[1, 2] = tyz - twx;
  342. mat[2, 0] = txz - twy;
  343. mat[2, 1] = tyz + twx;
  344. mat[2, 2] = 1.0f - (txx + tyy);
  345. return mat;
  346. }
  347. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection)
  348. {
  349. Quaternion q = new Quaternion();
  350. q.SetFromToRotation(fromDirection, toDirection);
  351. return q;
  352. }
  353. public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection, Vector3 fallbackAxis)
  354. {
  355. Quaternion q = new Quaternion();
  356. q.SetFromToRotation(fromDirection, toDirection, fallbackAxis);
  357. return q;
  358. }
  359. public static Quaternion LookRotation(Vector3 forward)
  360. {
  361. Quaternion quat = new Quaternion();
  362. quat.SetLookRotation(forward);
  363. return quat;
  364. }
  365. public static Quaternion LookRotation(Vector3 forward, Vector3 up)
  366. {
  367. Quaternion quat = new Quaternion();
  368. quat.SetLookRotation(forward, up);
  369. return quat;
  370. }
  371. public static Vector3 ToEuler(Quaternion rotation, EulerAngleOrder order = EulerAngleOrder.XYZ)
  372. {
  373. return rotation.ToEuler(order);
  374. }
  375. public static void ToAxisAngle(Quaternion rotation, out Vector3 axis, out Degree angleDeg)
  376. {
  377. rotation.ToAxisAngle(out axis, out angleDeg);
  378. }
  379. public static Quaternion FromRotationMatrix(Matrix3 rotMatrix)
  380. {
  381. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  382. // article "Quaternion Calculus and Fast Animation".
  383. Quaternion quat = new Quaternion();
  384. float trace = rotMatrix.m00 + rotMatrix.m11 + rotMatrix.m22;
  385. float root;
  386. if (trace > 0.0f)
  387. {
  388. // |w| > 1/2, may as well choose w > 1/2
  389. root = MathEx.Sqrt(trace + 1.0f); // 2w
  390. quat.w = 0.5f*root;
  391. root = 0.5f/root; // 1/(4w)
  392. quat.x = (rotMatrix.m21 - rotMatrix.m12) * root;
  393. quat.y = (rotMatrix.m02 - rotMatrix.m20) * root;
  394. quat.z = (rotMatrix.m10 - rotMatrix.m01) * root;
  395. }
  396. else
  397. {
  398. // |w| <= 1/2
  399. int[] nextLookup = { 1, 2, 0 };
  400. int i = 0;
  401. if (rotMatrix.m11 > rotMatrix.m00)
  402. i = 1;
  403. if (rotMatrix.m22 > rotMatrix[i, i])
  404. i = 2;
  405. int j = nextLookup[i];
  406. int k = nextLookup[j];
  407. root = MathEx.Sqrt(rotMatrix[i,i] - rotMatrix[j, j] - rotMatrix[k, k] + 1.0f);
  408. quat[i] = 0.5f*root;
  409. root = 0.5f/root;
  410. quat.w = (rotMatrix[k, j] - rotMatrix[j, k]) * root;
  411. quat[j] = (rotMatrix[j, i] + rotMatrix[i, j]) * root;
  412. quat[k] = (rotMatrix[k, i] + rotMatrix[i, k]) * root;
  413. }
  414. quat.Normalize();
  415. return quat;
  416. }
  417. public static Quaternion FromAxisAngle(Vector3 axis, Degree angleDeg)
  418. {
  419. Quaternion quat;
  420. float halfAngle = (float)(0.5f*angleDeg*MathEx.Deg2Rad);
  421. float sin = (float)MathEx.Sin(halfAngle);
  422. quat.w = (float)MathEx.Cos(halfAngle);
  423. quat.x = sin * axis.x;
  424. quat.y = sin * axis.y;
  425. quat.z = sin * axis.z;
  426. return quat;
  427. }
  428. public static Quaternion FromEuler(float xDeg, float yDeg, float zDeg, EulerAngleOrder order = EulerAngleOrder.XYZ)
  429. {
  430. Matrix3 mat = Matrix3.FromEuler(new Vector3(xDeg, yDeg, zDeg), order);
  431. return mat.ToQuaternion();
  432. }
  433. /**
  434. * @note Angles in degrees.
  435. */
  436. public static Quaternion FromEuler(Vector3 euler, EulerAngleOrder order = EulerAngleOrder.XYZ)
  437. {
  438. return FromEuler(euler.x, euler.y, euler.z, order);
  439. }
  440. public override int GetHashCode()
  441. {
  442. return x.GetHashCode() ^ y.GetHashCode() << 2 ^ z.GetHashCode() >> 2 ^ w.GetHashCode() >> 1;
  443. }
  444. public override bool Equals(object other)
  445. {
  446. if (!(other is Quaternion))
  447. return false;
  448. Quaternion quat = (Quaternion)other;
  449. if (x.Equals(quat.x) && y.Equals(quat.y) && z.Equals(quat.z) && w.Equals(quat.w))
  450. return true;
  451. return false;
  452. }
  453. public override string ToString()
  454. {
  455. return String.Format("({0}, {1}, {2}, {3})", x, y, z, w);
  456. }
  457. }
  458. }