cannonJSPlugin.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. import { Nullable, FloatArray } from "../../types";
  2. import { Logger } from "../../Misc/logger";
  3. import { Vector3, Matrix, Quaternion } from "../../Maths/math.vector";
  4. import { VertexBuffer } from "../../Meshes/buffer";
  5. import { AbstractMesh } from "../../Meshes/abstractMesh";
  6. import { IPhysicsEnginePlugin, PhysicsImpostorJoint } from "../../Physics/IPhysicsEngine";
  7. import { PhysicsImpostor, IPhysicsEnabledObject } from "../../Physics/physicsImpostor";
  8. import { PhysicsJoint, IMotorEnabledJoint, DistanceJointData, SpringJointData } from "../../Physics/physicsJoint";
  9. import { PhysicsEngine } from "../../Physics/physicsEngine";
  10. import { PhysicsRaycastResult } from "../physicsRaycastResult";
  11. //declare var require: any;
  12. declare var CANNON: any;
  13. /** @hidden */
  14. export class CannonJSPlugin implements IPhysicsEnginePlugin {
  15. public world: any;
  16. public name: string = "CannonJSPlugin";
  17. private _physicsMaterials = new Array();
  18. private _fixedTimeStep: number = 1 / 60;
  19. private _cannonRaycastResult: any;
  20. private _raycastResult: PhysicsRaycastResult;
  21. private _physicsBodysToRemoveAfterStep = new Array<any>();
  22. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  23. public BJSCANNON: any;
  24. public constructor(private _useDeltaForWorldStep: boolean = true, iterations: number = 10, cannonInjection = CANNON) {
  25. this.BJSCANNON = cannonInjection;
  26. if (!this.isSupported()) {
  27. Logger.Error("CannonJS is not available. Please make sure you included the js file.");
  28. return;
  29. }
  30. this._extendNamespace();
  31. this.world = new this.BJSCANNON.World();
  32. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  33. this.world.solver.iterations = iterations;
  34. this._cannonRaycastResult = new this.BJSCANNON.RaycastResult();
  35. this._raycastResult = new PhysicsRaycastResult();
  36. }
  37. public setGravity(gravity: Vector3): void {
  38. this.world.gravity.copy(gravity);
  39. }
  40. public setTimeStep(timeStep: number) {
  41. this._fixedTimeStep = timeStep;
  42. }
  43. public getTimeStep(): number {
  44. return this._fixedTimeStep;
  45. }
  46. public executeStep(delta: number): void {
  47. this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep);
  48. this._removeMarkedPhysicsBodiesFromWorld();
  49. }
  50. private _removeMarkedPhysicsBodiesFromWorld(): void {
  51. if (this._physicsBodysToRemoveAfterStep.length > 0) {
  52. this._physicsBodysToRemoveAfterStep.forEach((physicsBody) => {
  53. this.world.remove(physicsBody);
  54. });
  55. this._physicsBodysToRemoveAfterStep = [];
  56. }
  57. }
  58. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  59. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  61. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  62. }
  63. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  64. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  65. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66. impostor.physicsBody.applyForce(impulse, worldPoint);
  67. }
  68. public generatePhysicsBody(impostor: PhysicsImpostor) {
  69. // When calling forceUpdate generatePhysicsBody is called again, ensure that the updated body does not instantly collide with removed body
  70. this._removeMarkedPhysicsBodiesFromWorld();
  71. //parent-child relationship. Does this impostor has a parent impostor?
  72. if (impostor.parent) {
  73. if (impostor.physicsBody) {
  74. this.removePhysicsBody(impostor);
  75. //TODO is that needed?
  76. impostor.forceUpdate();
  77. }
  78. return;
  79. }
  80. //should a new body be created for this impostor?
  81. if (impostor.isBodyInitRequired()) {
  82. var shape = this._createShape(impostor);
  83. //unregister events, if body is being changed
  84. var oldBody = impostor.physicsBody;
  85. if (oldBody) {
  86. this.removePhysicsBody(impostor);
  87. }
  88. //create the body and material
  89. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  90. var bodyCreationObject = {
  91. mass: impostor.getParam("mass"),
  92. material: material
  93. };
  94. // A simple extend, in case native options were used.
  95. var nativeOptions = impostor.getParam("nativeOptions");
  96. for (var key in nativeOptions) {
  97. if (nativeOptions.hasOwnProperty(key)) {
  98. (<any>bodyCreationObject)[key] = nativeOptions[key];
  99. }
  100. }
  101. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  102. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  103. this.world.addEventListener("preStep", impostor.beforeStep);
  104. this.world.addEventListener("postStep", impostor.afterStep);
  105. impostor.physicsBody.addShape(shape);
  106. this.world.add(impostor.physicsBody);
  107. //try to keep the body moving in the right direction by taking old properties.
  108. //Should be tested!
  109. if (oldBody) {
  110. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function(param) {
  111. impostor.physicsBody[param].copy(oldBody[param]);
  112. });
  113. }
  114. this._processChildMeshes(impostor);
  115. }
  116. //now update the body's transformation
  117. this._updatePhysicsBodyTransformation(impostor);
  118. }
  119. private _processChildMeshes(mainImpostor: PhysicsImpostor) {
  120. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  121. let currentRotation: Nullable<Quaternion> = mainImpostor.object.rotationQuaternion;
  122. if (meshChildren.length) {
  123. var processMesh = (localPosition: Vector3, mesh: AbstractMesh) => {
  124. if (!currentRotation || !mesh.rotationQuaternion) {
  125. return;
  126. }
  127. var childImpostor = mesh.getPhysicsImpostor();
  128. if (childImpostor) {
  129. var parent = childImpostor.parent;
  130. if (parent !== mainImpostor) {
  131. var pPosition = mesh.position.clone();
  132. let localRotation = mesh.rotationQuaternion.multiply(Quaternion.Inverse(currentRotation));
  133. if (childImpostor.physicsBody) {
  134. this.removePhysicsBody(childImpostor);
  135. childImpostor.physicsBody = null;
  136. }
  137. childImpostor.parent = mainImpostor;
  138. childImpostor.resetUpdateFlags();
  139. mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  140. //Add the mass of the children.
  141. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  142. }
  143. }
  144. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  145. mesh.getChildMeshes(true).filter((m) => !!m.physicsImpostor).forEach(processMesh.bind(this, mesh.getAbsolutePosition()));
  146. };
  147. meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  148. }
  149. }
  150. public removePhysicsBody(impostor: PhysicsImpostor) {
  151. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  152. this.world.removeEventListener("preStep", impostor.beforeStep);
  153. this.world.removeEventListener("postStep", impostor.afterStep);
  154. // Only remove the physics body after the physics step to avoid disrupting cannon's internal state
  155. if (this._physicsBodysToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) {
  156. this._physicsBodysToRemoveAfterStep.push(impostor.physicsBody);
  157. }
  158. }
  159. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  160. var mainBody = impostorJoint.mainImpostor.physicsBody;
  161. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  162. if (!mainBody || !connectedBody) {
  163. return;
  164. }
  165. var constraint: any;
  166. var jointData = impostorJoint.joint.jointData;
  167. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  168. var constraintData = {
  169. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  170. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  171. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  172. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  173. maxForce: jointData.nativeParams.maxForce,
  174. collideConnected: !!jointData.collision
  175. };
  176. switch (impostorJoint.joint.type) {
  177. case PhysicsJoint.HingeJoint:
  178. case PhysicsJoint.Hinge2Joint:
  179. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  180. break;
  181. case PhysicsJoint.DistanceJoint:
  182. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, (<DistanceJointData>jointData).maxDistance || 2);
  183. break;
  184. case PhysicsJoint.SpringJoint:
  185. var springData = <SpringJointData>jointData;
  186. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  187. restLength: springData.length,
  188. stiffness: springData.stiffness,
  189. damping: springData.damping,
  190. localAnchorA: constraintData.pivotA,
  191. localAnchorB: constraintData.pivotB
  192. });
  193. break;
  194. case PhysicsJoint.LockJoint:
  195. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  196. break;
  197. case PhysicsJoint.PointToPointJoint:
  198. case PhysicsJoint.BallAndSocketJoint:
  199. default:
  200. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce);
  201. break;
  202. }
  203. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  204. constraint.collideConnected = !!jointData.collision;
  205. impostorJoint.joint.physicsJoint = constraint;
  206. //don't add spring as constraint, as it is not one.
  207. if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
  208. this.world.addConstraint(constraint);
  209. } else {
  210. (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback = (<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback || function() {
  211. constraint.applyForce();
  212. };
  213. impostorJoint.mainImpostor.registerAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
  214. }
  215. }
  216. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  217. if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {
  218. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  219. } else {
  220. impostorJoint.mainImpostor.unregisterAfterPhysicsStep((<SpringJointData>impostorJoint.joint.jointData).forceApplicationCallback);
  221. }
  222. }
  223. private _addMaterial(name: string, friction: number, restitution: number) {
  224. var index;
  225. var mat;
  226. for (index = 0; index < this._physicsMaterials.length; index++) {
  227. mat = this._physicsMaterials[index];
  228. if (mat.friction === friction && mat.restitution === restitution) {
  229. return mat;
  230. }
  231. }
  232. var currentMat = new this.BJSCANNON.Material(name);
  233. currentMat.friction = friction;
  234. currentMat.restitution = restitution;
  235. this._physicsMaterials.push(currentMat);
  236. return currentMat;
  237. }
  238. private _checkWithEpsilon(value: number): number {
  239. return value < PhysicsEngine.Epsilon ? PhysicsEngine.Epsilon : value;
  240. }
  241. private _createShape(impostor: PhysicsImpostor) {
  242. var object = impostor.object;
  243. var returnValue;
  244. var extendSize = impostor.getObjectExtendSize();
  245. switch (impostor.type) {
  246. case PhysicsImpostor.SphereImpostor:
  247. var radiusX = extendSize.x;
  248. var radiusY = extendSize.y;
  249. var radiusZ = extendSize.z;
  250. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  251. break;
  252. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  253. case PhysicsImpostor.CylinderImpostor:
  254. let nativeParams = impostor.getParam("nativeOptions");
  255. if (!nativeParams) {
  256. nativeParams = {};
  257. }
  258. let radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(extendSize.x) / 2;
  259. let radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(extendSize.x) / 2;
  260. let height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(extendSize.y);
  261. let numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16;
  262. returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments);
  263. // Rotate 90 degrees as this shape is horizontal in cannon
  264. var quat = new this.BJSCANNON.Quaternion();
  265. quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2);
  266. var translation = new this.BJSCANNON.Vec3(0, 0, 0);
  267. returnValue.transformAllPoints(translation, quat);
  268. break;
  269. case PhysicsImpostor.BoxImpostor:
  270. var box = extendSize.scale(0.5);
  271. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  272. break;
  273. case PhysicsImpostor.PlaneImpostor:
  274. Logger.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  275. returnValue = new this.BJSCANNON.Plane();
  276. break;
  277. case PhysicsImpostor.MeshImpostor:
  278. // should transform the vertex data to world coordinates!!
  279. var rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];
  280. var rawFaces = object.getIndices ? object.getIndices() : [];
  281. if (!rawVerts) { return; }
  282. // get only scale! so the object could transform correctly.
  283. let oldPosition = object.position.clone();
  284. let oldRotation = object.rotation && object.rotation.clone();
  285. let oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  286. object.position.copyFromFloats(0, 0, 0);
  287. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  288. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  289. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  290. let transform = object.computeWorldMatrix(true);
  291. // convert rawVerts to object space
  292. var temp = new Array<number>();
  293. var index: number;
  294. for (index = 0; index < rawVerts.length; index += 3) {
  295. Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  296. }
  297. Logger.Warn("MeshImpostor only collides against spheres.");
  298. returnValue = new this.BJSCANNON.Trimesh(temp, <number[]>rawFaces);
  299. //now set back the transformation!
  300. object.position.copyFrom(oldPosition);
  301. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  302. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  303. break;
  304. case PhysicsImpostor.HeightmapImpostor:
  305. let oldPosition2 = object.position.clone();
  306. let oldRotation2 = object.rotation && object.rotation.clone();
  307. let oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  308. object.position.copyFromFloats(0, 0, 0);
  309. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  310. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  311. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  312. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  313. returnValue = this._createHeightmap(object);
  314. object.position.copyFrom(oldPosition2);
  315. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  316. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  317. object.computeWorldMatrix(true);
  318. break;
  319. case PhysicsImpostor.ParticleImpostor:
  320. returnValue = new this.BJSCANNON.Particle();
  321. break;
  322. case PhysicsImpostor.NoImpostor:
  323. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0));
  324. break;
  325. }
  326. return returnValue;
  327. }
  328. private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) {
  329. var pos = <FloatArray>(object.getVerticesData(VertexBuffer.PositionKind));
  330. let transform = object.computeWorldMatrix(true);
  331. // convert rawVerts to object space
  332. var temp = new Array<number>();
  333. var index: number;
  334. for (index = 0; index < pos.length; index += 3) {
  335. Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(temp, index);
  336. }
  337. pos = temp;
  338. var matrix = new Array<Array<any>>();
  339. //For now pointDepth will not be used and will be automatically calculated.
  340. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  341. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  342. let boundingInfo = object.getBoundingInfo();
  343. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  344. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  345. var elementSize = dim * 2 / arraySize;
  346. for (var i = 0; i < pos.length; i = i + 3) {
  347. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  348. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  349. var y = -pos[i + 2] + minY;
  350. if (!matrix[x]) {
  351. matrix[x] = [];
  352. }
  353. if (!matrix[x][z]) {
  354. matrix[x][z] = y;
  355. }
  356. matrix[x][z] = Math.max(y, matrix[x][z]);
  357. }
  358. for (var x = 0; x <= arraySize; ++x) {
  359. if (!matrix[x]) {
  360. var loc = 1;
  361. while (!matrix[(x + loc) % arraySize]) {
  362. loc++;
  363. }
  364. matrix[x] = matrix[(x + loc) % arraySize].slice();
  365. //console.log("missing x", x);
  366. }
  367. for (var z = 0; z <= arraySize; ++z) {
  368. if (!matrix[x][z]) {
  369. var loc = 1;
  370. var newValue;
  371. while (newValue === undefined) {
  372. newValue = matrix[x][(z + loc++) % arraySize];
  373. }
  374. matrix[x][z] = newValue;
  375. }
  376. }
  377. }
  378. var shape = new this.BJSCANNON.Heightfield(matrix, {
  379. elementSize: elementSize
  380. });
  381. //For future reference, needed for body transformation
  382. shape.minY = minY;
  383. return shape;
  384. }
  385. private _minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  386. private _plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  387. private _tmpPosition: Vector3 = Vector3.Zero();
  388. private _tmpDeltaPosition: Vector3 = Vector3.Zero();
  389. private _tmpUnityRotation: Quaternion = new Quaternion();
  390. private _updatePhysicsBodyTransformation(impostor: PhysicsImpostor) {
  391. var object = impostor.object;
  392. //make sure it is updated...
  393. object.computeWorldMatrix && object.computeWorldMatrix(true);
  394. // The delta between the mesh position and the mesh bounding box center
  395. let bInfo = object.getBoundingInfo();
  396. if (!bInfo) { return; }
  397. var center = impostor.getObjectCenter();
  398. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  399. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  400. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  401. this._tmpPosition.copyFrom(center);
  402. var quaternion = object.rotationQuaternion;
  403. if (!quaternion) {
  404. return;
  405. }
  406. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  407. //ideally these would be rotated at time of creation like cylinder but they dont extend ConvexPolyhedron
  408. if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor) {
  409. //-90 DEG in X, precalculated
  410. quaternion = quaternion.multiply(this._minus90X);
  411. //Invert! (Precalculated, 90 deg in X)
  412. //No need to clone. this will never change.
  413. impostor.setDeltaRotation(this._plus90X);
  414. }
  415. //If it is a heightfield, if should be centered.
  416. if (impostor.type === PhysicsImpostor.HeightmapImpostor) {
  417. var mesh = <AbstractMesh>(<any>object);
  418. let boundingInfo = mesh.getBoundingInfo();
  419. //calculate the correct body position:
  420. var rotationQuaternion = mesh.rotationQuaternion;
  421. mesh.rotationQuaternion = this._tmpUnityRotation;
  422. mesh.computeWorldMatrix(true);
  423. //get original center with no rotation
  424. var c = center.clone();
  425. var oldPivot = mesh.getPivotMatrix();
  426. if (oldPivot) {
  427. // create a copy the pivot Matrix as it is modified in place
  428. oldPivot = oldPivot.clone();
  429. }
  430. else {
  431. oldPivot = Matrix.Identity();
  432. }
  433. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  434. var p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  435. mesh.setPreTransformMatrix(p);
  436. mesh.computeWorldMatrix(true);
  437. //calculate the translation
  438. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  439. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  440. //add it inverted to the delta
  441. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  442. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  443. //rotation is back
  444. mesh.rotationQuaternion = rotationQuaternion;
  445. mesh.setPreTransformMatrix(oldPivot);
  446. mesh.computeWorldMatrix(true);
  447. } else if (impostor.type === PhysicsImpostor.MeshImpostor) {
  448. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  449. //this._tmpPosition.copyFrom(object.position);
  450. }
  451. impostor.setDeltaPosition(this._tmpDeltaPosition);
  452. //Now update the impostor object
  453. impostor.physicsBody.position.copy(this._tmpPosition);
  454. impostor.physicsBody.quaternion.copy(quaternion);
  455. }
  456. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  457. impostor.object.position.copyFrom(impostor.physicsBody.position);
  458. if (impostor.object.rotationQuaternion) {
  459. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  460. }
  461. }
  462. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  463. impostor.physicsBody.position.copy(newPosition);
  464. impostor.physicsBody.quaternion.copy(newRotation);
  465. }
  466. public isSupported(): boolean {
  467. return this.BJSCANNON !== undefined;
  468. }
  469. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  470. impostor.physicsBody.velocity.copy(velocity);
  471. }
  472. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  473. impostor.physicsBody.angularVelocity.copy(velocity);
  474. }
  475. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  476. var v = impostor.physicsBody.velocity;
  477. if (!v) {
  478. return null;
  479. }
  480. return new Vector3(v.x, v.y, v.z);
  481. }
  482. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  483. var v = impostor.physicsBody.angularVelocity;
  484. if (!v) {
  485. return null;
  486. }
  487. return new Vector3(v.x, v.y, v.z);
  488. }
  489. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  490. impostor.physicsBody.mass = mass;
  491. impostor.physicsBody.updateMassProperties();
  492. }
  493. public getBodyMass(impostor: PhysicsImpostor): number {
  494. return impostor.physicsBody.mass;
  495. }
  496. public getBodyFriction(impostor: PhysicsImpostor): number {
  497. return impostor.physicsBody.material.friction;
  498. }
  499. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  500. impostor.physicsBody.material.friction = friction;
  501. }
  502. public getBodyRestitution(impostor: PhysicsImpostor): number {
  503. return impostor.physicsBody.material.restitution;
  504. }
  505. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  506. impostor.physicsBody.material.restitution = restitution;
  507. }
  508. public sleepBody(impostor: PhysicsImpostor) {
  509. impostor.physicsBody.sleep();
  510. }
  511. public wakeUpBody(impostor: PhysicsImpostor) {
  512. impostor.physicsBody.wakeUp();
  513. }
  514. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number) {
  515. joint.physicsJoint.distance = maxDistance;
  516. }
  517. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  518. if (!motorIndex) {
  519. joint.physicsJoint.enableMotor();
  520. joint.physicsJoint.setMotorSpeed(speed);
  521. if (maxForce) {
  522. this.setLimit(joint, maxForce);
  523. }
  524. }
  525. }
  526. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  527. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  528. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  529. }
  530. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  531. var body = impostor.physicsBody;
  532. mesh.position.x = body.position.x;
  533. mesh.position.y = body.position.y;
  534. mesh.position.z = body.position.z;
  535. if (mesh.rotationQuaternion) {
  536. mesh.rotationQuaternion.x = body.quaternion.x;
  537. mesh.rotationQuaternion.y = body.quaternion.y;
  538. mesh.rotationQuaternion.z = body.quaternion.z;
  539. mesh.rotationQuaternion.w = body.quaternion.w;
  540. }
  541. }
  542. public getRadius(impostor: PhysicsImpostor): number {
  543. var shape = impostor.physicsBody.shapes[0];
  544. return shape.boundingSphereRadius;
  545. }
  546. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  547. var shape = impostor.physicsBody.shapes[0];
  548. result.x = shape.halfExtents.x * 2;
  549. result.y = shape.halfExtents.y * 2;
  550. result.z = shape.halfExtents.z * 2;
  551. }
  552. public dispose() {
  553. }
  554. private _extendNamespace() {
  555. //this will force cannon to execute at least one step when using interpolation
  556. let step_tmp1 = new this.BJSCANNON.Vec3();
  557. let Engine = this.BJSCANNON;
  558. this.BJSCANNON.World.prototype.step = function(dt: number, timeSinceLastCalled: number, maxSubSteps: number) {
  559. maxSubSteps = maxSubSteps || 10;
  560. timeSinceLastCalled = timeSinceLastCalled || 0;
  561. if (timeSinceLastCalled === 0) {
  562. this.internalStep(dt);
  563. this.time += dt;
  564. } else {
  565. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  566. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  567. var t0 = performance.now();
  568. for (var i = 0; i !== internalSteps; i++) {
  569. this.internalStep(dt);
  570. if (performance.now() - t0 > dt * 1000) {
  571. break;
  572. }
  573. }
  574. this.time += timeSinceLastCalled;
  575. var h = this.time % dt;
  576. var h_div_dt = h / dt;
  577. var interpvelo = step_tmp1;
  578. var bodies = this.bodies;
  579. for (var j = 0; j !== bodies.length; j++) {
  580. var b = bodies[j];
  581. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  582. b.position.vsub(b.previousPosition, interpvelo);
  583. interpvelo.scale(h_div_dt, interpvelo);
  584. b.position.vadd(interpvelo, b.interpolatedPosition);
  585. } else {
  586. b.interpolatedPosition.copy(b.position);
  587. b.interpolatedQuaternion.copy(b.quaternion);
  588. }
  589. }
  590. }
  591. };
  592. }
  593. /**
  594. * Does a raycast in the physics world
  595. * @param from when should the ray start?
  596. * @param to when should the ray end?
  597. * @returns PhysicsRaycastResult
  598. */
  599. public raycast(from: Vector3, to: Vector3): PhysicsRaycastResult {
  600. this._cannonRaycastResult.reset();
  601. this.world.raycastClosest(from, to, {}, this._cannonRaycastResult);
  602. this._raycastResult.reset(from, to);
  603. if (this._cannonRaycastResult.hasHit) {
  604. // TODO: do we also want to get the body it hit?
  605. this._raycastResult.setHitData(
  606. {
  607. x: this._cannonRaycastResult.hitNormalWorld.x,
  608. y: this._cannonRaycastResult.hitNormalWorld.y,
  609. z: this._cannonRaycastResult.hitNormalWorld.z,
  610. },
  611. {
  612. x: this._cannonRaycastResult.hitPointWorld.x,
  613. y: this._cannonRaycastResult.hitPointWorld.y,
  614. z: this._cannonRaycastResult.hitPointWorld.z,
  615. }
  616. );
  617. this._raycastResult.setHitDistance(this._cannonRaycastResult.distance);
  618. }
  619. return this._raycastResult;
  620. }
  621. }
  622. PhysicsEngine.DefaultPluginFactory = () => { return new CannonJSPlugin(); };