babylon.cannonJSPlugin.ts 21 KB

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