babylon.cannonJSPlugin.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. var BABYLON;
  2. (function (BABYLON) {
  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 OldCannonJSPlugin {
  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?: PhysicsImpostorParameters): 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: PhysicsImpostorParameters): 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 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 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. var CannonJSPlugin = (function () {
  392. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  393. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  394. if (iterations === void 0) { iterations = 10; }
  395. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  396. this.name = "CannonJSPlugin";
  397. this._physicsMaterials = [];
  398. this._fixedTimeStep = 1 / 60;
  399. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  400. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  401. this._tmpPosition = BABYLON.Vector3.Zero();
  402. this._tmpQuaternion = new BABYLON.Quaternion();
  403. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  404. this._tmpDeltaRotation = new BABYLON.Quaternion();
  405. this._tmpUnityRotation = new BABYLON.Quaternion();
  406. if (!this.isSupported()) {
  407. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  408. return;
  409. }
  410. this.world = new CANNON.World();
  411. this.world.broadphase = new CANNON.NaiveBroadphase();
  412. this.world.solver.iterations = iterations;
  413. }
  414. CannonJSPlugin.prototype.setGravity = function (gravity) {
  415. this.world.gravity.copy(gravity);
  416. };
  417. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  418. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0);
  419. };
  420. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  421. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  422. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  423. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  424. };
  425. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  426. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  427. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  428. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  429. };
  430. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  431. //parent-child relationship. Does this impostor has a parent impostor?
  432. if (impostor.parent) {
  433. if (impostor.physicsBody) {
  434. this.removePhysicsBody(impostor);
  435. //TODO is that needed?
  436. impostor.forceUpdate();
  437. }
  438. return;
  439. }
  440. //should a new body be created for this impostor?
  441. if (impostor.isBodyInitRequired()) {
  442. if (!impostor.mesh.rotationQuaternion) {
  443. impostor.mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(impostor.mesh.rotation.y, impostor.mesh.rotation.x, impostor.mesh.rotation.z);
  444. }
  445. var shape = this._createShape(impostor);
  446. //unregister events, if body is being changed
  447. var oldBody = impostor.physicsBody;
  448. if (oldBody) {
  449. this.removePhysicsBody(oldBody);
  450. }
  451. //create the body and material
  452. var material = this._addMaterial(impostor.getOptions().friction, impostor.getOptions().restitution);
  453. var bodyCreationObject = {
  454. mass: impostor.getOptions().mass,
  455. material: material
  456. };
  457. // A simple extend, in case native options were used.
  458. var nativeOptions = impostor.getOptions().nativeOptions;
  459. for (var key in nativeOptions) {
  460. if (nativeOptions.hasOwnProperty(key)) {
  461. bodyCreationObject[key] = nativeOptions[key];
  462. }
  463. }
  464. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  465. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  466. this.world.addEventListener("preStep", impostor.beforeStep);
  467. this.world.addEventListener("postStep", impostor.afterStep);
  468. impostor.physicsBody.addShape(shape);
  469. this.world.add(impostor.physicsBody);
  470. //try to keep the body moving in the right direction by taking old properties.
  471. //Should be tested!
  472. if (oldBody) {
  473. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  474. impostor.physicsBody[param].copy(oldBody[param]);
  475. });
  476. }
  477. this._processChildMeshes(impostor);
  478. }
  479. //now update the body's transformation
  480. this._updatePhysicsBodyTransformation(impostor);
  481. };
  482. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  483. var _this = this;
  484. var meshChildren = mainImpostor.mesh.getChildMeshes();
  485. if (meshChildren.length) {
  486. var processMesh = function (localPosition, mesh) {
  487. var childImpostor = mesh.getPhysicsImpostor();
  488. if (childImpostor) {
  489. var parent = childImpostor.parent;
  490. if (parent !== mainImpostor) {
  491. var localPosition = mesh.position;
  492. if (childImpostor.physicsBody) {
  493. _this.removePhysicsBody(childImpostor);
  494. childImpostor.physicsBody = null;
  495. }
  496. childImpostor.parent = mainImpostor;
  497. childImpostor.resetUpdateFlags();
  498. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  499. //Add the mass of the children.
  500. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  501. }
  502. }
  503. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  504. };
  505. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  506. }
  507. };
  508. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  509. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  510. this.world.removeEventListener("preStep", impostor.beforeStep);
  511. this.world.removeEventListener("postStep", impostor.afterStep);
  512. this.world.remove(impostor.physicsBody);
  513. };
  514. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  515. var mainBody = impostorJoint.mainImpostor.physicsBody;
  516. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  517. if (!mainBody || !connectedBody) {
  518. return;
  519. }
  520. var constraint;
  521. var jointData = impostorJoint.joint.jointData;
  522. var constraintData = {
  523. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  524. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  525. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  526. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  527. maxForce: jointData.nativeParams.maxForce
  528. };
  529. switch (impostorJoint.joint.type) {
  530. case BABYLON.PhysicsJoint.HingeJoint:
  531. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  532. break;
  533. default:
  534. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  535. break;
  536. }
  537. this.world.addConstraint(constraint);
  538. return true;
  539. };
  540. CannonJSPlugin.prototype.removeJoint = function (joint) {
  541. //TODO
  542. };
  543. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  544. var index;
  545. var mat;
  546. for (index = 0; index < this._physicsMaterials.length; index++) {
  547. mat = this._physicsMaterials[index];
  548. if (mat.friction === friction && mat.restitution === restitution) {
  549. return mat;
  550. }
  551. }
  552. var currentMat = new CANNON.Material("mat");
  553. this._physicsMaterials.push(currentMat);
  554. for (index = 0; index < this._physicsMaterials.length; index++) {
  555. mat = this._physicsMaterials[index];
  556. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, { friction: friction, restitution: restitution });
  557. this.world.addContactMaterial(contactMaterial);
  558. }
  559. return currentMat;
  560. };
  561. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  562. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  563. };
  564. CannonJSPlugin.prototype._createShape = function (impostor) {
  565. var mesh = impostor.mesh;
  566. //get the correct bounding box
  567. var oldQuaternion = mesh.rotationQuaternion;
  568. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  569. mesh.computeWorldMatrix(true);
  570. var returnValue;
  571. switch (impostor.type) {
  572. case BABYLON.PhysicsEngine.SphereImpostor:
  573. var bbox = mesh.getBoundingInfo().boundingBox;
  574. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  575. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  576. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  577. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  578. break;
  579. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  580. case BABYLON.PhysicsEngine.CylinderImpostor:
  581. BABYLON.Tools.Warn("CylinderImposter not yet implemented, using BoxImposter instead");
  582. case BABYLON.PhysicsEngine.BoxImpostor:
  583. bbox = mesh.getBoundingInfo().boundingBox;
  584. var min = bbox.minimumWorld;
  585. var max = bbox.maximumWorld;
  586. var box = max.subtract(min).scale(0.5);
  587. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  588. break;
  589. case BABYLON.PhysicsEngine.PlaneImpostor:
  590. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  591. returnValue = new CANNON.Plane();
  592. break;
  593. case BABYLON.PhysicsEngine.MeshImpostor:
  594. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  595. var rawFaces = mesh.getIndices();
  596. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  597. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  598. break;
  599. case BABYLON.PhysicsEngine.HeightmapImpostor:
  600. returnValue = this._createHeightmap(mesh);
  601. break;
  602. }
  603. mesh.rotationQuaternion = oldQuaternion;
  604. return returnValue;
  605. };
  606. CannonJSPlugin.prototype._createHeightmap = function (mesh, pointDepth) {
  607. var pos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  608. var matrix = [];
  609. //For now pointDepth will not be used and will be automatically calculated.
  610. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  611. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  612. var dim = Math.min(mesh.getBoundingInfo().boundingBox.extendSize.x, mesh.getBoundingInfo().boundingBox.extendSize.z);
  613. var elementSize = dim * 2 / arraySize;
  614. var minY = mesh.getBoundingInfo().boundingBox.extendSize.y;
  615. for (var i = 0; i < pos.length; i = i + 3) {
  616. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  617. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  618. var y = pos[i + 1] + minY;
  619. if (!matrix[x]) {
  620. matrix[x] = [];
  621. }
  622. if (!matrix[x][z]) {
  623. matrix[x][z] = y;
  624. }
  625. matrix[x][z] = Math.max(y, matrix[x][z]);
  626. }
  627. for (var x = 0; x <= arraySize; ++x) {
  628. if (!matrix[x]) {
  629. var loc = 1;
  630. while (!matrix[(x + loc) % arraySize]) {
  631. loc++;
  632. }
  633. matrix[x] = matrix[(x + loc) % arraySize].slice();
  634. }
  635. for (var z = 0; z <= arraySize; ++z) {
  636. if (!matrix[x][z]) {
  637. var loc = 1;
  638. var newValue;
  639. while (newValue === undefined) {
  640. newValue = matrix[x][(z + loc++) % arraySize];
  641. }
  642. matrix[x][z] = newValue;
  643. }
  644. }
  645. }
  646. var shape = new CANNON.Heightfield(matrix, {
  647. elementSize: elementSize
  648. });
  649. //For future reference, needed for body transformation
  650. shape.minY = minY;
  651. return shape;
  652. };
  653. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  654. var mesh = impostor.mesh;
  655. //make sure it is updated...
  656. impostor.mesh.computeWorldMatrix(true);
  657. // The delta between the mesh position and the mesh bounding box center
  658. var bbox = mesh.getBoundingInfo().boundingBox;
  659. this._tmpDeltaPosition.copyFrom(mesh.position.subtract(bbox.center));
  660. var quaternion = mesh.rotationQuaternion;
  661. this._tmpPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center);
  662. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  663. if (impostor.type === BABYLON.PhysicsEngine.PlaneImpostor || impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  664. //-90 DEG in X, precalculated
  665. quaternion = quaternion.multiply(this._minus90X);
  666. //Invert! (Precalculated, 90 deg in X)
  667. //No need to clone. this will never change.
  668. impostor.setDeltaRotation(this._plus90X);
  669. }
  670. //If it is a heightfield, if should be centered.
  671. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  672. //calculate the correct body position:
  673. var rotationQuaternion = mesh.rotationQuaternion;
  674. mesh.rotationQuaternion = this._tmpUnityRotation;
  675. mesh.computeWorldMatrix(true);
  676. //get original center with no rotation
  677. var center = mesh.getBoundingInfo().boundingBox.center.clone();
  678. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  679. //rotation is back
  680. mesh.rotationQuaternion = rotationQuaternion;
  681. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  682. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  683. mesh.setPivotMatrix(p);
  684. mesh.computeWorldMatrix(true);
  685. //calculate the translation
  686. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  687. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  688. //add it inverted to the delta
  689. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(center));
  690. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  691. mesh.setPivotMatrix(oldPivot);
  692. mesh.computeWorldMatrix(true);
  693. }
  694. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  695. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  696. this._tmpPosition.copyFrom(mesh.position);
  697. }
  698. impostor.setDeltaPosition(this._tmpDeltaPosition);
  699. //Now update the impostor object
  700. impostor.physicsBody.position.copy(this._tmpPosition);
  701. impostor.physicsBody.quaternion.copy(quaternion);
  702. };
  703. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  704. impostor.mesh.position.copyFrom(impostor.physicsBody.position);
  705. impostor.mesh.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  706. };
  707. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  708. impostor.physicsBody.position.copy(newPosition);
  709. impostor.physicsBody.quaternion.copy(newRotation);
  710. };
  711. CannonJSPlugin.prototype.isSupported = function () {
  712. return window.CANNON !== undefined;
  713. };
  714. CannonJSPlugin.prototype.dispose = function () {
  715. //nothing to do, actually.
  716. };
  717. return CannonJSPlugin;
  718. }());
  719. BABYLON.CannonJSPlugin = CannonJSPlugin;
  720. })(BABYLON || (BABYLON = {}));