babylon.collisionWorker.ts 12 KB

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