babylon.cannonJSPlugin.js 20 KB

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