babylon.cannonJSPlugin.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var CannonJSPlugin = (function () {
  4. function CannonJSPlugin(_useDeltaForWorldStep) {
  5. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  6. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  7. this._registeredMeshes = [];
  8. this._physicsMaterials = [];
  9. this._fixedTimeStep = 1 / 60;
  10. //private _maxSubSteps : number = 15;
  11. this.name = "CannonJS";
  12. this.updateBodyPosition = function (mesh) {
  13. for (var index = 0; index < this._registeredMeshes.length; index++) {
  14. var registeredMesh = this._registeredMeshes[index];
  15. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16. var body = registeredMesh.body;
  17. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  18. body.quaternion.copy(mesh.rotationQuaternion);
  19. if (registeredMesh.deltaRotation) {
  20. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  21. body.quaternion = body.quaternion.mult(tmpQ);
  22. }
  23. if (registeredMesh.type === CANNON.Shape.types.HEIGHTFIELD) {
  24. //calculate the correct body position:
  25. var rotationQuaternion = mesh.rotationQuaternion;
  26. mesh.rotationQuaternion = new BABYLON.Quaternion();
  27. mesh.computeWorldMatrix(true);
  28. //get original center with no rotation
  29. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  30. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  31. //rotation is back
  32. mesh.rotationQuaternion = rotationQuaternion;
  33. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  35. mesh.setPivotMatrix(p);
  36. mesh.computeWorldMatrix(true);
  37. //calculate the translation
  38. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  39. center.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40. //add it inverted to the delta
  41. registeredMesh.delta = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  42. registeredMesh.delta.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  43. mesh.setPivotMatrix(oldPivot);
  44. mesh.computeWorldMatrix(true);
  45. }
  46. else if (registeredMesh.type === CANNON.Shape.types.TRIMESH) {
  47. center.copyFromFloats(mesh.position.x, mesh.position.y, mesh.position.z);
  48. }
  49. body.position.set(center.x, center.y, center.z);
  50. return;
  51. }
  52. }
  53. };
  54. }
  55. CannonJSPlugin.prototype.initialize = function (iterations) {
  56. if (iterations === void 0) { iterations = 10; }
  57. this._world = new CANNON.World();
  58. this._world.broadphase = new CANNON.NaiveBroadphase();
  59. this._world.solver.iterations = iterations;
  60. };
  61. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  62. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  63. };
  64. CannonJSPlugin.prototype.runOneStep = function (delta) {
  65. var _this = this;
  66. this._world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  67. this._registeredMeshes.forEach(function (registeredMesh) {
  68. // Body position
  69. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  70. registeredMesh.mesh.position.x = bodyX + registeredMesh.delta.x;
  71. registeredMesh.mesh.position.y = bodyY + registeredMesh.delta.y;
  72. registeredMesh.mesh.position.z = bodyZ + registeredMesh.delta.z;
  73. registeredMesh.mesh.rotationQuaternion.copyFrom(registeredMesh.body.quaternion);
  74. if (registeredMesh.deltaRotation) {
  75. registeredMesh.mesh.rotationQuaternion.multiplyInPlace(registeredMesh.deltaRotation);
  76. }
  77. //is the physics collision callback is set?
  78. if (registeredMesh.mesh.onPhysicsCollide) {
  79. if (!registeredMesh.collisionFunction) {
  80. registeredMesh.collisionFunction = function (e) {
  81. //find the mesh that collided with the registered mesh
  82. for (var idx = 0; idx < _this._registeredMeshes.length; idx++) {
  83. if (_this._registeredMeshes[idx].body == e.body) {
  84. registeredMesh.mesh.onPhysicsCollide(_this._registeredMeshes[idx].mesh, e.contact);
  85. }
  86. }
  87. };
  88. registeredMesh.body.addEventListener("collide", registeredMesh.collisionFunction);
  89. }
  90. }
  91. else {
  92. //unregister, in case the function was removed for some reason
  93. if (registeredMesh.collisionFunction) {
  94. registeredMesh.body.removeEventListener("collide", registeredMesh.collisionFunction);
  95. }
  96. }
  97. });
  98. };
  99. CannonJSPlugin.prototype.setGravity = function (gravity) {
  100. this._gravity = gravity;
  101. this._world.gravity.set(gravity.x, gravity.y, gravity.z);
  102. };
  103. CannonJSPlugin.prototype.getGravity = function () {
  104. return this._gravity;
  105. };
  106. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  107. this.unregisterMesh(mesh);
  108. if (!mesh.rotationQuaternion) {
  109. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  110. }
  111. mesh.computeWorldMatrix(true);
  112. var shape = this._createShape(mesh, impostor);
  113. return this._createRigidBodyFromShape(shape, mesh, options);
  114. };
  115. CannonJSPlugin.prototype._createShape = function (mesh, impostor) {
  116. //get the correct bounding box
  117. var oldQuaternion = mesh.rotationQuaternion;
  118. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  119. mesh.computeWorldMatrix(true);
  120. var returnValue;
  121. switch (impostor) {
  122. case BABYLON.PhysicsEngine.SphereImpostor:
  123. var bbox = mesh.getBoundingInfo().boundingBox;
  124. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  125. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  126. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  127. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  128. break;
  129. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  130. case BABYLON.PhysicsEngine.CylinderImpostor:
  131. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  132. case BABYLON.PhysicsEngine.BoxImpostor:
  133. bbox = mesh.getBoundingInfo().boundingBox;
  134. var min = bbox.minimumWorld;
  135. var max = bbox.maximumWorld;
  136. var box = max.subtract(min).scale(0.5);
  137. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  138. break;
  139. case BABYLON.PhysicsEngine.PlaneImpostor:
  140. BABYLON.Tools.Warn("Attention, Cannon.js PlaneImposter might not behave as you wish. Consider using BoxImposter instead");
  141. returnValue = new CANNON.Plane();
  142. break;
  143. case BABYLON.PhysicsEngine.MeshImpostor:
  144. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  145. var rawFaces = mesh.getIndices();
  146. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  147. returnValue = new CANNON.Trimesh(rawVerts, rawFaces); //this._createConvexPolyhedron(rawVerts, rawFaces, mesh);
  148. break;
  149. case BABYLON.PhysicsEngine.HeightmapImpostor:
  150. returnValue = this._createHeightmap(mesh);
  151. break;
  152. }
  153. mesh.rotationQuaternion = oldQuaternion;
  154. return returnValue;
  155. };
  156. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh) {
  157. var verts = [], faces = [];
  158. mesh.computeWorldMatrix(true);
  159. //reuse this variable
  160. var transformed = BABYLON.Vector3.Zero();
  161. // Get vertices
  162. for (var i = 0; i < rawVerts.length; i += 3) {
  163. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  164. verts.push(new CANNON.Vec3(transformed.x, transformed.y, transformed.z));
  165. }
  166. // Get faces
  167. for (var j = 0; j < rawFaces.length; j += 3) {
  168. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  169. }
  170. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  171. return shape;
  172. };
  173. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  174. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  175. var matrix = [];
  176. //For now pointDepth will not be used and will be automatically calculated.
  177. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  178. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  179. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  180. var elementSize = dim * 2 / arraySize;
  181. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  182. for (var i = 0; i < pos.length; i = i + 3) {
  183. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  184. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  185. var y = pos[i + 1] + minY;
  186. if (!matrix[x]) {
  187. matrix[x] = [];
  188. }
  189. if (!matrix[x][z]) {
  190. matrix[x][z] = y;
  191. }
  192. matrix[x][z] = Math.max(y, matrix[x][z]);
  193. }
  194. for (var x = 0; x <= arraySize; ++x) {
  195. if (!matrix[x]) {
  196. var loc = 1;
  197. while (!matrix[(x + loc) % arraySize]) {
  198. loc++;
  199. }
  200. matrix[x] = matrix[(x + loc) % arraySize].slice();
  201. }
  202. for (var z = 0; z <= arraySize; ++z) {
  203. if (!matrix[x][z]) {
  204. var loc = 1;
  205. var newValue;
  206. while (newValue === undefined) {
  207. newValue = matrix[x][(z + loc++) % arraySize];
  208. }
  209. matrix[x][z] = newValue;
  210. }
  211. }
  212. }
  213. var shape = new CANNON.Heightfield(matrix, {
  214. elementSize: elementSize
  215. });
  216. //For future reference, needed for body transformation
  217. shape.minY = minY;
  218. return shape;
  219. };
  220. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  221. var index;
  222. var mat;
  223. for (index = 0; index < this._physicsMaterials.length; index++) {
  224. mat = this._physicsMaterials[index];
  225. if (mat.friction === friction && mat.restitution === restitution) {
  226. return mat;
  227. }
  228. }
  229. var currentMat = new CANNON.Material("mat");
  230. this._physicsMaterials.push(currentMat);
  231. for (index = 0; index < this._physicsMaterials.length; index++) {
  232. mat = this._physicsMaterials[index];
  233. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  234. this._world.addContactMaterial(contactMaterial);
  235. }
  236. return currentMat;
  237. };
  238. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, options) {
  239. if (!mesh.rotationQuaternion) {
  240. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  241. }
  242. // The delta between the mesh position and the mesh bounding box center
  243. var bbox = mesh.getBoundingInfo().boundingBox;
  244. var deltaPosition = mesh.position.subtract(bbox.center);
  245. var deltaRotation;
  246. var material = this._addMaterial(options.friction, options.restitution);
  247. var body = new CANNON.Body({
  248. mass: options.mass,
  249. material: material,
  250. position: new CANNON.Vec3(bbox.center.x, bbox.center.y, bbox.center.z)
  251. });
  252. body.quaternion = new CANNON.Quaternion(mesh.rotationQuaternion.x, mesh.rotationQuaternion.y, mesh.rotationQuaternion.z, mesh.rotationQuaternion.w);
  253. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  254. if (shape.type === CANNON.Shape.types.PLANE || shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  255. //-90 DEG in X, precalculated
  256. var tmpQ = new CANNON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  257. body.quaternion = body.quaternion.mult(tmpQ);
  258. //Invert! (Precalculated, 90 deg in X)
  259. deltaRotation = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  260. }
  261. //If it is a heightfield, if should be centered.
  262. if (shape.type === CANNON.Shape.types.HEIGHTFIELD) {
  263. //calculate the correct body position:
  264. var rotationQuaternion = mesh.rotationQuaternion;
  265. mesh.rotationQuaternion = new BABYLON.Quaternion();
  266. mesh.computeWorldMatrix(true);
  267. //get original center with no rotation
  268. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  269. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  270. //rotation is back
  271. mesh.rotationQuaternion = rotationQuaternion;
  272. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  273. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  274. mesh.setPivotMatrix(p);
  275. mesh.computeWorldMatrix(true);
  276. //calculate the translation
  277. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  278. body.position = new CANNON.Vec3(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  279. //add it inverted to the delta
  280. deltaPosition = mesh.getBoundingInfo().boundingBox.center.subtract(center);
  281. deltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  282. mesh.setPivotMatrix(oldPivot);
  283. mesh.computeWorldMatrix(true);
  284. }
  285. else if (shape.type === CANNON.Shape.types.TRIMESH) {
  286. deltaPosition = BABYLON.Vector3.Zero();
  287. }
  288. //add the shape
  289. body.addShape(shape);
  290. this._world.add(body);
  291. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition, deltaRotation: deltaRotation, type: shape.type });
  292. return body;
  293. };
  294. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  295. var initialMesh = parts[0].mesh;
  296. this.unregisterMesh(initialMesh);
  297. initialMesh.computeWorldMatrix(true);
  298. var initialShape = this._createShape(initialMesh, parts[0].impostor);
  299. var body = this._createRigidBodyFromShape(initialShape, initialMesh, options);
  300. for (var index = 1; index < parts.length; index++) {
  301. var mesh = parts[index].mesh;
  302. mesh.computeWorldMatrix(true);
  303. var shape = this._createShape(mesh, parts[index].impostor);
  304. var localPosition = mesh.position;
  305. body.addShape(shape, new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  306. }
  307. return body;
  308. };
  309. CannonJSPlugin.prototype._unbindBody = function (body) {
  310. for (var index = 0; index < this._registeredMeshes.length; index++) {
  311. var registeredMesh = this._registeredMeshes[index];
  312. if (registeredMesh.body === body) {
  313. this._world.remove(registeredMesh.body);
  314. registeredMesh.body = null;
  315. registeredMesh.delta = null;
  316. registeredMesh.deltaRotation = null;
  317. }
  318. }
  319. };
  320. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  321. for (var index = 0; index < this._registeredMeshes.length; index++) {
  322. var registeredMesh = this._registeredMeshes[index];
  323. if (registeredMesh.mesh === mesh) {
  324. // Remove body
  325. if (registeredMesh.body) {
  326. this._unbindBody(registeredMesh.body);
  327. }
  328. this._registeredMeshes.splice(index, 1);
  329. return;
  330. }
  331. }
  332. };
  333. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  334. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  335. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  336. for (var index = 0; index < this._registeredMeshes.length; index++) {
  337. var registeredMesh = this._registeredMeshes[index];
  338. if (registeredMesh.mesh === mesh) {
  339. registeredMesh.body.applyImpulse(impulse, worldPoint);
  340. return;
  341. }
  342. }
  343. };
  344. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  345. var body1 = null, body2 = null;
  346. for (var index = 0; index < this._registeredMeshes.length; index++) {
  347. var registeredMesh = this._registeredMeshes[index];
  348. if (registeredMesh.mesh === mesh1) {
  349. body1 = registeredMesh.body;
  350. if (body2)
  351. break;
  352. }
  353. else if (registeredMesh.mesh === mesh2) {
  354. body2 = registeredMesh.body;
  355. if (body1)
  356. break;
  357. }
  358. }
  359. if (!body1 || !body2) {
  360. return false;
  361. }
  362. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.y, pivot1.z), body2, new CANNON.Vec3(pivot2.x, pivot2.y, pivot2.z));
  363. this._world.addConstraint(constraint);
  364. return true;
  365. };
  366. CannonJSPlugin.prototype.dispose = function () {
  367. while (this._registeredMeshes.length) {
  368. this.unregisterMesh(this._registeredMeshes[0].mesh);
  369. }
  370. };
  371. CannonJSPlugin.prototype.isSupported = function () {
  372. return window.CANNON !== undefined;
  373. };
  374. CannonJSPlugin.prototype.getWorldObject = function () {
  375. return this._world;
  376. };
  377. CannonJSPlugin.prototype.getPhysicsBodyOfMesh = function (mesh) {
  378. for (var index = 0; index < this._registeredMeshes.length; index++) {
  379. var registeredMesh = this._registeredMeshes[index];
  380. if (registeredMesh.mesh === mesh) {
  381. return registeredMesh.body;
  382. }
  383. }
  384. return null;
  385. };
  386. return CannonJSPlugin;
  387. })();
  388. BABYLON.CannonJSPlugin = CannonJSPlugin;
  389. })(BABYLON || (BABYLON = {}));