babylon.cannonJSPlugin.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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("mat-" + impostor.mesh.uniqueId, 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. case PhysicsJoint.SpringJoint:
  156. var springData = <SpringJointData>jointData;
  157. constraint = new CANNON.Spring(mainBody, connectedBody, {
  158. restLength: springData.length,
  159. stiffness: springData.stiffness,
  160. damping: springData.damping,
  161. localAnchorA: constraintData.pivotA,
  162. localAnchorB: constraintData.pivotB
  163. });
  164. break;
  165. default:
  166. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  167. break;
  168. }
  169. impostorJoint.joint.physicsJoint = constraint;
  170. this.world.addConstraint(constraint);
  171. }
  172. public removeJoint(joint: PhysicsImpostorJoint) {
  173. //TODO
  174. }
  175. private _addMaterial(name: string, friction: number, restitution: number) {
  176. var index;
  177. var mat;
  178. for (index = 0; index < this._physicsMaterials.length; index++) {
  179. mat = this._physicsMaterials[index];
  180. if (mat.friction === friction && mat.restitution === restitution) {
  181. return mat;
  182. }
  183. }
  184. var currentMat = new CANNON.Material("mat");
  185. currentMat.friction = friction;
  186. currentMat.restitution = restitution;
  187. this._physicsMaterials.push(currentMat);
  188. return currentMat;
  189. }
  190. private _checkWithEpsilon(value: number): number {
  191. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  192. }
  193. private _createShape(impostor: PhysicsImpostor) {
  194. var mesh = impostor.mesh;
  195. //get the correct bounding box
  196. var oldQuaternion = mesh.rotationQuaternion;
  197. mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  198. mesh.computeWorldMatrix(true);
  199. var returnValue;
  200. switch (impostor.type) {
  201. case PhysicsEngine.SphereImpostor:
  202. var bbox = mesh.getBoundingInfo().boundingBox;
  203. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  204. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  205. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  206. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  207. break;
  208. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  209. case PhysicsEngine.CylinderImpostor:
  210. Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  211. case PhysicsEngine.BoxImpostor:
  212. bbox = mesh.getBoundingInfo().boundingBox;
  213. var min = bbox.minimumWorld;
  214. var max = bbox.maximumWorld;
  215. var box = max.subtract(min).scale(0.5);
  216. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  217. break;
  218. case PhysicsEngine.PlaneImpostor:
  219. Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  220. returnValue = new CANNON.Plane();
  221. break;
  222. case PhysicsEngine.MeshImpostor:
  223. var rawVerts = mesh.getVerticesData(VertexBuffer.PositionKind);
  224. var rawFaces = mesh.getIndices();
  225. Tools.Warn("MeshImpostor only collides against spheres.");
  226. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  227. break;
  228. case PhysicsEngine.HeightmapImpostor:
  229. returnValue = this._createHeightmap(mesh);
  230. break;
  231. }
  232. mesh.rotationQuaternion = oldQuaternion;
  233. return returnValue;
  234. }
  235. private _createHeightmap(mesh: AbstractMesh, pointDepth?: number) {
  236. var pos = mesh.getVerticesData(VertexBuffer.PositionKind);
  237. var matrix = [];
  238. //For now pointDepth will not be used and will be automatically calculated.
  239. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  240. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  241. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  242. var elementSize = dim * 2 / arraySize;
  243. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  244. for (var i = 0; i < pos.length; i = i + 3) {
  245. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  246. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  247. var y = pos[i + 1] + minY;
  248. if (!matrix[x]) {
  249. matrix[x] = [];
  250. }
  251. if (!matrix[x][z]) {
  252. matrix[x][z] = y;
  253. }
  254. matrix[x][z] = Math.max(y, matrix[x][z]);
  255. }
  256. for (var x = 0; x <= arraySize; ++x) {
  257. if (!matrix[x]) {
  258. var loc = 1;
  259. while (!matrix[(x + loc) % arraySize]) {
  260. loc++;
  261. }
  262. matrix[x] = matrix[(x + loc) % arraySize].slice();
  263. //console.log("missing x", x);
  264. }
  265. for (var z = 0; z <= arraySize; ++z) {
  266. if (!matrix[x][z]) {
  267. var loc = 1;
  268. var newValue;
  269. while (newValue === undefined) {
  270. newValue = matrix[x][(z + loc++) % arraySize];
  271. }
  272. matrix[x][z] = newValue;
  273. }
  274. }
  275. }
  276. var shape = new CANNON.Heightfield(matrix, {
  277. elementSize: elementSize
  278. });
  279. //For future reference, needed for body transformation
  280. shape.minY = minY;
  281. return shape;
  282. }
  283. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  284. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  285. private _tmpPosition: Vector3 = Vector3.Zero();
  286. private _tmpQuaternion: Quaternion = new Quaternion();
  287. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  288. private _tmpDeltaRotation: Quaternion = new Quaternion();
  289. private _tmpUnityRotation: Quaternion = new Quaternion();
  290. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  291. var mesh = impostor.mesh;
  292. //make sure it is updated...
  293. impostor.mesh.computeWorldMatrix(true);
  294. // The delta between the mesh position and the mesh bounding box center
  295. var bbox = mesh.getBoundingInfo().boundingBox;
  296. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  297. var quaternion = mesh.rotationQuaternion;
  298. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  299. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  300. if (impostor.type === PhysicsEngine.PlaneImpostor || impostor.type === PhysicsEngine.HeightmapImpostor) {
  301. //-90 DEG in X, precalculated
  302. quaternion = quaternion.multiply(this._minus90X);
  303. //Invert! (Precalculated, 90 deg in X)
  304. //No need to clone. this will never change.
  305. impostor.setDeltaRotation(this._plus90X);
  306. }
  307. //If it is a heightfield, if should be centered.
  308. if (impostor.type === PhysicsEngine.HeightmapImpostor) {
  309. //calculate the correct body position:
  310. var rotationQuaternion = mesh.rotationQuaternion;
  311. mesh.rotationQuaternion = this._tmpUnityRotation;
  312. mesh.computeWorldMatrix(true);
  313. //get original center with no rotation
  314. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  315. var oldPivot = mesh.getPivotMatrix() || Matrix.Translation(0, 0, 0);
  316. //rotation is back
  317. mesh.rotationQuaternion = rotationQuaternion;
  318. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  319. var p = Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  320. mesh.setPivotMatrix(p);
  321. mesh.computeWorldMatrix(true);
  322. //calculate the translation
  323. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  324. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  325. //add it inverted to the delta
  326. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  327. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  328. mesh.setPivotMatrix(oldPivot);
  329. mesh.computeWorldMatrix(true);
  330. } else if (impostor.type === PhysicsEngine.MeshImpostor) {
  331. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  332. this._tmpPosition.copyFrom(mesh.position);
  333. }
  334. impostor.setDeltaPosition(this._tmpDeltaPosition);
  335. //Now update the impostor object
  336. impostor.physicsBody.position.copy(this._tmpPosition);
  337. impostor.physicsBody.quaternion.copy(quaternion);
  338. }
  339. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  340. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  341. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  342. }
  343. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  344. impostor.physicsBody.position.copy(newPosition);
  345. impostor.physicsBody.quaternion.copy(newRotation);
  346. }
  347. public isSupported(): boolean {
  348. return window.CANNON !== undefined;
  349. }
  350. public setVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  351. impostor.physicsBody.velocity.copy(velocity);
  352. }
  353. public sleepBody(impostor: PhysicsImpostor) {
  354. impostor.physicsBody.sleep();
  355. }
  356. public wakeUpBody(impostor: PhysicsImpostor) {
  357. impostor.physicsBody.wakeUp();
  358. }
  359. public dispose() {
  360. //nothing to do, actually.
  361. }
  362. }
  363. }