babylon.collisionWorker.js 11 KB

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