ray.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import { DeepImmutable, Nullable, float } from "types";
  2. import { ArrayTools } from "Misc/arrayTools";
  3. import { Matrix, Vector3, Plane, Tmp } from "Maths/math";
  4. import { AbstractMesh } from "Meshes/abstractMesh";
  5. import { PickingInfo, IntersectionInfo } from "Collisions/pickingInfo";
  6. import { BoundingBox } from "./boundingBox";
  7. import { BoundingSphere } from "./boundingSphere";
  8. /**
  9. * Class representing a ray with position and direction
  10. */
  11. export class Ray {
  12. private static readonly TmpVector3 = ArrayTools.BuildArray(6, Vector3.Zero);
  13. private _tmpRay: Ray;
  14. /**
  15. * Creates a new ray
  16. * @param origin origin point
  17. * @param direction direction
  18. * @param length length of the ray
  19. */
  20. constructor(
  21. /** origin point */
  22. public origin: Vector3,
  23. /** direction */
  24. public direction: Vector3,
  25. /** length of the ray */
  26. public length: number = Number.MAX_VALUE) {
  27. }
  28. // Methods
  29. /**
  30. * Checks if the ray intersects a box
  31. * @param minimum bound of the box
  32. * @param maximum bound of the box
  33. * @param intersectionTreshold extra extend to be added to the box in all direction
  34. * @returns if the box was hit
  35. */
  36. public intersectsBoxMinMax(minimum: DeepImmutable<Vector3>, maximum: DeepImmutable<Vector3>, intersectionTreshold: number = 0): boolean {
  37. const newMinimum = Ray.TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
  38. const newMaximum = Ray.TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
  39. var d = 0.0;
  40. var maxValue = Number.MAX_VALUE;
  41. var inv: number;
  42. var min: number;
  43. var max: number;
  44. var temp: number;
  45. if (Math.abs(this.direction.x) < 0.0000001) {
  46. if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
  47. return false;
  48. }
  49. }
  50. else {
  51. inv = 1.0 / this.direction.x;
  52. min = (newMinimum.x - this.origin.x) * inv;
  53. max = (newMaximum.x - this.origin.x) * inv;
  54. if (max === -Infinity) {
  55. max = Infinity;
  56. }
  57. if (min > max) {
  58. temp = min;
  59. min = max;
  60. max = temp;
  61. }
  62. d = Math.max(min, d);
  63. maxValue = Math.min(max, maxValue);
  64. if (d > maxValue) {
  65. return false;
  66. }
  67. }
  68. if (Math.abs(this.direction.y) < 0.0000001) {
  69. if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
  70. return false;
  71. }
  72. }
  73. else {
  74. inv = 1.0 / this.direction.y;
  75. min = (newMinimum.y - this.origin.y) * inv;
  76. max = (newMaximum.y - this.origin.y) * inv;
  77. if (max === -Infinity) {
  78. max = Infinity;
  79. }
  80. if (min > max) {
  81. temp = min;
  82. min = max;
  83. max = temp;
  84. }
  85. d = Math.max(min, d);
  86. maxValue = Math.min(max, maxValue);
  87. if (d > maxValue) {
  88. return false;
  89. }
  90. }
  91. if (Math.abs(this.direction.z) < 0.0000001) {
  92. if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
  93. return false;
  94. }
  95. }
  96. else {
  97. inv = 1.0 / this.direction.z;
  98. min = (newMinimum.z - this.origin.z) * inv;
  99. max = (newMaximum.z - this.origin.z) * inv;
  100. if (max === -Infinity) {
  101. max = Infinity;
  102. }
  103. if (min > max) {
  104. temp = min;
  105. min = max;
  106. max = temp;
  107. }
  108. d = Math.max(min, d);
  109. maxValue = Math.min(max, maxValue);
  110. if (d > maxValue) {
  111. return false;
  112. }
  113. }
  114. return true;
  115. }
  116. /**
  117. * Checks if the ray intersects a box
  118. * @param box the bounding box to check
  119. * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
  120. * @returns if the box was hit
  121. */
  122. public intersectsBox(box: DeepImmutable<BoundingBox>, intersectionTreshold: number = 0): boolean {
  123. return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
  124. }
  125. /**
  126. * If the ray hits a sphere
  127. * @param sphere the bounding sphere to check
  128. * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
  129. * @returns true if it hits the sphere
  130. */
  131. public intersectsSphere(sphere: DeepImmutable<BoundingSphere>, intersectionTreshold: number = 0): boolean {
  132. var x = sphere.center.x - this.origin.x;
  133. var y = sphere.center.y - this.origin.y;
  134. var z = sphere.center.z - this.origin.z;
  135. var pyth = (x * x) + (y * y) + (z * z);
  136. const radius = sphere.radius + intersectionTreshold;
  137. var rr = radius * radius;
  138. if (pyth <= rr) {
  139. return true;
  140. }
  141. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  142. if (dot < 0.0) {
  143. return false;
  144. }
  145. var temp = pyth - (dot * dot);
  146. return temp <= rr;
  147. }
  148. /**
  149. * If the ray hits a triange
  150. * @param vertex0 triangle vertex
  151. * @param vertex1 triangle vertex
  152. * @param vertex2 triangle vertex
  153. * @returns intersection information if hit
  154. */
  155. public intersectsTriangle(vertex0: DeepImmutable<Vector3>, vertex1: DeepImmutable<Vector3>, vertex2: DeepImmutable<Vector3>): Nullable<IntersectionInfo> {
  156. const edge1 = Ray.TmpVector3[0];
  157. const edge2 = Ray.TmpVector3[1];
  158. const pvec = Ray.TmpVector3[2];
  159. const tvec = Ray.TmpVector3[3];
  160. const qvec = Ray.TmpVector3[4];
  161. vertex1.subtractToRef(vertex0, edge1);
  162. vertex2.subtractToRef(vertex0, edge2);
  163. Vector3.CrossToRef(this.direction, edge2, pvec);
  164. var det = Vector3.Dot(edge1, pvec);
  165. if (det === 0) {
  166. return null;
  167. }
  168. var invdet = 1 / det;
  169. this.origin.subtractToRef(vertex0, tvec);
  170. var bu = Vector3.Dot(tvec, pvec) * invdet;
  171. if (bu < 0 || bu > 1.0) {
  172. return null;
  173. }
  174. Vector3.CrossToRef(tvec, edge1, qvec);
  175. var bv = Vector3.Dot(this.direction, qvec) * invdet;
  176. if (bv < 0 || bu + bv > 1.0) {
  177. return null;
  178. }
  179. //check if the distance is longer than the predefined length.
  180. var distance = Vector3.Dot(edge2, qvec) * invdet;
  181. if (distance > this.length) {
  182. return null;
  183. }
  184. return new IntersectionInfo(bu, bv, distance);
  185. }
  186. /**
  187. * Checks if ray intersects a plane
  188. * @param plane the plane to check
  189. * @returns the distance away it was hit
  190. */
  191. public intersectsPlane(plane: DeepImmutable<Plane>): Nullable<number> {
  192. var distance: number;
  193. var result1 = Vector3.Dot(plane.normal, this.direction);
  194. if (Math.abs(result1) < 9.99999997475243E-07) {
  195. return null;
  196. }
  197. else {
  198. var result2 = Vector3.Dot(plane.normal, this.origin);
  199. distance = (-plane.d - result2) / result1;
  200. if (distance < 0.0) {
  201. if (distance < -9.99999997475243E-07) {
  202. return null;
  203. } else {
  204. return 0;
  205. }
  206. }
  207. return distance;
  208. }
  209. }
  210. /**
  211. * Checks if ray intersects a mesh
  212. * @param mesh the mesh to check
  213. * @param fastCheck if only the bounding box should checked
  214. * @returns picking info of the intersecton
  215. */
  216. public intersectsMesh(mesh: DeepImmutable<AbstractMesh>, fastCheck?: boolean): PickingInfo {
  217. var tm = Tmp.Matrix[0];
  218. mesh.getWorldMatrix().invertToRef(tm);
  219. if (this._tmpRay) {
  220. Ray.TransformToRef(this, tm, this._tmpRay);
  221. }else {
  222. this._tmpRay = Ray.Transform(this, tm);
  223. }
  224. return mesh.intersects(this._tmpRay, fastCheck);
  225. }
  226. /**
  227. * Checks if ray intersects a mesh
  228. * @param meshes the meshes to check
  229. * @param fastCheck if only the bounding box should checked
  230. * @param results array to store result in
  231. * @returns Array of picking infos
  232. */
  233. public intersectsMeshes(meshes: Array<DeepImmutable<AbstractMesh>>, fastCheck?: boolean, results?: Array<PickingInfo>): Array<PickingInfo> {
  234. if (results) {
  235. results.length = 0;
  236. }else {
  237. results = [];
  238. }
  239. for (var i = 0; i < meshes.length; i++) {
  240. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  241. if (pickInfo.hit) {
  242. results.push(pickInfo);
  243. }
  244. }
  245. results.sort(this._comparePickingInfo);
  246. return results;
  247. }
  248. private _comparePickingInfo(pickingInfoA: DeepImmutable<PickingInfo>, pickingInfoB: DeepImmutable<PickingInfo>): number {
  249. if (pickingInfoA.distance < pickingInfoB.distance) {
  250. return -1;
  251. }else if (pickingInfoA.distance > pickingInfoB.distance) {
  252. return 1;
  253. }else {
  254. return 0;
  255. }
  256. }
  257. private static smallnum = 0.00000001;
  258. private static rayl = 10e8;
  259. /**
  260. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  261. * @param sega the first point of the segment to test the intersection against
  262. * @param segb the second point of the segment to test the intersection against
  263. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  264. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  265. */
  266. intersectionSegment(sega: DeepImmutable<Vector3>, segb: DeepImmutable<Vector3>, threshold: number): number {
  267. const o = this.origin;
  268. const u = Tmp.Vector3[0];
  269. const rsegb = Tmp.Vector3[1];
  270. const v = Tmp.Vector3[2];
  271. const w = Tmp.Vector3[3];
  272. segb.subtractToRef(sega, u);
  273. this.direction.scaleToRef(Ray.rayl, v);
  274. o.addToRef(v, rsegb);
  275. sega.subtractToRef(o, w);
  276. var a = Vector3.Dot(u, u); // always >= 0
  277. var b = Vector3.Dot(u, v);
  278. var c = Vector3.Dot(v, v); // always >= 0
  279. var d = Vector3.Dot(u, w);
  280. var e = Vector3.Dot(v, w);
  281. var D = a * c - b * b; // always >= 0
  282. var sc: number, sN: number, sD = D; // sc = sN / sD, default sD = D >= 0
  283. var tc: number, tN: number, tD = D; // tc = tN / tD, default tD = D >= 0
  284. // compute the line parameters of the two closest points
  285. if (D < Ray.smallnum) { // the lines are almost parallel
  286. sN = 0.0; // force using point P0 on segment S1
  287. sD = 1.0; // to prevent possible division by 0.0 later
  288. tN = e;
  289. tD = c;
  290. }
  291. else { // get the closest points on the infinite lines
  292. sN = (b * e - c * d);
  293. tN = (a * e - b * d);
  294. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  295. sN = 0.0;
  296. tN = e;
  297. tD = c;
  298. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  299. sN = sD;
  300. tN = e + b;
  301. tD = c;
  302. }
  303. }
  304. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  305. tN = 0.0;
  306. // recompute sc for this edge
  307. if (-d < 0.0) {
  308. sN = 0.0;
  309. } else if (-d > a) {
  310. sN = sD;
  311. }
  312. else {
  313. sN = -d;
  314. sD = a;
  315. }
  316. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  317. tN = tD;
  318. // recompute sc for this edge
  319. if ((-d + b) < 0.0) {
  320. sN = 0;
  321. } else if ((-d + b) > a) {
  322. sN = sD;
  323. } else {
  324. sN = (-d + b);
  325. sD = a;
  326. }
  327. }
  328. // finally do the division to get sc and tc
  329. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  330. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  331. // get the difference of the two closest points
  332. const qtc = Tmp.Vector3[4];
  333. v.scaleToRef(tc, qtc);
  334. const qsc = Tmp.Vector3[5];
  335. u.scaleToRef(sc, qsc);
  336. qsc.addInPlace(w);
  337. const dP = Tmp.Vector3[6];
  338. qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)
  339. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  340. if (isIntersected) {
  341. return qsc.length();
  342. }
  343. return -1;
  344. }
  345. /**
  346. * Update the ray from viewport position
  347. * @param x position
  348. * @param y y position
  349. * @param viewportWidth viewport width
  350. * @param viewportHeight viewport height
  351. * @param world world matrix
  352. * @param view view matrix
  353. * @param projection projection matrix
  354. * @returns this ray updated
  355. */
  356. public update(x: number, y: number, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>): Ray {
  357. this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection);
  358. return this;
  359. }
  360. // Statics
  361. /**
  362. * Creates a ray with origin and direction of 0,0,0
  363. * @returns the new ray
  364. */
  365. public static Zero(): Ray {
  366. return new Ray(Vector3.Zero(), Vector3.Zero());
  367. }
  368. /**
  369. * Creates a new ray from screen space and viewport
  370. * @param x position
  371. * @param y y position
  372. * @param viewportWidth viewport width
  373. * @param viewportHeight viewport height
  374. * @param world world matrix
  375. * @param view view matrix
  376. * @param projection projection matrix
  377. * @returns new ray
  378. */
  379. public static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>): Ray {
  380. let result = Ray.Zero();
  381. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  382. }
  383. /**
  384. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  385. * transformed to the given world matrix.
  386. * @param origin The origin point
  387. * @param end The end point
  388. * @param world a matrix to transform the ray to. Default is the identity matrix.
  389. * @returns the new ray
  390. */
  391. public static CreateNewFromTo(origin: DeepImmutable<Vector3>, end: DeepImmutable<Vector3>, world: DeepImmutable<Matrix> = Matrix.IdentityReadOnly): Ray {
  392. var direction = end.subtract(origin);
  393. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  394. direction.normalize();
  395. return Ray.Transform(new Ray(origin, direction, length), world);
  396. }
  397. /**
  398. * Transforms a ray by a matrix
  399. * @param ray ray to transform
  400. * @param matrix matrix to apply
  401. * @returns the resulting new ray
  402. */
  403. public static Transform(ray: DeepImmutable<Ray>, matrix: DeepImmutable<Matrix>): Ray {
  404. var result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
  405. Ray.TransformToRef(ray, matrix, result);
  406. return result;
  407. }
  408. /**
  409. * Transforms a ray by a matrix
  410. * @param ray ray to transform
  411. * @param matrix matrix to apply
  412. * @param result ray to store result in
  413. */
  414. public static TransformToRef(ray: DeepImmutable<Ray>, matrix: DeepImmutable<Matrix>, result: Ray): void {
  415. Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  416. Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  417. result.length = ray.length;
  418. var dir = result.direction;
  419. var len = dir.length();
  420. if (!(len === 0 || len === 1)) {
  421. var num = 1.0 / len;
  422. dir.x *= num;
  423. dir.y *= num;
  424. dir.z *= num;
  425. result.length *= len;
  426. }
  427. }
  428. /**
  429. * Unproject a ray from screen space to object space
  430. * @param sourceX defines the screen space x coordinate to use
  431. * @param sourceY defines the screen space y coordinate to use
  432. * @param viewportWidth defines the current width of the viewport
  433. * @param viewportHeight defines the current height of the viewport
  434. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  435. * @param view defines the view matrix to use
  436. * @param projection defines the projection matrix to use
  437. */
  438. public unprojectRayToRef(sourceX: float, sourceY: float, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>): void {
  439. var matrix = Tmp.Matrix[0];
  440. world.multiplyToRef(view, matrix);
  441. matrix.multiplyToRef(projection, matrix);
  442. matrix.invert();
  443. var nearScreenSource = Tmp.Vector3[0];
  444. nearScreenSource.x = sourceX / viewportWidth * 2 - 1;
  445. nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1);
  446. nearScreenSource.z = -1.0;
  447. var farScreenSource = Tmp.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
  448. const nearVec3 = Tmp.Vector3[2];
  449. const farVec3 = Tmp.Vector3[3];
  450. Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
  451. Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
  452. this.origin.copyFrom(nearVec3);
  453. farVec3.subtractToRef(nearVec3, this.direction);
  454. this.direction.normalize();
  455. }
  456. }