babylon.cannonJSPlugin.js 19 KB

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