collider.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. import { Nullable, IndicesArray } from "../types";
  2. import { Vector3 } from "../Maths/math.vector";
  3. import { AbstractMesh } from "../Meshes/abstractMesh";
  4. import { Plane } from '../Maths/math.plane';
  5. var intersectBoxAASphere = (boxMin: Vector3, boxMax: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean => {
  6. if (boxMin.x > sphereCenter.x + sphereRadius) {
  7. return false;
  8. }
  9. if (sphereCenter.x - sphereRadius > boxMax.x) {
  10. return false;
  11. }
  12. if (boxMin.y > sphereCenter.y + sphereRadius) {
  13. return false;
  14. }
  15. if (sphereCenter.y - sphereRadius > boxMax.y) {
  16. return false;
  17. }
  18. if (boxMin.z > sphereCenter.z + sphereRadius) {
  19. return false;
  20. }
  21. if (sphereCenter.z - sphereRadius > boxMax.z) {
  22. return false;
  23. }
  24. return true;
  25. };
  26. var getLowestRoot: (a: number, b: number, c: number, maxR: number) => { root: number, found: boolean } =
  27. (function() {
  28. var result = { root: 0, found: false };
  29. return function(a: number, b: number, c: number, maxR: number) {
  30. result.root = 0; result.found = false;
  31. var determinant = b * b - 4.0 * a * c;
  32. if (determinant < 0) {
  33. return result;
  34. }
  35. var sqrtD = Math.sqrt(determinant);
  36. var r1 = (-b - sqrtD) / (2.0 * a);
  37. var r2 = (-b + sqrtD) / (2.0 * a);
  38. if (r1 > r2) {
  39. var temp = r2;
  40. r2 = r1;
  41. r1 = temp;
  42. }
  43. if (r1 > 0 && r1 < maxR) {
  44. result.root = r1;
  45. result.found = true;
  46. return result;
  47. }
  48. if (r2 > 0 && r2 < maxR) {
  49. result.root = r2;
  50. result.found = true;
  51. return result;
  52. }
  53. return result;
  54. };
  55. }
  56. )();
  57. /** @hidden */
  58. export class Collider {
  59. // Implementation of the "Improved Collision detection and Response" algorithm proposed by Kasper Fauerby
  60. // https://www.peroxide.dk/papers/collision/collision.pdf
  61. /** Define if a collision was found */
  62. public collisionFound: boolean;
  63. /**
  64. * Define last intersection point in local space
  65. */
  66. public intersectionPoint: Vector3;
  67. /**
  68. * Define last collided mesh
  69. */
  70. public collidedMesh: Nullable<AbstractMesh>;
  71. private _collisionPoint = Vector3.Zero();
  72. private _planeIntersectionPoint = Vector3.Zero();
  73. private _tempVector = Vector3.Zero();
  74. private _tempVector2 = Vector3.Zero();
  75. private _tempVector3 = Vector3.Zero();
  76. private _tempVector4 = Vector3.Zero();
  77. private _edge = Vector3.Zero();
  78. private _baseToVertex = Vector3.Zero();
  79. private _destinationPoint = Vector3.Zero();
  80. private _slidePlaneNormal = Vector3.Zero();
  81. private _displacementVector = Vector3.Zero();
  82. /** @hidden */
  83. public _radius = Vector3.One();
  84. /** @hidden */
  85. public _retry = 0;
  86. private _velocity: Vector3;
  87. private _basePoint: Vector3;
  88. private _epsilon: number;
  89. /** @hidden */
  90. public _velocityWorldLength: number;
  91. /** @hidden */
  92. public _basePointWorld = Vector3.Zero();
  93. private _velocityWorld = Vector3.Zero();
  94. private _normalizedVelocity = Vector3.Zero();
  95. /** @hidden */
  96. public _initialVelocity: Vector3;
  97. /** @hidden */
  98. public _initialPosition: Vector3;
  99. private _nearestDistance: number;
  100. private _collisionMask = -1;
  101. public get collisionMask(): number {
  102. return this._collisionMask;
  103. }
  104. public set collisionMask(mask: number) {
  105. this._collisionMask = !isNaN(mask) ? mask : -1;
  106. }
  107. /**
  108. * Gets the plane normal used to compute the sliding response (in local space)
  109. */
  110. public get slidePlaneNormal(): Vector3 {
  111. return this._slidePlaneNormal;
  112. }
  113. // Methods
  114. /** @hidden */
  115. public _initialize(source: Vector3, dir: Vector3, e: number): void {
  116. this._velocity = dir;
  117. Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  118. this._basePoint = source;
  119. source.multiplyToRef(this._radius, this._basePointWorld);
  120. dir.multiplyToRef(this._radius, this._velocityWorld);
  121. this._velocityWorldLength = this._velocityWorld.length();
  122. this._epsilon = e;
  123. this.collisionFound = false;
  124. }
  125. /** @hidden */
  126. public _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean {
  127. pa.subtractToRef(point, this._tempVector);
  128. pb.subtractToRef(point, this._tempVector2);
  129. Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  130. var d = Vector3.Dot(this._tempVector4, n);
  131. if (d < 0) {
  132. return false;
  133. }
  134. pc.subtractToRef(point, this._tempVector3);
  135. Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  136. d = Vector3.Dot(this._tempVector4, n);
  137. if (d < 0) {
  138. return false;
  139. }
  140. Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  141. d = Vector3.Dot(this._tempVector4, n);
  142. return d >= 0;
  143. }
  144. /** @hidden */
  145. public _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean {
  146. var distance = Vector3.Distance(this._basePointWorld, sphereCenter);
  147. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  148. if (distance > this._velocityWorldLength + max + sphereRadius) {
  149. return false;
  150. }
  151. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
  152. return false;
  153. }
  154. return true;
  155. }
  156. /** @hidden */
  157. public _testTriangle(faceIndex: number, trianglePlaneArray: Array<Plane>, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean, hostMesh: AbstractMesh): void {
  158. var t0;
  159. var embeddedInPlane = false;
  160. //defensive programming, actually not needed.
  161. if (!trianglePlaneArray) {
  162. trianglePlaneArray = [];
  163. }
  164. if (!trianglePlaneArray[faceIndex]) {
  165. trianglePlaneArray[faceIndex] = new Plane(0, 0, 0, 0);
  166. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  167. }
  168. var trianglePlane = trianglePlaneArray[faceIndex];
  169. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
  170. return;
  171. }
  172. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  173. var normalDotVelocity = Vector3.Dot(trianglePlane.normal, this._velocity);
  174. if (normalDotVelocity == 0) {
  175. if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
  176. return;
  177. }
  178. embeddedInPlane = true;
  179. t0 = 0;
  180. }
  181. else {
  182. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  183. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  184. if (t0 > t1) {
  185. var temp = t1;
  186. t1 = t0;
  187. t0 = temp;
  188. }
  189. if (t0 > 1.0 || t1 < 0.0) {
  190. return;
  191. }
  192. if (t0 < 0) {
  193. t0 = 0;
  194. }
  195. if (t0 > 1.0) {
  196. t0 = 1.0;
  197. }
  198. }
  199. this._collisionPoint.copyFromFloats(0, 0, 0);
  200. var found = false;
  201. var t = 1.0;
  202. if (!embeddedInPlane) {
  203. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  204. this._velocity.scaleToRef(t0, this._tempVector);
  205. this._planeIntersectionPoint.addInPlace(this._tempVector);
  206. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  207. found = true;
  208. t = t0;
  209. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  210. }
  211. }
  212. if (!found) {
  213. var velocitySquaredLength = this._velocity.lengthSquared();
  214. var a = velocitySquaredLength;
  215. this._basePoint.subtractToRef(p1, this._tempVector);
  216. var b = 2.0 * (Vector3.Dot(this._velocity, this._tempVector));
  217. var c = this._tempVector.lengthSquared() - 1.0;
  218. var lowestRoot = getLowestRoot(a, b, c, t);
  219. if (lowestRoot.found) {
  220. t = lowestRoot.root;
  221. found = true;
  222. this._collisionPoint.copyFrom(p1);
  223. }
  224. this._basePoint.subtractToRef(p2, this._tempVector);
  225. b = 2.0 * (Vector3.Dot(this._velocity, this._tempVector));
  226. c = this._tempVector.lengthSquared() - 1.0;
  227. lowestRoot = getLowestRoot(a, b, c, t);
  228. if (lowestRoot.found) {
  229. t = lowestRoot.root;
  230. found = true;
  231. this._collisionPoint.copyFrom(p2);
  232. }
  233. this._basePoint.subtractToRef(p3, this._tempVector);
  234. b = 2.0 * (Vector3.Dot(this._velocity, this._tempVector));
  235. c = this._tempVector.lengthSquared() - 1.0;
  236. lowestRoot = getLowestRoot(a, b, c, t);
  237. if (lowestRoot.found) {
  238. t = lowestRoot.root;
  239. found = true;
  240. this._collisionPoint.copyFrom(p3);
  241. }
  242. p2.subtractToRef(p1, this._edge);
  243. p1.subtractToRef(this._basePoint, this._baseToVertex);
  244. var edgeSquaredLength = this._edge.lengthSquared();
  245. var edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
  246. var edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
  247. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  248. b = edgeSquaredLength * (2.0 * Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  249. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  250. lowestRoot = getLowestRoot(a, b, c, t);
  251. if (lowestRoot.found) {
  252. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  253. if (f >= 0.0 && f <= 1.0) {
  254. t = lowestRoot.root;
  255. found = true;
  256. this._edge.scaleInPlace(f);
  257. p1.addToRef(this._edge, this._collisionPoint);
  258. }
  259. }
  260. p3.subtractToRef(p2, this._edge);
  261. p2.subtractToRef(this._basePoint, this._baseToVertex);
  262. edgeSquaredLength = this._edge.lengthSquared();
  263. edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
  264. edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
  265. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  266. b = edgeSquaredLength * (2.0 * Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  267. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  268. lowestRoot = getLowestRoot(a, b, c, t);
  269. if (lowestRoot.found) {
  270. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  271. if (f >= 0.0 && f <= 1.0) {
  272. t = lowestRoot.root;
  273. found = true;
  274. this._edge.scaleInPlace(f);
  275. p2.addToRef(this._edge, this._collisionPoint);
  276. }
  277. }
  278. p1.subtractToRef(p3, this._edge);
  279. p3.subtractToRef(this._basePoint, this._baseToVertex);
  280. edgeSquaredLength = this._edge.lengthSquared();
  281. edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);
  282. edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);
  283. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  284. b = edgeSquaredLength * (2.0 * Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  285. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  286. lowestRoot = getLowestRoot(a, b, c, t);
  287. if (lowestRoot.found) {
  288. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  289. if (f >= 0.0 && f <= 1.0) {
  290. t = lowestRoot.root;
  291. found = true;
  292. this._edge.scaleInPlace(f);
  293. p3.addToRef(this._edge, this._collisionPoint);
  294. }
  295. }
  296. }
  297. if (found) {
  298. var distToCollision = t * this._velocity.length();
  299. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  300. // if collisionResponse is false, collision is not found but the collidedMesh is set anyway.
  301. // onCollide observable are triggered if collideMesh is set
  302. // this allow trigger volumes to be created.
  303. if (hostMesh.collisionResponse) {
  304. if (!this.intersectionPoint) {
  305. this.intersectionPoint = this._collisionPoint.clone();
  306. } else {
  307. this.intersectionPoint.copyFrom(this._collisionPoint);
  308. }
  309. this._nearestDistance = distToCollision;
  310. this.collisionFound = true;
  311. }
  312. this.collidedMesh = hostMesh;
  313. }
  314. }
  315. }
  316. /** @hidden */
  317. public _collide(trianglePlaneArray: Array<Plane>, pts: Vector3[], indices: IndicesArray, indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean, hostMesh: AbstractMesh): void {
  318. if (!indices || indices.length === 0) {
  319. for (let i = 0; i < pts.length; i += 3) {
  320. const p1 = pts[i];
  321. const p2 = pts[i + 1];
  322. const p3 = pts[i + 2];
  323. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);
  324. }
  325. } else {
  326. for (let i = indexStart; i < indexEnd; i += 3) {
  327. const p1 = pts[indices[i] - decal];
  328. const p2 = pts[indices[i + 1] - decal];
  329. const p3 = pts[indices[i + 2] - decal];
  330. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);
  331. }
  332. }
  333. }
  334. /** @hidden */
  335. public _getResponse(pos: Vector3, vel: Vector3): void {
  336. pos.addToRef(vel, this._destinationPoint);
  337. vel.scaleInPlace((this._nearestDistance / vel.length()));
  338. this._basePoint.addToRef(vel, pos);
  339. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  340. this._slidePlaneNormal.normalize();
  341. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  342. pos.addInPlace(this._displacementVector);
  343. this.intersectionPoint.addInPlace(this._displacementVector);
  344. this._slidePlaneNormal.scaleInPlace(Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  345. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  346. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  347. }
  348. }