ammoJSPlugin.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import { Quaternion, Vector3, Matrix } from "../../Maths/math";
  2. import { IPhysicsEnginePlugin, PhysicsImpostorJoint } from "../../Physics/IPhysicsEngine";
  3. import { Logger } from "../../Misc/logger";
  4. import { PhysicsImpostor, IPhysicsEnabledObject } from "../../Physics/physicsImpostor";
  5. import { PhysicsJoint, IMotorEnabledJoint, DistanceJointData } from "../../Physics/physicsJoint";
  6. import { VertexBuffer } from "../../Meshes/buffer";
  7. import { Nullable } from "../../types";
  8. import { AbstractMesh } from "../../Meshes/abstractMesh";
  9. declare var Ammo: any;
  10. /**
  11. * AmmoJS Physics plugin
  12. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  13. * @see https://github.com/kripken/ammo.js/
  14. */
  15. export class AmmoJSPlugin implements IPhysicsEnginePlugin {
  16. /**
  17. * Reference to the Ammo library
  18. */
  19. public bjsAMMO: any = {};
  20. /**
  21. * Created ammoJS world which physics bodies are added to
  22. */
  23. public world: any;
  24. /**
  25. * Name of the plugin
  26. */
  27. public name: string = "AmmoJSPlugin";
  28. private _timeStep: number = 1 / 60;
  29. private _fixedTimeStep: number = 1 / 60;
  30. private _maxSteps = 5;
  31. private _tmpQuaternion = new Quaternion();
  32. private _tmpAmmoTransform: any;
  33. private _tmpAmmoQuaternion: any;
  34. private _tmpAmmoConcreteContactResultCallback: any;
  35. private _collisionConfiguration: any;
  36. private _dispatcher: any;
  37. private _overlappingPairCache: any;
  38. private _solver: any;
  39. private _tmpAmmoVectorA: any;
  40. private _tmpAmmoVectorB: any;
  41. private _tmpAmmoVectorC: any;
  42. private _tmpContactCallbackResult = false;
  43. private static readonly DISABLE_COLLISION_FLAG = 4;
  44. private static readonly KINEMATIC_FLAG = 2;
  45. private static readonly DISABLE_DEACTIVATION_FLAG = 4;
  46. /**
  47. * Initializes the ammoJS plugin
  48. * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)
  49. * @param ammoInjection can be used to inject your own ammo reference
  50. */
  51. public constructor(private _useDeltaForWorldStep: boolean = true, ammoInjection: any = Ammo) {
  52. if (typeof ammoInjection === "function") {
  53. ammoInjection(this.bjsAMMO);
  54. }else {
  55. this.bjsAMMO = ammoInjection;
  56. }
  57. if (!this.isSupported()) {
  58. Logger.Error("AmmoJS is not available. Please make sure you included the js file.");
  59. return;
  60. }
  61. // Initialize the physics world
  62. this._collisionConfiguration = new this.bjsAMMO.btDefaultCollisionConfiguration();
  63. this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);
  64. this._overlappingPairCache = new this.bjsAMMO.btDbvtBroadphase();
  65. this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();
  66. this.world = new this.bjsAMMO.btDiscreteDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration);
  67. this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();
  68. this._tmpAmmoConcreteContactResultCallback.addSingleResult = () => { this._tmpContactCallbackResult = true; };
  69. // Create temp ammo variables
  70. this._tmpAmmoTransform = new this.bjsAMMO.btTransform();
  71. this._tmpAmmoTransform.setIdentity();
  72. this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);
  73. this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);
  74. this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);
  75. this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);
  76. }
  77. /**
  78. * Sets the gravity of the physics world (m/(s^2))
  79. * @param gravity Gravity to set
  80. */
  81. public setGravity(gravity: Vector3): void {
  82. this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);
  83. this.world.setGravity(this._tmpAmmoVectorA);
  84. }
  85. /**
  86. * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)
  87. * @param timeStep timestep to use in seconds
  88. */
  89. public setTimeStep(timeStep: number) {
  90. this._timeStep = timeStep;
  91. }
  92. /**
  93. * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60)
  94. * @param fixedTimeStep fixedTimeStep to use in seconds
  95. */
  96. public setFixedTimeStep(fixedTimeStep: number) {
  97. this._fixedTimeStep = fixedTimeStep;
  98. }
  99. /**
  100. * Sets the maximum number of steps by the physics engine per frame (Default: 5)
  101. * @param maxSteps the maximum number of steps by the physics engine per frame
  102. */
  103. public setMaxSteps(maxSteps: number) {
  104. this._maxSteps = maxSteps;
  105. }
  106. /**
  107. * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)
  108. * @returns the current timestep in seconds
  109. */
  110. public getTimeStep(): number {
  111. return this._timeStep;
  112. }
  113. // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume
  114. private _isImpostorInContact(impostor: PhysicsImpostor) {
  115. this._tmpContactCallbackResult = false;
  116. this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  117. return this._tmpContactCallbackResult;
  118. }
  119. // Ammo's collision events have some weird quirks
  120. // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not
  121. // so only fire event if both contactTest and contactPairTest have a hit
  122. private _isImpostorPairInContact(impostorA: PhysicsImpostor, impostorB: PhysicsImpostor) {
  123. this._tmpContactCallbackResult = false;
  124. this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  125. return this._tmpContactCallbackResult;
  126. }
  127. // Ammo's behavior when maxSteps > 0 does not behave as described in docs
  128. // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  129. //
  130. // When maxSteps is 0 do the entire simulation in one step
  131. // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo)
  132. // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep
  133. private _stepSimulation(timeStep: number = 1 / 60, maxSteps: number = 10, fixedTimeStep: number = 1 / 60) {
  134. if (maxSteps == 0) {
  135. this.world.stepSimulation(timeStep, 0);
  136. } else {
  137. while (maxSteps > 0 && timeStep > 0) {
  138. if (timeStep - fixedTimeStep < fixedTimeStep) {
  139. this.world.stepSimulation(timeStep, 0);
  140. timeStep = 0;
  141. } else {
  142. timeStep -= fixedTimeStep;
  143. this.world.stepSimulation(fixedTimeStep, 0);
  144. }
  145. maxSteps--;
  146. }
  147. }
  148. }
  149. /**
  150. * Moves the physics simulation forward delta seconds and updates the given physics imposters
  151. * Prior to the step the imposters physics location is set to the position of the babylon meshes
  152. * After the step the babylon meshes are set to the position of the physics imposters
  153. * @param delta amount of time to step forward
  154. * @param impostors array of imposters to update before/after the step
  155. */
  156. public executeStep(delta: number, impostors: Array<PhysicsImpostor>): void {
  157. for (var impostor of impostors) {
  158. // Update physics world objects to match babylon world
  159. impostor.beforeStep();
  160. }
  161. this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);
  162. for (var mainImpostor of impostors) {
  163. // After physics update make babylon world objects match physics world objects
  164. mainImpostor.afterStep();
  165. // Handle collision event
  166. if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {
  167. if (this._isImpostorInContact(mainImpostor)) {
  168. for (var collideCallback of mainImpostor._onPhysicsCollideCallbacks) {
  169. for (var otherImpostor of collideCallback.otherImpostors) {
  170. if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {
  171. if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {
  172. mainImpostor.onCollide({ body: otherImpostor.physicsBody });
  173. otherImpostor.onCollide({ body: mainImpostor.physicsBody });
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. }
  181. }
  182. private _tmpVector = new Vector3();
  183. private _tmpMatrix = new Matrix();
  184. /**
  185. * Applies an implulse on the imposter
  186. * @param impostor imposter to apply impulse
  187. * @param force amount of force to be applied to the imposter
  188. * @param contactPoint the location to apply the impulse on the imposter
  189. */
  190. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  191. var worldPoint = this._tmpAmmoVectorA;
  192. var impulse = this._tmpAmmoVectorB;
  193. // Convert contactPoint into world space
  194. if (impostor.object && impostor.object.getWorldMatrix) {
  195. impostor.object.getWorldMatrix().invertToRef(this._tmpMatrix);
  196. Vector3.TransformCoordinatesToRef(contactPoint, this._tmpMatrix, this._tmpVector);
  197. contactPoint = this._tmpVector;
  198. }
  199. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  200. impulse.setValue(force.x, force.y, force.z);
  201. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  202. }
  203. /**
  204. * Applies a force on the imposter
  205. * @param impostor imposter to apply force
  206. * @param force amount of force to be applied to the imposter
  207. * @param contactPoint the location to apply the force on the imposter
  208. */
  209. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  210. var worldPoint = this._tmpAmmoVectorA;
  211. var impulse = this._tmpAmmoVectorB;
  212. // Convert contactPoint into world space
  213. if (impostor.object && impostor.object.getWorldMatrix) {
  214. impostor.object.getWorldMatrix().invertToRef(this._tmpMatrix);
  215. Vector3.TransformCoordinatesToRef(contactPoint, this._tmpMatrix, this._tmpVector);
  216. contactPoint = this._tmpVector;
  217. }
  218. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  219. impulse.setValue(force.x, force.y, force.z);
  220. impostor.physicsBody.applyForce(impulse, worldPoint);
  221. }
  222. /**
  223. * Creates a physics body using the plugin
  224. * @param impostor the imposter to create the physics body on
  225. */
  226. public generatePhysicsBody(impostor: PhysicsImpostor) {
  227. impostor._pluginData = { toDispose: [] };
  228. //parent-child relationship
  229. if (impostor.parent) {
  230. if (impostor.physicsBody) {
  231. this.removePhysicsBody(impostor);
  232. impostor.forceUpdate();
  233. }
  234. return;
  235. }
  236. if (impostor.isBodyInitRequired()) {
  237. var colShape = this._createShape(impostor);
  238. var mass = impostor.getParam("mass");
  239. impostor._pluginData.mass = mass;
  240. var localInertia = new Ammo.btVector3(0, 0, 0);
  241. var startTransform = new Ammo.btTransform();
  242. startTransform.setIdentity();
  243. if (mass !== 0) {
  244. colShape.calculateLocalInertia(mass, localInertia);
  245. }
  246. this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);
  247. this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion!.x, impostor.object.rotationQuaternion!.y, impostor.object.rotationQuaternion!.z, impostor.object.rotationQuaternion!.w);
  248. startTransform.setOrigin(this._tmpAmmoVectorA);
  249. startTransform.setRotation(this._tmpAmmoQuaternion);
  250. var myMotionState = new Ammo.btDefaultMotionState(startTransform);
  251. var rbInfo = new Ammo.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
  252. var body = new Ammo.btRigidBody(rbInfo);
  253. // Make objects kinematic if it's mass is 0
  254. if (mass === 0) {
  255. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.KINEMATIC_FLAG);
  256. body.setActivationState(AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG);
  257. }
  258. // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape
  259. if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) {
  260. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.DISABLE_COLLISION_FLAG);
  261. }
  262. this.world.addRigidBody(body);
  263. impostor.physicsBody = body;
  264. this.setBodyRestitution(impostor, impostor.getParam("restitution"));
  265. this.setBodyFriction(impostor, impostor.getParam("friction"));
  266. impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);
  267. }
  268. }
  269. /**
  270. * Removes the physics body from the imposter and disposes of the body's memory
  271. * @param impostor imposter to remove the physics body from
  272. */
  273. public removePhysicsBody(impostor: PhysicsImpostor) {
  274. if (this.world) {
  275. this.world.removeRigidBody(impostor.physicsBody);
  276. impostor._pluginData.toDispose.forEach((d: any) => {
  277. this.bjsAMMO.destroy(d);
  278. });
  279. }
  280. }
  281. /**
  282. * Generates a joint
  283. * @param impostorJoint the imposter joint to create the joint with
  284. */
  285. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  286. var mainBody = impostorJoint.mainImpostor.physicsBody;
  287. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  288. if (!mainBody || !connectedBody) {
  289. return;
  290. }
  291. var jointData = impostorJoint.joint.jointData;
  292. if (!jointData.mainPivot) {
  293. jointData.mainPivot = new Vector3(0, 0, 0);
  294. }
  295. if (!jointData.connectedPivot) {
  296. jointData.connectedPivot = new Vector3(0, 0, 0);
  297. }
  298. var joint: any;
  299. switch (impostorJoint.joint.type) {
  300. case PhysicsJoint.DistanceJoint:
  301. var distance = (<DistanceJointData>jointData).maxDistance;
  302. if (distance) {
  303. jointData.mainPivot = new Vector3(0, -distance / 2, 0);
  304. jointData.connectedPivot = new Vector3(0, distance / 2, 0);
  305. }
  306. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  307. break;
  308. case PhysicsJoint.HingeJoint:
  309. if (!jointData.mainAxis) {
  310. jointData.mainAxis = new Vector3(0, 0, 0);
  311. }
  312. if (!jointData.connectedAxis) {
  313. jointData.connectedAxis = new Vector3(0, 0, 0);
  314. }
  315. var mainAxis = new Ammo.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);
  316. var connectedAxis = new Ammo.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);
  317. joint = new Ammo.btHingeConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);
  318. break;
  319. case PhysicsJoint.BallAndSocketJoint:
  320. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  321. break;
  322. default:
  323. Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");
  324. joint = new Ammo.btPoint2PointConstraint(mainBody, connectedBody, new Ammo.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new Ammo.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  325. break;
  326. }
  327. this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision);
  328. impostorJoint.joint.physicsJoint = joint;
  329. }
  330. /**
  331. * Removes a joint
  332. * @param impostorJoint the imposter joint to remove the joint from
  333. */
  334. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  335. if (this.world) {
  336. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  337. }
  338. }
  339. // adds all verticies (including child verticies) to the triangle mesh
  340. private _addMeshVerts(btTriangleMesh: any, topLevelObject: IPhysicsEnabledObject, object: IPhysicsEnabledObject) {
  341. var triangleCount = 0;
  342. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  343. var indices = object.getIndices();
  344. if (!indices) {
  345. indices = [];
  346. }
  347. var vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
  348. if (!vertexPositions) {
  349. vertexPositions = [];
  350. }
  351. object.computeWorldMatrix(false);
  352. var faceCount = indices.length / 3;
  353. for (var i = 0; i < faceCount; i++) {
  354. var triPoints = [];
  355. for (var point = 0; point < 3; point++) {
  356. var v = new Vector3(vertexPositions[(indices[(i * 3) + point] * 3) + 0], vertexPositions[(indices[(i * 3) + point] * 3) + 1], vertexPositions[(indices[(i * 3) + point] * 3) + 2]);
  357. v = Vector3.TransformCoordinates(v, object.getWorldMatrix());
  358. v.subtractInPlace(topLevelObject.position);
  359. var vec: any;
  360. if (point == 0) {
  361. vec = this._tmpAmmoVectorA;
  362. } else if (point == 1) {
  363. vec = this._tmpAmmoVectorB;
  364. } else {
  365. vec = this._tmpAmmoVectorC;
  366. }
  367. vec.setValue(v.x, v.y, v.z);
  368. triPoints.push(vec);
  369. }
  370. btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);
  371. triangleCount++;
  372. }
  373. object.getChildMeshes().forEach((m) => {
  374. triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);
  375. });
  376. }
  377. return triangleCount;
  378. }
  379. private _createShape(impostor: PhysicsImpostor, ignoreChildren = false) {
  380. var object = impostor.object;
  381. var returnValue: any;
  382. var extendSize = impostor.getObjectExtendSize();
  383. if (!ignoreChildren) {
  384. var meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];
  385. returnValue = new Ammo.btCompoundShape();
  386. // Add shape of all children to the compound shape
  387. var childrenAdded = 0;
  388. meshChildren.forEach((childMesh) => {
  389. var childImpostor = childMesh.getPhysicsImpostor();
  390. if (childImpostor) {
  391. var shape = this._createShape(childImpostor);
  392. // Position needs to be scaled based on parent's scaling
  393. var parentMat = childMesh.parent!.getWorldMatrix().clone();
  394. var s = new Vector3();
  395. parentMat.decompose(s);
  396. this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);
  397. this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion!.x, childMesh.rotationQuaternion!.y, childMesh.rotationQuaternion!.z, childMesh.rotationQuaternion!.w);
  398. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  399. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  400. childImpostor.dispose();
  401. childrenAdded++;
  402. }
  403. });
  404. if (childrenAdded > 0) {
  405. // Add parents shape as a child if present
  406. if (impostor.type != PhysicsImpostor.NoImpostor) {
  407. var shape = this._createShape(impostor, true);
  408. if (shape) {
  409. this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
  410. this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
  411. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  412. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  413. }
  414. }
  415. return returnValue;
  416. } else {
  417. // If no children with impostors create the actual shape below instead
  418. Ammo.destroy(returnValue);
  419. returnValue = null;
  420. }
  421. }
  422. switch (impostor.type) {
  423. case PhysicsImpostor.SphereImpostor:
  424. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  425. break;
  426. case PhysicsImpostor.CylinderImpostor:
  427. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  428. returnValue = new Ammo.btCylinderShape(this._tmpAmmoVectorA);
  429. break;
  430. case PhysicsImpostor.PlaneImpostor:
  431. case PhysicsImpostor.BoxImpostor:
  432. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  433. returnValue = new Ammo.btBoxShape(this._tmpAmmoVectorA);
  434. break;
  435. case PhysicsImpostor.MeshImpostor:
  436. var tetraMesh = new Ammo.btTriangleMesh();
  437. impostor._pluginData.toDispose.concat([tetraMesh]);
  438. var triangeCount = this._addMeshVerts(tetraMesh, object, object);
  439. if (triangeCount == 0) {
  440. returnValue = new Ammo.btCompoundShape();
  441. } else {
  442. returnValue = new Ammo.btBvhTriangleMeshShape(tetraMesh);
  443. }
  444. break;
  445. case PhysicsImpostor.NoImpostor:
  446. // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints
  447. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  448. break;
  449. default:
  450. Logger.Warn("The impostor type is not currently supported by the ammo plugin.");
  451. break;
  452. }
  453. return returnValue;
  454. }
  455. /**
  456. * Sets the physics body position/rotation from the babylon mesh's position/rotation
  457. * @param impostor imposter containing the physics body and babylon object
  458. */
  459. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  460. impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  461. impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
  462. if (!impostor.object.rotationQuaternion) {
  463. if (impostor.object.rotation) {
  464. this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  465. this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
  466. }
  467. } else {
  468. impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  469. }
  470. }
  471. /**
  472. * Sets the babylon object's position/rotation from the physics body's position/rotation
  473. * @param impostor imposter containing the physics body and babylon object
  474. * @param newPosition new position
  475. * @param newRotation new rotation
  476. */
  477. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  478. var trans = impostor.physicsBody.getWorldTransform();
  479. // If rotation/position has changed update and activate riged body
  480. if (
  481. trans.getOrigin().x() != newPosition.x ||
  482. trans.getOrigin().y() != newPosition.y ||
  483. trans.getOrigin().z() != newPosition.z ||
  484. trans.getRotation().x() != newRotation.x ||
  485. trans.getRotation().y() != newRotation.y ||
  486. trans.getRotation().z() != newRotation.z ||
  487. trans.getRotation().w() != newRotation.w
  488. ) {
  489. this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
  490. trans.setOrigin(this._tmpAmmoVectorA);
  491. this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  492. trans.setRotation(this._tmpAmmoQuaternion);
  493. impostor.physicsBody.setWorldTransform(trans);
  494. if (impostor.mass == 0) {
  495. // Kinematic objects must be updated using motion state
  496. var motionState = impostor.physicsBody.getMotionState();
  497. if (motionState) {
  498. motionState.setWorldTransform(trans);
  499. }
  500. } else {
  501. impostor.physicsBody.activate();
  502. }
  503. }
  504. }
  505. /**
  506. * If this plugin is supported
  507. * @returns true if its supported
  508. */
  509. public isSupported(): boolean {
  510. return this.bjsAMMO !== undefined;
  511. }
  512. /**
  513. * Sets the linear velocity of the physics body
  514. * @param impostor imposter to set the velocity on
  515. * @param velocity velocity to set
  516. */
  517. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  518. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  519. impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
  520. }
  521. /**
  522. * Sets the angular velocity of the physics body
  523. * @param impostor imposter to set the velocity on
  524. * @param velocity velocity to set
  525. */
  526. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  527. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  528. impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
  529. }
  530. /**
  531. * gets the linear velocity
  532. * @param impostor imposter to get linear velocity from
  533. * @returns linear velocity
  534. */
  535. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  536. var v = impostor.physicsBody.getLinearVelocity();
  537. if (!v) {
  538. return null;
  539. }
  540. return new Vector3(v.x(), v.y(), v.z());
  541. }
  542. /**
  543. * gets the angular velocity
  544. * @param impostor imposter to get angular velocity from
  545. * @returns angular velocity
  546. */
  547. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  548. var v = impostor.physicsBody.getAngularVelocity();
  549. if (!v) {
  550. return null;
  551. }
  552. return new Vector3(v.x(), v.y(), v.z());
  553. }
  554. /**
  555. * Sets the mass of physics body
  556. * @param impostor imposter to set the mass on
  557. * @param mass mass to set
  558. */
  559. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  560. impostor.physicsBody.setMassProps(mass);
  561. impostor._pluginData.mass = mass;
  562. }
  563. /**
  564. * Gets the mass of the physics body
  565. * @param impostor imposter to get the mass from
  566. * @returns mass
  567. */
  568. public getBodyMass(impostor: PhysicsImpostor): number {
  569. return impostor._pluginData.mass;
  570. }
  571. /**
  572. * Gets friction of the impostor
  573. * @param impostor impostor to get friction from
  574. * @returns friction value
  575. */
  576. public getBodyFriction(impostor: PhysicsImpostor): number {
  577. return impostor._pluginData.friction;
  578. }
  579. /**
  580. * Sets friction of the impostor
  581. * @param impostor impostor to set friction on
  582. * @param friction friction value
  583. */
  584. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  585. impostor.physicsBody.setFriction(friction);
  586. impostor._pluginData.friction = friction;
  587. }
  588. /**
  589. * Gets restitution of the impostor
  590. * @param impostor impostor to get restitution from
  591. * @returns restitution value
  592. */
  593. public getBodyRestitution(impostor: PhysicsImpostor): number {
  594. return impostor._pluginData.restitution;
  595. }
  596. /**
  597. * Sets resitution of the impostor
  598. * @param impostor impostor to set resitution on
  599. * @param restitution resitution value
  600. */
  601. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  602. impostor.physicsBody.setRestitution(restitution);
  603. impostor._pluginData.restitution = restitution;
  604. }
  605. /**
  606. * Sleeps the physics body and stops it from being active
  607. * @param impostor impostor to sleep
  608. */
  609. public sleepBody(impostor: PhysicsImpostor) {
  610. Logger.Warn("sleepBody is not currently supported by the Ammo physics plugin");
  611. }
  612. /**
  613. * Activates the physics body
  614. * @param impostor impostor to activate
  615. */
  616. public wakeUpBody(impostor: PhysicsImpostor) {
  617. impostor.physicsBody.activate();
  618. }
  619. /**
  620. * Updates the distance parameters of the joint
  621. * @param joint joint to update
  622. * @param maxDistance maximum distance of the joint
  623. * @param minDistance minimum distance of the joint
  624. */
  625. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  626. Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  627. }
  628. /**
  629. * Sets a motor on the joint
  630. * @param joint joint to set motor on
  631. * @param speed speed of the motor
  632. * @param maxForce maximum force of the motor
  633. * @param motorIndex index of the motor
  634. */
  635. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  636. joint.physicsJoint.enableAngularMotor(true, speed, maxForce);
  637. }
  638. /**
  639. * Sets the motors limit
  640. * @param joint joint to set limit on
  641. * @param upperLimit upper limit
  642. * @param lowerLimit lower limit
  643. */
  644. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  645. Logger.Warn("setLimit is not currently supported by the Ammo physics plugin");
  646. }
  647. /**
  648. * Syncs the position and rotation of a mesh with the impostor
  649. * @param mesh mesh to sync
  650. * @param impostor impostor to update the mesh with
  651. */
  652. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  653. var body = impostor.physicsBody;
  654. body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  655. mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
  656. mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
  657. mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
  658. if (mesh.rotationQuaternion) {
  659. mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
  660. mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
  661. mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
  662. mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
  663. }
  664. }
  665. /**
  666. * Gets the radius of the impostor
  667. * @param impostor impostor to get radius from
  668. * @returns the radius
  669. */
  670. public getRadius(impostor: PhysicsImpostor): number {
  671. var exntend = impostor.getObjectExtendSize();
  672. return exntend.x / 2;
  673. }
  674. /**
  675. * Gets the box size of the impostor
  676. * @param impostor impostor to get box size from
  677. * @param result the resulting box size
  678. */
  679. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  680. var exntend = impostor.getObjectExtendSize();
  681. result.x = exntend.x;
  682. result.y = exntend.y;
  683. result.z = exntend.z;
  684. }
  685. /**
  686. * Disposes of the impostor
  687. */
  688. public dispose() {
  689. // Dispose of world
  690. Ammo.destroy(this.world);
  691. Ammo.destroy(this._solver);
  692. Ammo.destroy(this._overlappingPairCache);
  693. Ammo.destroy(this._dispatcher);
  694. Ammo.destroy(this._collisionConfiguration);
  695. // Dispose of tmp variables
  696. Ammo.destroy(this._tmpAmmoVectorA);
  697. Ammo.destroy(this._tmpAmmoVectorB);
  698. Ammo.destroy(this._tmpAmmoVectorC);
  699. Ammo.destroy(this._tmpAmmoTransform);
  700. Ammo.destroy(this._tmpAmmoQuaternion);
  701. Ammo.destroy(this._tmpAmmoConcreteContactResultCallback);
  702. this.world = null;
  703. }
  704. }