babylon.collisionWorker.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. declare function importScripts(...urls: string[]): void;
  2. module BABYLON {
  3. //If this file is included in the main thread, this will be initialized.
  4. export var WorkerIncluded: boolean = true;
  5. export class CollisionCache {
  6. private _meshes: { [n: string]: SerializedMesh; } = {};
  7. private _geometries: { [s: string]: SerializedGeometry; } = {};
  8. public getMeshes(): { [n: number]: SerializedMesh; } {
  9. return this._meshes;
  10. }
  11. public getGeometries(): { [s: number]: SerializedGeometry; } {
  12. return this._geometries;
  13. }
  14. public getMesh(id: any): SerializedMesh {
  15. return this._meshes[id];
  16. }
  17. public addMesh(mesh: SerializedMesh) {
  18. this._meshes[mesh.uniqueId] = mesh;
  19. }
  20. public removeMesh(uniqueId: number) {
  21. delete this._meshes[uniqueId];
  22. }
  23. public getGeometry(id: string): SerializedGeometry {
  24. return this._geometries[id];
  25. }
  26. public addGeometry(geometry: SerializedGeometry) {
  27. this._geometries[geometry.id] = geometry;
  28. }
  29. public removeGeometry(id: string) {
  30. delete this._geometries[id];
  31. }
  32. }
  33. export class CollideWorker {
  34. private collisionsScalingMatrix = Matrix.Zero();
  35. private collisionTranformationMatrix = Matrix.Zero();
  36. constructor(public collider: Collider, private _collisionCache: CollisionCache, private finalPosition: Vector3) {
  37. }
  38. public collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId: Nullable<number>) {
  39. //TODO CollisionsEpsilon should be defined here and not in the engine.
  40. const closeDistance = 0.01; //is initializing here correct? A quick look - looks like it is fine.
  41. if (this.collider.retry >= maximumRetry) {
  42. this.finalPosition.copyFrom(position);
  43. return;
  44. }
  45. this.collider._initialize(position, velocity, closeDistance);
  46. // Check all meshes
  47. var meshes = this._collisionCache.getMeshes();
  48. var keys = Object.keys(meshes);
  49. var len = keys.length;
  50. var uniqueId: string;
  51. for (var i = 0; i < len; ++i) {
  52. uniqueId = keys[i];
  53. if (parseInt(uniqueId) != excludedMeshUniqueId) {
  54. var mesh: SerializedMesh = (<any>meshes)[uniqueId];
  55. if (mesh.checkCollisions)
  56. this.checkCollision(mesh);
  57. }
  58. }
  59. if (!this.collider.collisionFound) {
  60. position.addToRef(velocity, this.finalPosition);
  61. return;
  62. }
  63. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  64. this.collider._getResponse(position, velocity);
  65. }
  66. if (velocity.length() <= closeDistance) {
  67. this.finalPosition.copyFrom(position);
  68. return;
  69. }
  70. this.collider.retry++;
  71. this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
  72. }
  73. private checkCollision(mesh: SerializedMesh) {
  74. if (!this.collider._canDoCollision(Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, Vector3.FromArray(mesh.boxMinimum), Vector3.FromArray(mesh.boxMaximum))) {
  75. return;
  76. };
  77. // Transformation matrix
  78. Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
  79. var worldFromCache = Matrix.FromArray(mesh.worldMatrixFromCache);
  80. worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
  81. this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
  82. //return colTransMat;
  83. }
  84. private processCollisionsForSubMeshes(transformMatrix: Matrix, mesh: SerializedMesh): void { // No Octrees for now
  85. //if (this._submeshesOctree && this.useOctreeForCollisions) {
  86. // var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  87. // var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  88. // len = intersections.length;
  89. // subMeshes = intersections.data;
  90. //} else {
  91. var subMeshes = mesh.subMeshes;
  92. var len = subMeshes.length;
  93. //}
  94. if (!mesh.geometryId) {
  95. console.log("no mesh geometry id");
  96. return;
  97. }
  98. var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
  99. if (!meshGeometry) {
  100. console.log("couldn't find geometry", mesh.geometryId);
  101. return;
  102. }
  103. for (var index = 0; index < len; index++) {
  104. var subMesh = subMeshes[index];
  105. // Bounding test
  106. if (len > 1 && !this.checkSubmeshCollision(subMesh))
  107. continue;
  108. this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
  109. if (this.collider.collisionFound) {
  110. this.collider.collidedMesh = <any>mesh.uniqueId;
  111. }
  112. }
  113. }
  114. private collideForSubMesh(subMesh: SerializedSubMesh, transformMatrix: Matrix, meshGeometry: SerializedGeometry): void {
  115. if (!(<any>meshGeometry)['positionsArray']) {
  116. (<any>meshGeometry)['positionsArray'] = [];
  117. for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
  118. var p = Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
  119. (<any>meshGeometry)['positionsArray'].push(p);
  120. }
  121. }
  122. if (!(<any>subMesh)['_lastColliderWorldVertices'] || !(<any>subMesh)['_lastColliderTransformMatrix'].equals(transformMatrix)) {
  123. (<any>subMesh)['_lastColliderTransformMatrix'] = transformMatrix.clone();
  124. (<any>subMesh)['_lastColliderWorldVertices'] = [];
  125. (<any>subMesh)['_trianglePlanes'] = [];
  126. var start = subMesh.verticesStart;
  127. var end = (subMesh.verticesStart + subMesh.verticesCount);
  128. for (var i = start; i < end; i++) {
  129. (<any>subMesh)['_lastColliderWorldVertices'].push(Vector3.TransformCoordinates((<any>meshGeometry)['positionsArray'][i], transformMatrix));
  130. }
  131. }
  132. // Collide
  133. this.collider._collide((<any>subMesh)['_trianglePlanes'], (<any>subMesh)['_lastColliderWorldVertices'], <any>meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
  134. }
  135. private checkSubmeshCollision(subMesh: SerializedSubMesh): boolean {
  136. return this.collider._canDoCollision(Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, Vector3.FromArray(subMesh.boxMinimum), Vector3.FromArray(subMesh.boxMaximum));
  137. }
  138. }
  139. export interface ICollisionDetector {
  140. onInit(payload: InitPayload): void;
  141. onUpdate(payload: UpdatePayload): void;
  142. onCollision(payload: CollidePayload): void;
  143. }
  144. export class CollisionDetectorTransferable implements ICollisionDetector {
  145. private _collisionCache: CollisionCache;
  146. public onInit(payload: InitPayload) {
  147. this._collisionCache = new CollisionCache();
  148. var reply: WorkerReply = {
  149. error: WorkerReplyType.SUCCESS,
  150. taskType: WorkerTaskType.INIT
  151. }
  152. postMessage(reply, "");
  153. }
  154. public onUpdate(payload: UpdatePayload) {
  155. var replay: WorkerReply = {
  156. error: WorkerReplyType.SUCCESS,
  157. taskType: WorkerTaskType.UPDATE
  158. }
  159. try {
  160. for (var id in payload.updatedGeometries) {
  161. if (payload.updatedGeometries.hasOwnProperty(id)) {
  162. this._collisionCache.addGeometry(payload.updatedGeometries[id]);
  163. }
  164. }
  165. for (var uniqueId in payload.updatedMeshes) {
  166. if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
  167. this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
  168. }
  169. }
  170. payload.removedGeometries.forEach((id) => {
  171. this._collisionCache.removeGeometry(id);
  172. });
  173. payload.removedMeshes.forEach((uniqueId) => {
  174. this._collisionCache.removeMesh(uniqueId);
  175. });
  176. } catch (x) {
  177. replay.error = WorkerReplyType.UNKNOWN_ERROR;
  178. }
  179. postMessage(replay, "");
  180. }
  181. public onCollision(payload: CollidePayload) {
  182. var finalPosition = Vector3.Zero();
  183. //create a new collider
  184. var collider = new Collider();
  185. collider.radius = Vector3.FromArray(payload.collider.radius);
  186. var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
  187. colliderWorker.collideWithWorld(Vector3.FromArray(payload.collider.position), Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
  188. var replyPayload: CollisionReplyPayload = {
  189. collidedMeshUniqueId: <any>collider.collidedMesh,
  190. collisionId: payload.collisionId,
  191. newPosition: finalPosition.asArray()
  192. }
  193. var reply: WorkerReply = {
  194. error: WorkerReplyType.SUCCESS,
  195. taskType: WorkerTaskType.COLLIDE,
  196. payload: replyPayload
  197. }
  198. postMessage(reply, "");
  199. }
  200. }
  201. //TypeScript doesn't know WorkerGlobalScope
  202. declare class WorkerGlobalScope { }
  203. //check if we are in a web worker, as this code should NOT run on the main UI thread
  204. try {
  205. if (self && self instanceof WorkerGlobalScope) {
  206. //Window hack to allow including babylonjs native code. the <any> is for typescript.
  207. window = <any>{};
  208. //scripts were not included, standalone worker
  209. if (!BABYLON.Collider) {
  210. importScripts("./babylon.collisionCoordinator.js");
  211. importScripts("./babylon.collider.js");
  212. importScripts("../Math/babylon.math.js");
  213. }
  214. var collisionDetector: ICollisionDetector = new CollisionDetectorTransferable();
  215. var onNewMessage = (event: MessageEvent) => {
  216. var message = <BabylonMessage>event.data;
  217. switch (message.taskType) {
  218. case WorkerTaskType.INIT:
  219. collisionDetector.onInit(<InitPayload>message.payload);
  220. break;
  221. case WorkerTaskType.COLLIDE:
  222. collisionDetector.onCollision(<CollidePayload>message.payload);
  223. break;
  224. case WorkerTaskType.UPDATE:
  225. collisionDetector.onUpdate(<UpdatePayload>message.payload);
  226. break;
  227. }
  228. }
  229. self.onmessage = onNewMessage;
  230. }
  231. } catch (e) {
  232. console.log("single worker init");
  233. }
  234. }