babylon.collisionWorker.ts 11 KB

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