babylon.physicsEngine.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. module BABYLON {
  2. declare var CANNON;
  3. declare var window;
  4. export class PhysicsEngine {
  5. private _world = new CANNON.World();
  6. private _registeredMeshes = [];
  7. private _physicsMaterials = [];
  8. constructor(public gravity: Vector3, iterations: number) {
  9. this._world.broadphase = new CANNON.NaiveBroadphase();
  10. this._world.solver.iterations = iterations;
  11. this._setGravity(gravity);
  12. }
  13. public _runOneStep(delta: number): void {
  14. if (delta > 0.1) {
  15. delta = 0.1;
  16. } else if (delta <= 0) {
  17. delta = 1.0 / 60.0;
  18. }
  19. this._world.step(delta);
  20. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21. var registeredMesh = this._registeredMeshes[index];
  22. if (registeredMesh.isChild) {
  23. continue;
  24. }
  25. registeredMesh.mesh.position.x = registeredMesh.body.position.x;
  26. registeredMesh.mesh.position.y = registeredMesh.body.position.z;
  27. registeredMesh.mesh.position.z = registeredMesh.body.position.y;
  28. if (!registeredMesh.mesh.rotationQuaternion) {
  29. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  30. }
  31. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  32. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  33. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  34. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  35. }
  36. }
  37. public _addMaterial(friction: number, restitution: number) {
  38. var index;
  39. var mat;
  40. for (index = 0; index < this._physicsMaterials.length; index++) {
  41. mat = this._physicsMaterials[index];
  42. if (mat.friction === friction && mat.restitution === restitution) {
  43. return mat;
  44. }
  45. }
  46. var currentMat = new CANNON.Material();
  47. currentMat.friction = friction;
  48. currentMat.restitution = restitution;
  49. this._physicsMaterials.push(currentMat);
  50. for (index = 0; index < this._physicsMaterials.length; index++) {
  51. mat = this._physicsMaterials[index];
  52. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  53. contactMaterial.contactEquationStiffness = 1e10;
  54. contactMaterial.contactEquationRegularizationTime = 10;
  55. this._world.addContactMaterial(contactMaterial);
  56. }
  57. return currentMat;
  58. }
  59. public _setGravity(gravity: Vector3): void {
  60. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  61. this._world.gravity.set(this.gravity.x, this.gravity.z, this.gravity.y);
  62. }
  63. public _checkWithEpsilon(value: number): number {
  64. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  65. }
  66. public _registerMesh(mesh: Mesh, options, onlyShape?: boolean): void {
  67. var shape = null;
  68. var initialRotation;
  69. if (mesh.rotationQuaternion) {
  70. initialRotation = mesh.rotationQuaternion.clone();
  71. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  72. }
  73. this._unregisterMesh(mesh);
  74. mesh.computeWorldMatrix(true);
  75. switch (options.impostor) {
  76. case BABYLON.PhysicsEngine.SphereImpostor:
  77. var bbox = mesh.getBoundingInfo().boundingBox;
  78. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  79. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  80. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  81. shape = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82. break;
  83. case BABYLON.PhysicsEngine.BoxImpostor:
  84. bbox = mesh.getBoundingInfo().boundingBox;
  85. var min = bbox.minimumWorld;
  86. var max = bbox.maximumWorld;
  87. var box = max.subtract(min).scale(0.5);
  88. shape = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.z), this._checkWithEpsilon(box.y)));
  89. break;
  90. case BABYLON.PhysicsEngine.PlaneImpostor:
  91. shape = new CANNON.Plane();
  92. break;
  93. case BABYLON.PhysicsEngine.MeshImpostor:
  94. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95. var rawFaces = mesh.getIndices();
  96. var verts = [], faces = [];
  97. mesh.computeWorldMatrix(true);
  98. // Get vertices
  99. for (var i = 0; i < rawVerts.length; i += 3) {
  100. var transformed = BABYLON.Vector3.Zero();
  101. BABYLON.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. // Construct polyhedron
  109. shape = new CANNON.ConvexPolyhedron(verts, faces);
  110. break;
  111. }
  112. if (onlyShape) {
  113. return shape;
  114. }
  115. var material = this._addMaterial(options.friction, options.restitution);
  116. var body = new CANNON.RigidBody(options.mass, shape, material);
  117. if (initialRotation) {
  118. body.quaternion.x = initialRotation.x;
  119. body.quaternion.z = initialRotation.y;
  120. body.quaternion.y = initialRotation.z;
  121. body.quaternion.w = -initialRotation.w;
  122. }
  123. body.position.set(mesh.position.x, mesh.position.z, mesh.position.y);
  124. this._world.add(body);
  125. this._registeredMeshes.push({ mesh: mesh, body: body, material: material });
  126. return body;
  127. }
  128. public _registerCompound(options): any {
  129. var compoundShape = new CANNON.Compound();
  130. var initialMesh = options.parts[0].mesh;
  131. var initialPosition = initialMesh.position;
  132. for (var index = 0; index < options.parts.length; index++) {
  133. var mesh = options.parts[index].mesh;
  134. var shape = this._registerMesh(mesh, options.parts[index], true);
  135. if (index == 0) { // Parent
  136. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  137. } else {
  138. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  139. }
  140. }
  141. var material = this._addMaterial(options.friction, options.restitution);
  142. var body = new CANNON.RigidBody(options.mass, compoundShape, material);
  143. body.position.set(initialPosition.x, initialPosition.z, initialPosition.y);
  144. this._world.add(body);
  145. for (index = 0; index < options.parts.length; index++) {
  146. mesh = options.parts[index].mesh;
  147. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, isChild: index != 0 });
  148. }
  149. body.parts = options.parts;
  150. return body;
  151. }
  152. public _unbindBody(body): void {
  153. for (var index = 0; index < this._registeredMeshes.length; index++) {
  154. var registeredMesh = this._registeredMeshes[index];
  155. if (registeredMesh.body === body) {
  156. registeredMesh.body = null;
  157. }
  158. }
  159. }
  160. public _unregisterMesh(mesh: Mesh): void {
  161. for (var index = 0; index < this._registeredMeshes.length; index++) {
  162. var registeredMesh = this._registeredMeshes[index];
  163. if (registeredMesh.mesh === mesh) {
  164. // Remove body
  165. if (registeredMesh.body) {
  166. this._world.remove(registeredMesh.body);
  167. this._unbindBody(registeredMesh.body);
  168. }
  169. this._registeredMeshes.splice(index, 1);
  170. return;
  171. }
  172. }
  173. }
  174. public _applyImpulse(mesh: Mesh, force: Vector3, contactPoint: Vector3): void {
  175. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  176. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  177. for (var index = 0; index < this._registeredMeshes.length; index++) {
  178. var registeredMesh = this._registeredMeshes[index];
  179. if (registeredMesh.mesh === mesh) {
  180. registeredMesh.body.applyImpulse(impulse, worldPoint);
  181. return;
  182. }
  183. }
  184. }
  185. public _createLink(mesh1: Mesh, mesh2: Mesh, pivot1: Vector3, pivot2: Vector3): void {
  186. var body1, body2;
  187. for (var index = 0; index < this._registeredMeshes.length; index++) {
  188. var registeredMesh = this._registeredMeshes[index];
  189. if (registeredMesh.mesh === mesh1) {
  190. body1 = registeredMesh.body;
  191. } else if (registeredMesh.mesh === mesh2) {
  192. body2 = registeredMesh.body;
  193. }
  194. }
  195. if (!body1 || !body2) {
  196. return;
  197. }
  198. 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));
  199. this._world.addConstraint(constraint);
  200. }
  201. public dispose(): void {
  202. while (this._registeredMeshes.length) {
  203. this._unregisterMesh(this._registeredMeshes[0].mesh);
  204. }
  205. }
  206. // Statics
  207. public static IsSupported(): boolean {
  208. return window.CANNON !== undefined;
  209. }
  210. public static NoImpostor = 0;
  211. public static SphereImpostor = 1;
  212. public static BoxImpostor = 2;
  213. public static PlaneImpostor = 3;
  214. public static CompoundImpostor = 4;
  215. public static MeshImpostor = 4;
  216. public static Epsilon = 0.001;
  217. }
  218. }