babylon.cannonJSPlugin.ts 22 KB

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