Quaternion.cs 15 KB

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