babylon.cannonJSPlugin.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. module BABYLON {
  2. declare var CANNON;
  3. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  4. public checkWithEpsilon: (value: number) => number;
  5. private _world: any;
  6. private _registeredMeshes = [];
  7. private _physicsMaterials = [];
  8. public initialize(iterations: number = 10): void {
  9. this._world = new CANNON.World();
  10. this._world.broadphase = new CANNON.NaiveBroadphase();
  11. this._world.solver.iterations = iterations;
  12. }
  13. private _checkWithEpsilon(value: number): number {
  14. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  15. }
  16. public runOneStep(delta: number): void {
  17. this._world.step(delta);
  18. for (var index = 0; index < this._registeredMeshes.length; index++) {
  19. var registeredMesh = this._registeredMeshes[index];
  20. if (registeredMesh.isChild) {
  21. continue;
  22. }
  23. // Body position
  24. var bodyX = registeredMesh.body.position.x,
  25. bodyY = registeredMesh.body.position.y,
  26. bodyZ = registeredMesh.body.position.z;
  27. var deltaPos = registeredMesh.delta;
  28. if (deltaPos) {
  29. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  30. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  31. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  32. } else {
  33. registeredMesh.mesh.position.x = bodyX;
  34. registeredMesh.mesh.position.y = bodyZ;
  35. registeredMesh.mesh.position.z = bodyY;
  36. }
  37. if (!registeredMesh.mesh.rotationQuaternion) {
  38. registeredMesh.mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  39. }
  40. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  41. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  42. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  43. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  44. }
  45. }
  46. public setGravity(gravity: Vector3): void {
  47. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  48. }
  49. public registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any {
  50. this.unregisterMesh(mesh);
  51. mesh.computeWorldMatrix(true);
  52. switch (impostor) {
  53. case PhysicsEngine.SphereImpostor:
  54. var bbox = mesh.getBoundingInfo().boundingBox;
  55. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  56. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  57. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  58. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  59. case PhysicsEngine.BoxImpostor:
  60. bbox = mesh.getBoundingInfo().boundingBox;
  61. var min = bbox.minimumWorld;
  62. var max = bbox.maximumWorld;
  63. var box = max.subtract(min).scale(0.5);
  64. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  65. case PhysicsEngine.PlaneImpostor:
  66. return this._createPlane(mesh, options);
  67. case PhysicsEngine.MeshImpostor:
  68. var rawVerts = mesh.getVerticesData(VertexBuffer.PositionKind);
  69. var rawFaces = mesh.getIndices();
  70. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  71. }
  72. return null;
  73. }
  74. private _createSphere(radius: number, mesh: AbstractMesh, options?: PhysicsBodyCreationOptions): any {
  75. var shape = new CANNON.Sphere(radius);
  76. if (!options) {
  77. return shape;
  78. }
  79. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  80. }
  81. private _createBox(x: number, y: number, z: number, mesh: AbstractMesh, options?: PhysicsBodyCreationOptions): any {
  82. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  83. if (!options) {
  84. return shape;
  85. }
  86. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  87. }
  88. private _createPlane(mesh: AbstractMesh, options?: PhysicsBodyCreationOptions): any {
  89. var shape = new CANNON.Plane();
  90. if (!options) {
  91. return shape;
  92. }
  93. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  94. }
  95. private _createConvexPolyhedron(rawVerts: number[], rawFaces: number[], mesh: AbstractMesh, options?: PhysicsBodyCreationOptions): any {
  96. var verts = [], faces = [];
  97. mesh.computeWorldMatrix(true);
  98. // Get vertices
  99. for (var i = 0; i < rawVerts.length; i += 3) {
  100. var transformed = Vector3.Zero();
  101. Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  102. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  103. }
  104. // Get faces
  105. for (var j = 0; j < rawFaces.length; j += 3) {
  106. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  107. }
  108. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  109. if (!options) {
  110. return shape;
  111. }
  112. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  113. }
  114. private _addMaterial(friction: number, restitution: number) {
  115. var index;
  116. var mat;
  117. for (index = 0; index < this._physicsMaterials.length; index++) {
  118. mat = this._physicsMaterials[index];
  119. if (mat.friction === friction && mat.restitution === restitution) {
  120. return mat;
  121. }
  122. }
  123. var currentMat = new CANNON.Material();
  124. currentMat.friction = friction;
  125. currentMat.restitution = restitution;
  126. this._physicsMaterials.push(currentMat);
  127. for (index = 0; index < this._physicsMaterials.length; index++) {
  128. mat = this._physicsMaterials[index];
  129. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  130. contactMaterial.contactEquationStiffness = 1e10;
  131. contactMaterial.contactEquationRegularizationTime = 10;
  132. this._world.addContactMaterial(contactMaterial);
  133. }
  134. return currentMat;
  135. }
  136. private _createRigidBodyFromShape(shape: any, mesh: AbstractMesh, mass: number, friction: number, restitution: number): any {
  137. var initialRotation: Quaternion = null;
  138. if (mesh.rotationQuaternion) {
  139. initialRotation = mesh.rotationQuaternion.clone();
  140. mesh.rotationQuaternion = new Quaternion(0, 0, 0, 1);
  141. }
  142. // The delta between the mesh position and the mesh bounding box center
  143. var bbox = mesh.getBoundingInfo().boundingBox;
  144. var deltaPosition = mesh.position.subtract(bbox.center);
  145. var material = this._addMaterial(friction, restitution);
  146. var body = new CANNON.RigidBody(mass, shape, material);
  147. if (initialRotation) {
  148. body.quaternion.x = initialRotation.x;
  149. body.quaternion.z = initialRotation.y;
  150. body.quaternion.y = initialRotation.z;
  151. body.quaternion.w = -initialRotation.w;
  152. }
  153. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  154. this._world.add(body);
  155. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  156. return body;
  157. }
  158. public registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any {
  159. var compoundShape = new CANNON.Compound();
  160. for (var index = 0; index < parts.length; index++) {
  161. var mesh = parts[index].mesh;
  162. var shape = this.registerMesh(mesh, parts[index].impostor);
  163. if (index == 0) { // Parent
  164. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  165. } else {
  166. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  167. }
  168. }
  169. var initialMesh = parts[0].mesh;
  170. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  171. body.parts = parts;
  172. return body;
  173. }
  174. private _unbindBody(body): void {
  175. for (var index = 0; index < this._registeredMeshes.length; index++) {
  176. var registeredMesh = this._registeredMeshes[index];
  177. if (registeredMesh.body === body) {
  178. registeredMesh.body = null;
  179. registeredMesh.delta = 0;
  180. }
  181. }
  182. }
  183. public unregisterMesh(mesh: AbstractMesh): void {
  184. for (var index = 0; index < this._registeredMeshes.length; index++) {
  185. var registeredMesh = this._registeredMeshes[index];
  186. if (registeredMesh.mesh === mesh) {
  187. // Remove body
  188. if (registeredMesh.body) {
  189. this._world.remove(registeredMesh.body);
  190. this._unbindBody(registeredMesh.body);
  191. }
  192. this._registeredMeshes.splice(index, 1);
  193. return;
  194. }
  195. }
  196. }
  197. public applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void {
  198. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  199. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  200. for (var index = 0; index < this._registeredMeshes.length; index++) {
  201. var registeredMesh = this._registeredMeshes[index];
  202. if (registeredMesh.mesh === mesh) {
  203. registeredMesh.body.applyImpulse(impulse, worldPoint);
  204. return;
  205. }
  206. }
  207. }
  208. public updateBodyPosition = function (mesh: AbstractMesh): void {
  209. for (var index = 0; index < this._registeredMeshes.length; index++) {
  210. var registeredMesh = this._registeredMeshes[index];
  211. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  212. var body = registeredMesh.body;
  213. var center = mesh.getBoundingInfo().boundingBox.center;
  214. body.position.set(center.x, center.z, center.y);
  215. body.quaternion.x = mesh.rotationQuaternion.x;
  216. body.quaternion.z = mesh.rotationQuaternion.y;
  217. body.quaternion.y = mesh.rotationQuaternion.z;
  218. body.quaternion.w = -mesh.rotationQuaternion.w;
  219. return;
  220. }
  221. }
  222. }
  223. public createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean {
  224. var body1 = null, body2 = null;
  225. for (var index = 0; index < this._registeredMeshes.length; index++) {
  226. var registeredMesh = this._registeredMeshes[index];
  227. if (registeredMesh.mesh === mesh1) {
  228. body1 = registeredMesh.body;
  229. } else if (registeredMesh.mesh === mesh2) {
  230. body2 = registeredMesh.body;
  231. }
  232. }
  233. if (!body1 || !body2) {
  234. return false;
  235. }
  236. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  237. this._world.addConstraint(constraint);
  238. return true;
  239. }
  240. public dispose(): void {
  241. while (this._registeredMeshes.length) {
  242. this.unregisterMesh(this._registeredMeshes[0].mesh);
  243. }
  244. }
  245. public isSupported(): boolean {
  246. return window.CANNON !== undefined;
  247. }
  248. }
  249. }