babylon.collisionWorker.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. for (var uniqueId in meshes) {
  51. if (meshes.hasOwnProperty(uniqueId) && parseInt(uniqueId) != excludedMeshUniqueId) {
  52. var mesh = meshes[uniqueId];
  53. if (mesh.checkCollisions)
  54. this.checkCollision(mesh);
  55. }
  56. }
  57. if (!this.collider.collisionFound) {
  58. position.addToRef(velocity, this.finalPosition);
  59. return;
  60. }
  61. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  62. this.collider._getResponse(position, velocity);
  63. }
  64. if (velocity.length() <= closeDistance) {
  65. this.finalPosition.copyFrom(position);
  66. return;
  67. }
  68. this.collider.retry++;
  69. this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
  70. };
  71. CollideWorker.prototype.checkCollision = function (mesh) {
  72. if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
  73. return;
  74. }
  75. ;
  76. // Transformation matrix
  77. BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
  78. var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
  79. worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
  80. this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
  81. //return colTransMat;
  82. };
  83. CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
  84. var len;
  85. var subMeshes;
  86. // 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. subMeshes = mesh.subMeshes;
  94. 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. //Unneeded
  111. //subMesh['getMesh'] = function () {
  112. // return mesh.uniqueId;
  113. //}
  114. this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
  115. }
  116. };
  117. CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
  118. var positionsArray = [];
  119. for (var i = 0; i < meshGeometry.positions.length; i = i + 3) {
  120. var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
  121. positionsArray.push(p);
  122. }
  123. subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
  124. //The following two arrays should be initialized CORRECTLY to save some calculation time.
  125. subMesh['_lastColliderWorldVertices'] = [];
  126. subMesh['_trianglePlanes'] = [];
  127. var start = subMesh.verticesStart;
  128. var end = (subMesh.verticesStart + subMesh.verticesCount);
  129. for (var i = start; i < end; i++) {
  130. subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(positionsArray[i], transformMatrix));
  131. }
  132. //}
  133. // Collide
  134. this.collider._collide(subMesh['_trianglePlanes'] = [], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
  135. };
  136. //TODO - this! :-)
  137. CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
  138. return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
  139. };
  140. return CollideWorker;
  141. })();
  142. BABYLON.CollideWorker = CollideWorker;
  143. var CollisionDetectorTransferable = (function () {
  144. function CollisionDetectorTransferable() {
  145. }
  146. CollisionDetectorTransferable.prototype.onInit = function (payload) {
  147. this._collisionCache = new CollisionCache();
  148. var reply = {
  149. error: 0 /* SUCCESS */,
  150. taskType: 0 /* INIT */
  151. };
  152. postMessage(reply, undefined);
  153. };
  154. CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
  155. for (var id in payload.updatedGeometries) {
  156. if (payload.updatedGeometries.hasOwnProperty(id)) {
  157. this._collisionCache.addGeometry(payload.updatedGeometries[id]);
  158. }
  159. }
  160. for (var uniqueId in payload.updatedMeshes) {
  161. if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
  162. this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
  163. }
  164. }
  165. var replay = {
  166. error: 0 /* SUCCESS */,
  167. taskType: 1 /* UPDATE */
  168. };
  169. postMessage(replay, undefined);
  170. };
  171. CollisionDetectorTransferable.prototype.onCollision = function (payload) {
  172. var finalPosition = BABYLON.Vector3.Zero();
  173. //create a new collider
  174. var collider = new BABYLON.Collider();
  175. collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
  176. var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
  177. colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
  178. var replyPayload = {
  179. collidedMeshUniqueId: collider.collidedMesh,
  180. collisionId: payload.collisionId,
  181. newPosition: finalPosition.asArray()
  182. };
  183. var reply = {
  184. error: 0 /* SUCCESS */,
  185. taskType: 2 /* COLLIDE */,
  186. payload: replyPayload
  187. };
  188. postMessage(reply, undefined);
  189. };
  190. return CollisionDetectorTransferable;
  191. })();
  192. BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
  193. try {
  194. if (self && self instanceof WorkerGlobalScope) {
  195. //Window hack to allow including babylonjs native code. the <any> is for typescript.
  196. window = {};
  197. //scripts were not included, standalone worker
  198. if (!BABYLON.Collider) {
  199. importScripts("./babylon.collisionCoordinator.js");
  200. importScripts("./babylon.collider.js");
  201. importScripts("../Math/babylon.math.js");
  202. }
  203. var collisionDetector = new CollisionDetectorTransferable();
  204. var onNewMessage = function (event) {
  205. var message = event.data;
  206. switch (message.taskType) {
  207. case 0 /* INIT */:
  208. collisionDetector.onInit(message.payload);
  209. break;
  210. case 2 /* COLLIDE */:
  211. collisionDetector.onCollision(message.payload);
  212. break;
  213. case 1 /* UPDATE */:
  214. collisionDetector.onUpdate(message.payload);
  215. break;
  216. }
  217. };
  218. self.onmessage = onNewMessage;
  219. }
  220. }
  221. catch (e) {
  222. console.log("single worker init");
  223. }
  224. })(BABYLON || (BABYLON = {}));
  225. //# sourceMappingURL=babylon.collisionWorker.js.map