collisionWorker.ts 12 KB

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