babylon.cannonJSPlugin.ts 21 KB

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