babylon.cannonJSPlugin.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. module BABYLON {
  2. declare var CANNON;
  3. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  4. public world: any; //CANNON.World
  5. public name: string = "CannonJSPlugin";
  6. private _physicsMaterials = [];
  7. private _fixedTimeStep: number = 1 / 60;
  8. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  9. private _currentCollisionGroup = 2;
  10. public constructor(private _useDeltaForWorldStep: boolean = true, iterations: number = 10) {
  11. if (!this.isSupported()) {
  12. Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  13. return;
  14. }
  15. this.world = new CANNON.World();
  16. this.world.broadphase = new CANNON.NaiveBroadphase();
  17. this.world.solver.iterations = iterations;
  18. }
  19. public setGravity(gravity: Vector3): void {
  20. this.world.gravity.copy(gravity);
  21. }
  22. public executeStep(delta: number, impostors: Array<PhysicsImpostor>): void {
  23. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  24. }
  25. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  26. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  27. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  28. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  29. }
  30. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  31. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  32. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  33. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34. }
  35. public generatePhysicsBody(impostor: PhysicsImpostor) {
  36. //parent-child relationship. Does this impostor has a parent impostor?
  37. if (impostor.parent) {
  38. if (impostor.physicsBody) {
  39. this.removePhysicsBody(impostor);
  40. //TODO is that needed?
  41. impostor.forceUpdate();
  42. }
  43. return;
  44. }
  45. //should a new body be created for this impostor?
  46. if (impostor.isBodyInitRequired()) {
  47. if (!impostor.mesh.rotationQuaternion) {
  48. impostor.mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  49. }
  50. var shape = this._createShape(impostor);
  51. //unregister events, if body is being changed
  52. var oldBody = impostor.physicsBody;
  53. if (oldBody) {
  54. this.removePhysicsBody(impostor);
  55. }
  56. //create the body and material
  57. var material = this._addMaterial(impostor.getParam("friction"), impostor.getParam("restitution"));
  58. var bodyCreationObject = {
  59. mass: impostor.getParam("mass"),
  60. material: material
  61. };
  62. // A simple extend, in case native options were used.
  63. var nativeOptions = impostor.getParam("nativeOptions");
  64. for (var key in nativeOptions) {
  65. if (nativeOptions.hasOwnProperty(key)) {
  66. bodyCreationObject[key] = nativeOptions[key];
  67. }
  68. }
  69. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  70. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71. this.world.addEventListener("preStep", impostor.beforeStep);
  72. this.world.addEventListener("postStep", impostor.afterStep);
  73. impostor.physicsBody.addShape(shape);
  74. this.world.add(impostor.physicsBody);
  75. //try to keep the body moving in the right direction by taking old properties.
  76. //Should be tested!
  77. if (oldBody) {
  78. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  79. impostor.physicsBody[param].copy(oldBody[param]);
  80. });
  81. }
  82. this._processChildMeshes(impostor);
  83. }
  84. //now update the body's transformation
  85. this._updatePhysicsBodyTransformation(impostor);
  86. }
  87. private _processChildMeshes(mainImpostor: PhysicsImpostor) {
  88. var meshChildren = mainImpostor.mesh.getChildMeshes();
  89. if (meshChildren.length) {
  90. var processMesh = (localPosition: Vector3, mesh: AbstractMesh) => {
  91. var childImpostor = mesh.getPhysicsImpostor();
  92. if (childImpostor) {
  93. var parent = childImpostor.parent;
  94. if (parent !== mainImpostor) {
  95. var localPosition = mesh.position;
  96. if (childImpostor.physicsBody) {
  97. this.removePhysicsBody(childImpostor);
  98. childImpostor.physicsBody = null;
  99. }
  100. childImpostor.parent = mainImpostor;
  101. childImpostor.resetUpdateFlags();
  102. mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  103. //Add the mass of the children.
  104. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  105. }
  106. }
  107. mesh.getChildMeshes().forEach(processMesh.bind(this, mesh.position));
  108. }
  109. meshChildren.forEach(processMesh.bind(this, Vector3.Zero()));
  110. }
  111. }
  112. public removePhysicsBody(impostor: PhysicsImpostor) {
  113. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  114. this.world.removeEventListener("preStep", impostor.beforeStep);
  115. this.world.removeEventListener("postStep", impostor.afterStep);
  116. this.world.remove(impostor.physicsBody);
  117. }
  118. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  119. var mainBody = impostorJoint.mainImpostor.physicsBody;
  120. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  121. if (!mainBody || !connectedBody) {
  122. return;
  123. }
  124. var constraint;
  125. var jointData = impostorJoint.joint.jointData;
  126. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  127. var constraintData = {
  128. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  129. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  130. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  131. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  132. maxForce: jointData.nativeParams.maxForce
  133. };
  134. if (!jointData.collision) {
  135. //add 1st body to a collision group of its own, if it is not in 1
  136. if (mainBody.collisionFilterGroup === 1) {
  137. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  138. this._currentCollisionGroup <<= 1;
  139. }
  140. if (connectedBody.collisionFilterGroup === 1) {
  141. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  142. this._currentCollisionGroup <<= 1;
  143. }
  144. //add their mask to the collisionFilterMask of each other:
  145. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  146. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  147. }
  148. switch (impostorJoint.joint.type) {
  149. case PhysicsJoint.HingeJoint:
  150. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  151. break;
  152. case PhysicsJoint.DistanceJoint:
  153. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, (<DistanceJointData>jointData).maxDistance || 2)
  154. break;
  155. default:
  156. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  157. break;
  158. }
  159. impostorJoint.joint.physicsJoint = constraint;
  160. this.world.addConstraint(constraint);
  161. }
  162. public removeJoint(joint: PhysicsImpostorJoint) {
  163. //TODO
  164. }
  165. private _addMaterial(friction: number, restitution: number) {
  166. var index;
  167. var mat;
  168. for (index = 0; index < this._physicsMaterials.length; index++) {
  169. mat = this._physicsMaterials[index];
  170. if (mat.friction === friction && mat.restitution === restitution) {
  171. return mat;
  172. }
  173. }
  174. var currentMat = new CANNON.Material("mat");
  175. this._physicsMaterials.push(currentMat);
  176. for (index = 0; index < this._physicsMaterials.length; index++) {
  177. mat = this._physicsMaterials[index];
  178. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  179. this.world.addContactMaterial(contactMaterial);
  180. }
  181. return currentMat;
  182. }
  183. private _checkWithEpsilon(value: number): number {
  184. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  185. }
  186. private _createShape(impostor: PhysicsImpostor) {
  187. var mesh = impostor.mesh;
  188. //get the correct bounding box
  189. var oldQuaternion = mesh.rotationQuaternion;
  190. mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  191. mesh.computeWorldMatrix(true);
  192. var returnValue;
  193. switch (impostor.type) {
  194. case PhysicsEngine.SphereImpostor:
  195. var bbox = mesh.getBoundingInfo().boundingBox;
  196. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  197. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  198. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  199. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  200. break;
  201. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  202. case PhysicsEngine.CylinderImpostor:
  203. Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  204. case PhysicsEngine.BoxImpostor:
  205. bbox = mesh.getBoundingInfo().boundingBox;
  206. var min = bbox.minimumWorld;
  207. var max = bbox.maximumWorld;
  208. var box = max.subtract(min).scale(0.5);
  209. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  210. break;
  211. case PhysicsEngine.PlaneImpostor:
  212. Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  213. returnValue = new CANNON.Plane();
  214. break;
  215. case PhysicsEngine.MeshImpostor:
  216. var rawVerts = mesh.getVerticesData(VertexBuffer.PositionKind);
  217. var rawFaces = mesh.getIndices();
  218. Tools.Warn("MeshImpostor only collides against spheres.");
  219. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  220. break;
  221. case PhysicsEngine.HeightmapImpostor:
  222. returnValue = this._createHeightmap(mesh);
  223. break;
  224. }
  225. mesh.rotationQuaternion = oldQuaternion;
  226. return returnValue;
  227. }
  228. private _createHeightmap(mesh: AbstractMesh, pointDepth?: number) {
  229. var pos = mesh.getVerticesData(VertexBuffer.PositionKind);
  230. var matrix = [];
  231. //For now pointDepth will not be used and will be automatically calculated.
  232. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  233. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  234. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  235. var elementSize = dim * 2 / arraySize;
  236. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  237. for (var i = 0; i < pos.length; i = i + 3) {
  238. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  239. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  240. var y = pos[i + 1] + minY;
  241. if (!matrix[x]) {
  242. matrix[x] = [];
  243. }
  244. if (!matrix[x][z]) {
  245. matrix[x][z] = y;
  246. }
  247. matrix[x][z] = Math.max(y, matrix[x][z]);
  248. }
  249. for (var x = 0; x <= arraySize; ++x) {
  250. if (!matrix[x]) {
  251. var loc = 1;
  252. while (!matrix[(x + loc) % arraySize]) {
  253. loc++;
  254. }
  255. matrix[x] = matrix[(x + loc) % arraySize].slice();
  256. //console.log("missing x", x);
  257. }
  258. for (var z = 0; z <= arraySize; ++z) {
  259. if (!matrix[x][z]) {
  260. var loc = 1;
  261. var newValue;
  262. while (newValue === undefined) {
  263. newValue = matrix[x][(z + loc++) % arraySize];
  264. }
  265. matrix[x][z] = newValue;
  266. }
  267. }
  268. }
  269. var shape = new CANNON.Heightfield(matrix, {
  270. elementSize: elementSize
  271. });
  272. //For future reference, needed for body transformation
  273. shape.minY = minY;
  274. return shape;
  275. }
  276. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  277. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  278. private _tmpPosition: Vector3 = Vector3.Zero();
  279. private _tmpQuaternion: Quaternion = new Quaternion();
  280. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  281. private _tmpDeltaRotation: Quaternion = new Quaternion();
  282. private _tmpUnityRotation: Quaternion = new Quaternion();
  283. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  284. var mesh = impostor.mesh;
  285. //make sure it is updated...
  286. impostor.mesh.computeWorldMatrix(true);
  287. // The delta between the mesh position and the mesh bounding box center
  288. var bbox = mesh.getBoundingInfo().boundingBox;
  289. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  290. var quaternion = mesh.rotationQuaternion;
  291. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  292. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  293. if (impostor.type === PhysicsEngine.PlaneImpostor || impostor.type === PhysicsEngine.HeightmapImpostor) {
  294. //-90 DEG in X, precalculated
  295. quaternion = quaternion.multiply(this._minus90X);
  296. //Invert! (Precalculated, 90 deg in X)
  297. //No need to clone. this will never change.
  298. impostor.setDeltaRotation(this._plus90X);
  299. }
  300. //If it is a heightfield, if should be centered.
  301. if (impostor.type === PhysicsEngine.HeightmapImpostor) {
  302. //calculate the correct body position:
  303. var rotationQuaternion = mesh.rotationQuaternion;
  304. mesh.rotationQuaternion = this._tmpUnityRotation;
  305. mesh.computeWorldMatrix(true);
  306. //get original center with no rotation
  307. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  308. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  309. //rotation is back
  310. mesh.rotationQuaternion = rotationQuaternion;
  311. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  312. var p = Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  313. mesh.setPivotMatrix(p);
  314. mesh.computeWorldMatrix(true);
  315. //calculate the translation
  316. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  317. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  318. //add it inverted to the delta
  319. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  320. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  321. mesh.setPivotMatrix(oldPivot);
  322. mesh.computeWorldMatrix(true);
  323. } else if (impostor.type === PhysicsEngine.MeshImpostor) {
  324. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  325. this._tmpPosition.copyFrom(mesh.position);
  326. }
  327. impostor.setDeltaPosition(this._tmpDeltaPosition);
  328. //Now update the impostor object
  329. impostor.physicsBody.position.copy(this._tmpPosition);
  330. impostor.physicsBody.quaternion.copy(quaternion);
  331. }
  332. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  333. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  334. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  335. }
  336. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  337. impostor.physicsBody.position.copy(newPosition);
  338. impostor.physicsBody.quaternion.copy(newRotation);
  339. }
  340. public isSupported(): boolean {
  341. return window.CANNON !== undefined;
  342. }
  343. public setVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  344. impostor.physicsBody.velocity.copy(velocity);
  345. }
  346. public dispose() {
  347. //nothing to do, actually.
  348. }
  349. }
  350. }