babylon.ammoJSPlugin.ts 34 KB

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