babylon.cannonJSPlugin.ts 20 KB

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