babylon.ammoJSPlugin.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. if (meshChildren.length > 0) {
  343. returnValue = new Ammo.btCompoundShape();
  344. // Add shape of all children to the compound shape
  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. }
  359. });
  360. // Add parents shape as a child if present
  361. var shape = this._createShape(impostor, true);
  362. if (shape) {
  363. this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
  364. this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
  365. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  366. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  367. }
  368. return returnValue;
  369. }
  370. }
  371. switch (impostor.type) {
  372. case PhysicsImpostor.SphereImpostor:
  373. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  374. break;
  375. case PhysicsImpostor.CylinderImpostor:
  376. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  377. returnValue = new Ammo.btCylinderShape(this._tmpAmmoVectorA);
  378. break;
  379. case PhysicsImpostor.PlaneImpostor:
  380. case PhysicsImpostor.BoxImpostor:
  381. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  382. returnValue = new Ammo.btBoxShape(this._tmpAmmoVectorA);
  383. break;
  384. case PhysicsImpostor.MeshImpostor:
  385. var tetraMesh = new Ammo.btTriangleMesh();
  386. impostor._pluginData.toDispose.concat([tetraMesh]);
  387. var triangeCount = this._addMeshVerts(tetraMesh, object, object);
  388. if (triangeCount == 0) {
  389. returnValue = new Ammo.btCompoundShape();
  390. }else {
  391. returnValue = new Ammo.btBvhTriangleMeshShape(tetraMesh);
  392. }
  393. break;
  394. case PhysicsImpostor.NoImpostor:
  395. // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints
  396. returnValue = new Ammo.btSphereShape(extendSize.x / 2);
  397. break;
  398. }
  399. return returnValue;
  400. }
  401. /**
  402. * Sets the physics body position/rotation from the babylon mesh's position/rotation
  403. * @param impostor imposter containing the physics body and babylon object
  404. */
  405. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  406. impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  407. impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
  408. if (!impostor.object.rotationQuaternion) {
  409. if (impostor.object.rotation) {
  410. this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  411. this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
  412. }
  413. }else {
  414. impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  415. }
  416. }
  417. /**
  418. * Sets the babylon object's position/rotation from the physics body's position/rotation
  419. * @param impostor imposter containing the physics body and babylon object
  420. * @param newPosition new position
  421. * @param newRotation new rotation
  422. */
  423. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  424. var trans = impostor.physicsBody.getWorldTransform();
  425. // If rotation/position has changed update and activate riged body
  426. if (
  427. trans.getOrigin().x() != newPosition.x ||
  428. trans.getOrigin().y() != newPosition.y ||
  429. trans.getOrigin().z() != newPosition.z ||
  430. trans.getRotation().x() != newRotation.x ||
  431. trans.getRotation().y() != newRotation.y ||
  432. trans.getRotation().z() != newRotation.z ||
  433. trans.getRotation().w() != newRotation.w
  434. ) {
  435. this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
  436. trans.setOrigin(this._tmpAmmoVectorA);
  437. this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  438. trans.setRotation(this._tmpAmmoQuaternion);
  439. impostor.physicsBody.setWorldTransform(trans);
  440. if (impostor.mass == 0) {
  441. // Kinematic objects must be updated using motion state
  442. var motionState = impostor.physicsBody.getMotionState();
  443. if (motionState) {
  444. motionState.setWorldTransform(trans);
  445. }
  446. }else {
  447. impostor.physicsBody.activate();
  448. }
  449. }
  450. }
  451. /**
  452. * If this plugin is supported
  453. * @returns true if its supported
  454. */
  455. public isSupported(): boolean {
  456. return this.bjsAMMO !== undefined;
  457. }
  458. /**
  459. * Sets the linear velocity of the physics body
  460. * @param impostor imposter to set the velocity on
  461. * @param velocity velocity to set
  462. */
  463. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  464. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  465. impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
  466. }
  467. /**
  468. * Sets the angular velocity of the physics body
  469. * @param impostor imposter to set the velocity on
  470. * @param velocity velocity to set
  471. */
  472. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  473. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  474. impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
  475. }
  476. /**
  477. * gets the linear velocity
  478. * @param impostor imposter to get linear velocity from
  479. * @returns linear velocity
  480. */
  481. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  482. var v = impostor.physicsBody.getLinearVelocity();
  483. if (!v) {
  484. return null;
  485. }
  486. return new Vector3(v.x(), v.y(), v.z());
  487. }
  488. /**
  489. * gets the angular velocity
  490. * @param impostor imposter to get angular velocity from
  491. * @returns angular velocity
  492. */
  493. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  494. var v = impostor.physicsBody.getAngularVelocity();
  495. if (!v) {
  496. return null;
  497. }
  498. return new Vector3(v.x(), v.y(), v.z());
  499. }
  500. /**
  501. * Sets the mass of physics body
  502. * @param impostor imposter to set the mass on
  503. * @param mass mass to set
  504. */
  505. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  506. impostor.physicsBody.setMassProps(mass);
  507. impostor._pluginData.mass = mass;
  508. }
  509. /**
  510. * Gets the mass of the physics body
  511. * @param impostor imposter to get the mass from
  512. * @returns mass
  513. */
  514. public getBodyMass(impostor: PhysicsImpostor): number {
  515. return impostor._pluginData.mass;
  516. }
  517. /**
  518. * Gets friction of the impostor
  519. * @param impostor impostor to get friction from
  520. * @returns friction value
  521. */
  522. public getBodyFriction(impostor: PhysicsImpostor): number {
  523. return impostor.physicsBody.getFriction();
  524. }
  525. /**
  526. * Sets friction of the impostor
  527. * @param impostor impostor to set friction on
  528. * @param friction friction value
  529. */
  530. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  531. impostor.physicsBody.setFriction(friction);
  532. }
  533. /**
  534. * Gets restitution of the impostor
  535. * @param impostor impostor to get restitution from
  536. * @returns restitution value
  537. */
  538. public getBodyRestitution(impostor: PhysicsImpostor): number {
  539. return impostor.physicsBody.getRestitution();
  540. }
  541. /**
  542. * Sets resitution of the impostor
  543. * @param impostor impostor to set resitution on
  544. * @param restitution resitution value
  545. */
  546. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  547. impostor.physicsBody.setRestitution(restitution);
  548. }
  549. /**
  550. * Sleeps the physics body and stops it from being active
  551. * @param impostor impostor to sleep
  552. */
  553. public sleepBody(impostor: PhysicsImpostor) {
  554. Tools.Warn("sleepBody is not currently supported by the Ammo physics plugin");
  555. }
  556. /**
  557. * Activates the physics body
  558. * @param impostor impostor to activate
  559. */
  560. public wakeUpBody(impostor: PhysicsImpostor) {
  561. impostor.physicsBody.activate();
  562. }
  563. /**
  564. * Updates the distance parameters of the joint
  565. * @param joint joint to update
  566. * @param maxDistance maximum distance of the joint
  567. * @param minDistance minimum distance of the joint
  568. */
  569. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  570. Tools.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  571. }
  572. /**
  573. * Sets a motor on the joint
  574. * @param joint joint to set motor on
  575. * @param speed speed of the motor
  576. * @param maxForce maximum force of the motor
  577. * @param motorIndex index of the motor
  578. */
  579. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  580. Tools.Warn("setMotor is not currently supported by the Ammo physics plugin");
  581. }
  582. /**
  583. * Sets the motors limit
  584. * @param joint joint to set limit on
  585. * @param upperLimit upper limit
  586. * @param lowerLimit lower limit
  587. */
  588. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  589. Tools.Warn("setLimit is not currently supported by the Ammo physics plugin");
  590. }
  591. /**
  592. * Syncs the position and rotation of a mesh with the impostor
  593. * @param mesh mesh to sync
  594. * @param impostor impostor to update the mesh with
  595. */
  596. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  597. var body = impostor.physicsBody;
  598. body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  599. mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
  600. mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
  601. mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
  602. if (mesh.rotationQuaternion) {
  603. mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
  604. mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
  605. mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
  606. mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
  607. }
  608. }
  609. /**
  610. * Gets the radius of the impostor
  611. * @param impostor impostor to get radius from
  612. * @returns the radius
  613. */
  614. public getRadius(impostor: PhysicsImpostor): number {
  615. var exntend = impostor.getObjectExtendSize();
  616. return exntend.x / 2;
  617. }
  618. /**
  619. * Gets the box size of the impostor
  620. * @param impostor impostor to get box size from
  621. * @param result the resulting box size
  622. */
  623. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  624. var exntend = impostor.getObjectExtendSize();
  625. result.x = exntend.x;
  626. result.y = exntend.y;
  627. result.z = exntend.z;
  628. }
  629. /**
  630. * Disposes of the impostor
  631. */
  632. public dispose() {
  633. // Dispose of world
  634. Ammo.destroy(this.world);
  635. Ammo.destroy(this._solver);
  636. Ammo.destroy(this._overlappingPairCache);
  637. Ammo.destroy(this._dispatcher);
  638. Ammo.destroy(this._collisionConfiguration);
  639. // Dispose of tmp variables
  640. Ammo.destroy(this._tmpAmmoVectorA);
  641. Ammo.destroy(this._tmpAmmoVectorB);
  642. Ammo.destroy(this._tmpAmmoVectorC);
  643. Ammo.destroy(this._tmpAmmoTransform);
  644. Ammo.destroy(this._tmpAmmoQuaternion);
  645. Ammo.destroy(this._tmpAmmoConcreteContactResultCallback);
  646. this.world = null;
  647. }
  648. }
  649. }