babylon.collisionWorker.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. if (this.collider.collisionFound) {
  116. this.collider.collidedMesh = mesh.id;
  117. }
  118. }
  119. };
  120. CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
  121. if (!meshGeometry['positionsArray']) {
  122. meshGeometry['positionsArray'] = [];
  123. for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
  124. var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
  125. meshGeometry['positionsArray'].push(p);
  126. }
  127. }
  128. if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
  129. subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
  130. subMesh['_lastColliderWorldVertices'] = [];
  131. subMesh['_trianglePlanes'] = [];
  132. var start = subMesh.verticesStart;
  133. var end = (subMesh.verticesStart + subMesh.verticesCount);
  134. for (var i = start; i < end; i++) {
  135. subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(meshGeometry['positionsArray'][i], transformMatrix));
  136. }
  137. }
  138. // Collide
  139. this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
  140. };
  141. CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
  142. return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
  143. };
  144. return CollideWorker;
  145. })();
  146. BABYLON.CollideWorker = CollideWorker;
  147. var CollisionDetectorTransferable = (function () {
  148. function CollisionDetectorTransferable() {
  149. }
  150. CollisionDetectorTransferable.prototype.onInit = function (payload) {
  151. this._collisionCache = new CollisionCache();
  152. var reply = {
  153. error: 0 /* SUCCESS */,
  154. taskType: 0 /* INIT */
  155. };
  156. postMessage(reply, undefined);
  157. };
  158. CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
  159. for (var id in payload.updatedGeometries) {
  160. if (payload.updatedGeometries.hasOwnProperty(id)) {
  161. this._collisionCache.addGeometry(payload.updatedGeometries[id]);
  162. }
  163. }
  164. for (var uniqueId in payload.updatedMeshes) {
  165. if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
  166. this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
  167. }
  168. }
  169. var replay = {
  170. error: 0 /* SUCCESS */,
  171. taskType: 1 /* UPDATE */
  172. };
  173. postMessage(replay, undefined);
  174. };
  175. CollisionDetectorTransferable.prototype.onCollision = function (payload) {
  176. var finalPosition = BABYLON.Vector3.Zero();
  177. //create a new collider
  178. var collider = new BABYLON.Collider();
  179. collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
  180. var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
  181. colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
  182. var replyPayload = {
  183. collidedMeshUniqueId: collider.collidedMesh,
  184. collisionId: payload.collisionId,
  185. newPosition: finalPosition.asArray()
  186. };
  187. var reply = {
  188. error: 0 /* SUCCESS */,
  189. taskType: 2 /* COLLIDE */,
  190. payload: replyPayload
  191. };
  192. postMessage(reply, undefined);
  193. };
  194. return CollisionDetectorTransferable;
  195. })();
  196. BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
  197. try {
  198. if (self && self instanceof WorkerGlobalScope) {
  199. //Window hack to allow including babylonjs native code. the <any> is for typescript.
  200. window = {};
  201. //scripts were not included, standalone worker
  202. if (!BABYLON.Collider) {
  203. importScripts("./babylon.collisionCoordinator.js");
  204. importScripts("./babylon.collider.js");
  205. importScripts("../Math/babylon.math.js");
  206. }
  207. var collisionDetector = new CollisionDetectorTransferable();
  208. var onNewMessage = function (event) {
  209. var message = event.data;
  210. switch (message.taskType) {
  211. case 0 /* INIT */:
  212. collisionDetector.onInit(message.payload);
  213. break;
  214. case 2 /* COLLIDE */:
  215. collisionDetector.onCollision(message.payload);
  216. break;
  217. case 1 /* UPDATE */:
  218. collisionDetector.onUpdate(message.payload);
  219. break;
  220. }
  221. };
  222. self.onmessage = onNewMessage;
  223. }
  224. }
  225. catch (e) {
  226. console.log("single worker init");
  227. }
  228. })(BABYLON || (BABYLON = {}));