quat.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. /**
  2. * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. /*
  8. * This code has been modified from https://github.com/toji/gl-matrix/,
  9. * copyright (c) 2015, Brandon Jones, Colin MacKenzie IV.
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. */
  18. /*
  19. * Quat.fromUnitVec3 has been modified from https://github.com/Jam3/quat-from-unit-vec3,
  20. * copyright (c) 2015 Jam3. MIT License
  21. */
  22. import { Mat3 } from './mat3';
  23. import { Vec3 } from './vec3';
  24. import { EPSILON } from './common';
  25. import { NumberArray } from '../../../mol-util/type-helpers';
  26. interface Quat extends Array<number> { [d: number]: number, '@type': 'quat', length: 4 }
  27. interface ReadonlyQuat extends Array<number> { readonly [d: number]: number, '@type': 'quat', length: 4 }
  28. function Quat() {
  29. return Quat.zero();
  30. }
  31. namespace Quat {
  32. export function zero(): Quat {
  33. // force double backing array by 0.1.
  34. const ret = [0.1, 0, 0, 0];
  35. ret[0] = 0.0;
  36. return ret as any;
  37. }
  38. export function identity(): Quat {
  39. const out = zero();
  40. out[3] = 1;
  41. return out;
  42. }
  43. export function setIdentity(out: Quat) {
  44. out[0] = 0;
  45. out[1] = 0;
  46. out[2] = 0;
  47. out[3] = 1;
  48. }
  49. export function hasNaN(q: Quat) {
  50. return isNaN(q[0]) || isNaN(q[1]) || isNaN(q[2]) || isNaN(q[3]);
  51. }
  52. export function create(x: number, y: number, z: number, w: number) {
  53. const out = identity();
  54. out[0] = x;
  55. out[1] = y;
  56. out[2] = z;
  57. out[3] = w;
  58. return out;
  59. }
  60. export function setAxisAngle(out: Quat, axis: Vec3, rad: number) {
  61. rad = rad * 0.5;
  62. const s = Math.sin(rad);
  63. out[0] = s * axis[0];
  64. out[1] = s * axis[1];
  65. out[2] = s * axis[2];
  66. out[3] = Math.cos(rad);
  67. return out;
  68. }
  69. /**
  70. * Gets the rotation axis and angle for a given
  71. * quaternion. If a quaternion is created with
  72. * setAxisAngle, this method will return the same
  73. * values as providied in the original parameter list
  74. * OR functionally equivalent values.
  75. * Example: The quaternion formed by axis [0, 0, 1] and
  76. * angle -90 is the same as the quaternion formed by
  77. * [0, 0, 1] and 270. This method favors the latter.
  78. */
  79. export function getAxisAngle(out_axis: Vec3, q: Quat) {
  80. const rad = Math.acos(q[3]) * 2.0;
  81. const s = Math.sin(rad / 2.0);
  82. if (s !== 0.0) {
  83. out_axis[0] = q[0] / s;
  84. out_axis[1] = q[1] / s;
  85. out_axis[2] = q[2] / s;
  86. } else {
  87. // If s is zero, return any axis (no rotation - axis does not matter)
  88. out_axis[0] = 1;
  89. out_axis[1] = 0;
  90. out_axis[2] = 0;
  91. }
  92. return rad;
  93. }
  94. export function multiply(out: Quat, a: Quat, b: Quat) {
  95. const ax = a[0], ay = a[1], az = a[2], aw = a[3];
  96. const bx = b[0], by = b[1], bz = b[2], bw = b[3];
  97. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  98. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  99. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  100. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  101. return out;
  102. }
  103. export function rotateX(out: Quat, a: Quat, rad: number) {
  104. rad *= 0.5;
  105. const ax = a[0], ay = a[1], az = a[2], aw = a[3];
  106. const bx = Math.sin(rad), bw = Math.cos(rad);
  107. out[0] = ax * bw + aw * bx;
  108. out[1] = ay * bw + az * bx;
  109. out[2] = az * bw - ay * bx;
  110. out[3] = aw * bw - ax * bx;
  111. return out;
  112. }
  113. export function rotateY(out: Quat, a: Quat, rad: number) {
  114. rad *= 0.5;
  115. const ax = a[0], ay = a[1], az = a[2], aw = a[3];
  116. const by = Math.sin(rad), bw = Math.cos(rad);
  117. out[0] = ax * bw - az * by;
  118. out[1] = ay * bw + aw * by;
  119. out[2] = az * bw + ax * by;
  120. out[3] = aw * bw - ay * by;
  121. return out;
  122. }
  123. export function rotateZ(out: Quat, a: Quat, rad: number) {
  124. rad *= 0.5;
  125. const ax = a[0], ay = a[1], az = a[2], aw = a[3];
  126. const bz = Math.sin(rad), bw = Math.cos(rad);
  127. out[0] = ax * bw + ay * bz;
  128. out[1] = ay * bw - ax * bz;
  129. out[2] = az * bw + aw * bz;
  130. out[3] = aw * bw - az * bz;
  131. return out;
  132. }
  133. /**
  134. * Calculates the W component of a quat from the X, Y, and Z components.
  135. * Assumes that quaternion is 1 unit in length.
  136. * Any existing W component will be ignored.
  137. */
  138. export function calculateW(out: Quat, a: Quat) {
  139. const x = a[0], y = a[1], z = a[2];
  140. out[0] = x;
  141. out[1] = y;
  142. out[2] = z;
  143. out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));
  144. return out;
  145. }
  146. /**
  147. * Performs a spherical linear interpolation between two quat
  148. */
  149. export function slerp(out: Quat, a: Quat, b: Quat, t: number) {
  150. // benchmarks:
  151. // http://jsperf.com/quaternion-slerp-implementations
  152. const ax = a[0], ay = a[1], az = a[2], aw = a[3];
  153. let bx = b[0], by = b[1], bz = b[2], bw = b[3];
  154. let omega, cosom, sinom, scale0, scale1;
  155. // calc cosine
  156. cosom = ax * bx + ay * by + az * bz + aw * bw;
  157. // adjust signs (if necessary)
  158. if (cosom < 0.0) {
  159. cosom = -cosom;
  160. bx = - bx;
  161. by = - by;
  162. bz = - bz;
  163. bw = - bw;
  164. }
  165. // calculate coefficients
  166. if ((1.0 - cosom) > 0.000001) {
  167. // standard case (slerp)
  168. omega = Math.acos(cosom);
  169. sinom = Math.sin(omega);
  170. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  171. scale1 = Math.sin(t * omega) / sinom;
  172. } else {
  173. // "from" and "to" quaternions are very close
  174. // ... so we can do a linear interpolation
  175. scale0 = 1.0 - t;
  176. scale1 = t;
  177. }
  178. // calculate final values
  179. out[0] = scale0 * ax + scale1 * bx;
  180. out[1] = scale0 * ay + scale1 * by;
  181. out[2] = scale0 * az + scale1 * bz;
  182. out[3] = scale0 * aw + scale1 * bw;
  183. return out;
  184. }
  185. export function invert(out: Quat, a: Quat) {
  186. const a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3];
  187. const dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  188. const invDot = dot ? 1.0 / dot : 0;
  189. // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  190. out[0] = -a0 * invDot;
  191. out[1] = -a1 * invDot;
  192. out[2] = -a2 * invDot;
  193. out[3] = a3 * invDot;
  194. return out;
  195. }
  196. /**
  197. * Calculates the conjugate of a quat
  198. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  199. */
  200. export function conjugate(out: Quat, a: Quat) {
  201. out[0] = -a[0];
  202. out[1] = -a[1];
  203. out[2] = -a[2];
  204. out[3] = a[3];
  205. return out;
  206. }
  207. /**
  208. * Creates a quaternion from the given 3x3 rotation matrix.
  209. *
  210. * NOTE: The resultant quaternion is not normalized, so you should be sure
  211. * to renormalize the quaternion yourself where necessary.
  212. */
  213. export function fromMat3(out: Quat, m: Mat3) {
  214. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  215. // article "Quaternion Calculus and Fast Animation".
  216. const fTrace = m[0] + m[4] + m[8];
  217. let fRoot;
  218. if (fTrace > 0.0) {
  219. // |w| > 1/2, may as well choose w > 1/2
  220. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  221. out[3] = 0.5 * fRoot;
  222. fRoot = 0.5 / fRoot; // 1/(4w)
  223. out[0] = (m[5] - m[7]) * fRoot;
  224. out[1] = (m[6] - m[2]) * fRoot;
  225. out[2] = (m[1] - m[3]) * fRoot;
  226. } else {
  227. // |w| <= 1/2
  228. let i = 0;
  229. if (m[4] > m[0]) i = 1;
  230. if (m[8] > m[i * 3 + i]) i = 2;
  231. const j = (i + 1) % 3;
  232. const k = (i + 2) % 3;
  233. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  234. out[i] = 0.5 * fRoot;
  235. fRoot = 0.5 / fRoot;
  236. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  237. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  238. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  239. }
  240. return out;
  241. }
  242. const fromUnitVec3Temp = [0, 0, 0] as Vec3;
  243. /** Quaternion from two normalized unit vectors. */
  244. export function fromUnitVec3(out: Quat, a: Vec3, b: Vec3) {
  245. // assumes a and b are normalized
  246. let r = Vec3.dot(a, b) + 1;
  247. if (r < EPSILON) {
  248. // If u and v are exactly opposite, rotate 180 degrees
  249. // around an arbitrary orthogonal axis. Axis normalisation
  250. // can happen later, when we normalise the quaternion.
  251. r = 0;
  252. if (Math.abs(a[0]) > Math.abs(a[2])) {
  253. Vec3.set(fromUnitVec3Temp, -a[1], a[0], 0);
  254. } else {
  255. Vec3.set(fromUnitVec3Temp, 0, -a[2], a[1]);
  256. }
  257. } else {
  258. // Otherwise, build quaternion the standard way.
  259. Vec3.cross(fromUnitVec3Temp, a, b);
  260. }
  261. out[0] = fromUnitVec3Temp[0];
  262. out[1] = fromUnitVec3Temp[1];
  263. out[2] = fromUnitVec3Temp[2];
  264. out[3] = r;
  265. normalize(out, out);
  266. return out;
  267. }
  268. export function clone(a: Quat) {
  269. const out = zero();
  270. out[0] = a[0];
  271. out[1] = a[1];
  272. out[2] = a[2];
  273. out[3] = a[3];
  274. return out;
  275. }
  276. export function toArray(a: Quat, out: NumberArray, offset: number) {
  277. out[offset + 0] = a[0];
  278. out[offset + 1] = a[1];
  279. out[offset + 2] = a[2];
  280. out[offset + 3] = a[3];
  281. return out;
  282. }
  283. export function fromArray(a: Quat, array: NumberArray, offset: number) {
  284. a[0] = array[offset + 0];
  285. a[1] = array[offset + 1];
  286. a[2] = array[offset + 2];
  287. a[3] = array[offset + 3];
  288. return a;
  289. }
  290. export function copy(out: Quat, a: Quat) {
  291. out[0] = a[0];
  292. out[1] = a[1];
  293. out[2] = a[2];
  294. out[3] = a[3];
  295. return out;
  296. }
  297. export function set(out: Quat, x: number, y: number, z: number, w: number) {
  298. out[0] = x;
  299. out[1] = y;
  300. out[2] = z;
  301. out[3] = w;
  302. return out;
  303. }
  304. export function add(out: Quat, a: Quat, b: Quat) {
  305. out[0] = a[0] + b[0];
  306. out[1] = a[1] + b[1];
  307. out[2] = a[2] + b[2];
  308. out[3] = a[3] + b[3];
  309. return out;
  310. }
  311. export function normalize(out: Quat, a: Quat) {
  312. const x = a[0];
  313. const y = a[1];
  314. const z = a[2];
  315. const w = a[3];
  316. let len = x * x + y * y + z * z + w * w;
  317. if (len > 0) {
  318. len = 1 / Math.sqrt(len);
  319. out[0] = x * len;
  320. out[1] = y * len;
  321. out[2] = z * len;
  322. out[3] = w * len;
  323. }
  324. return out;
  325. }
  326. /**
  327. * Sets a quaternion to represent the shortest rotation from one
  328. * vector to another.
  329. *
  330. * Both vectors are assumed to be unit length.
  331. */
  332. const rotTmpVec3 = [0, 0, 0] as Vec3;
  333. const rotTmpVec3UnitX = [1, 0, 0] as Vec3;
  334. const rotTmpVec3UnitY = [0, 1, 0] as Vec3;
  335. export function rotationTo(out: Quat, a: Vec3, b: Vec3) {
  336. const dot = Vec3.dot(a, b);
  337. if (dot < -0.999999) {
  338. Vec3.cross(rotTmpVec3, rotTmpVec3UnitX, a);
  339. if (Vec3.magnitude(rotTmpVec3) < 0.000001)
  340. Vec3.cross(rotTmpVec3, rotTmpVec3UnitY, a);
  341. Vec3.normalize(rotTmpVec3, rotTmpVec3);
  342. setAxisAngle(out, rotTmpVec3, Math.PI);
  343. return out;
  344. } else if (dot > 0.999999) {
  345. out[0] = 0;
  346. out[1] = 0;
  347. out[2] = 0;
  348. out[3] = 1;
  349. return out;
  350. } else {
  351. Vec3.cross(rotTmpVec3, a, b);
  352. out[0] = rotTmpVec3[0];
  353. out[1] = rotTmpVec3[1];
  354. out[2] = rotTmpVec3[2];
  355. out[3] = 1 + dot;
  356. return normalize(out, out);
  357. }
  358. }
  359. /**
  360. * Performs a spherical linear interpolation with two control points
  361. */
  362. const sqlerpTemp1 = zero();
  363. const sqlerpTemp2 = zero();
  364. export function sqlerp(out: Quat, a: Quat, b: Quat, c: Quat, d: Quat, t: number) {
  365. slerp(sqlerpTemp1, a, d, t);
  366. slerp(sqlerpTemp2, b, c, t);
  367. slerp(out, sqlerpTemp1, sqlerpTemp2, 2 * t * (1 - t));
  368. return out;
  369. }
  370. /**
  371. * Sets the specified quaternion with values corresponding to the given
  372. * axes. Each axis is a vec3 and is expected to be unit length and
  373. * perpendicular to all other specified axes.
  374. */
  375. const axesTmpMat = [0, 0, 0, 0, 0, 0, 0, 0, 0] as Mat3;
  376. export function setAxes(out: Quat, view: Vec3, right: Vec3, up: Vec3) {
  377. axesTmpMat[0] = right[0];
  378. axesTmpMat[3] = right[1];
  379. axesTmpMat[6] = right[2];
  380. axesTmpMat[1] = up[0];
  381. axesTmpMat[4] = up[1];
  382. axesTmpMat[7] = up[2];
  383. axesTmpMat[2] = -view[0];
  384. axesTmpMat[5] = -view[1];
  385. axesTmpMat[8] = -view[2];
  386. return normalize(out, fromMat3(out, axesTmpMat));
  387. }
  388. export function toString(a: Quat, precision?: number) {
  389. return `[${a[0].toPrecision(precision)} ${a[1].toPrecision(precision)} ${a[2].toPrecision(precision)} ${a[3].toPrecision(precision)}]`;
  390. }
  391. export const Identity: ReadonlyQuat = identity();
  392. }
  393. export { Quat };