ammoJSPlugin.ts 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. import { Quaternion, Vector3, Matrix } from "../../Maths/math.vector";
  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 { VertexData } from "../../Meshes/mesh.vertexData";
  8. import { Nullable } from "../../types";
  9. import { AbstractMesh } from "../../Meshes/abstractMesh";
  10. import { Mesh } from "../../Meshes/mesh";
  11. import { ShapeBuilder } from "../../Meshes/Builders/shapeBuilder";
  12. import { LinesBuilder } from "../../Meshes/Builders/linesBuilder";
  13. import { LinesMesh } from '../../Meshes/linesMesh';
  14. import { PhysicsRaycastResult } from "../physicsRaycastResult";
  15. import { Scalar } from "../../Maths/math.scalar";
  16. declare var Ammo: any;
  17. /**
  18. * AmmoJS Physics plugin
  19. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  20. * @see https://github.com/kripken/ammo.js/
  21. */
  22. export class AmmoJSPlugin implements IPhysicsEnginePlugin {
  23. /**
  24. * Reference to the Ammo library
  25. */
  26. public bjsAMMO: any = {};
  27. /**
  28. * Created ammoJS world which physics bodies are added to
  29. */
  30. public world: any;
  31. /**
  32. * Name of the plugin
  33. */
  34. public name: string = "AmmoJSPlugin";
  35. private _timeStep: number = 1 / 60;
  36. private _fixedTimeStep: number = 1 / 60;
  37. private _maxSteps = 5;
  38. private _tmpQuaternion = new Quaternion();
  39. private _tmpAmmoTransform: any;
  40. private _tmpAmmoQuaternion: any;
  41. private _tmpAmmoConcreteContactResultCallback: any;
  42. private _collisionConfiguration: any;
  43. private _dispatcher: any;
  44. private _overlappingPairCache: any;
  45. private _solver: any;
  46. private _softBodySolver: any;
  47. private _tmpAmmoVectorA: any;
  48. private _tmpAmmoVectorB: any;
  49. private _tmpAmmoVectorC: any;
  50. private _tmpAmmoVectorD: any;
  51. private _tmpContactCallbackResult = false;
  52. private _tmpAmmoVectorRCA: any;
  53. private _tmpAmmoVectorRCB: any;
  54. private _raycastResult: PhysicsRaycastResult;
  55. private static readonly DISABLE_COLLISION_FLAG = 4;
  56. private static readonly KINEMATIC_FLAG = 2;
  57. private static readonly DISABLE_DEACTIVATION_FLAG = 4;
  58. /**
  59. * Initializes the ammoJS plugin
  60. * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)
  61. * @param ammoInjection can be used to inject your own ammo reference
  62. * @param overlappingPairCache can be used to specify your own overlapping pair cache
  63. */
  64. public constructor(private _useDeltaForWorldStep: boolean = true, ammoInjection: any = Ammo, overlappingPairCache: any = null) {
  65. if (typeof ammoInjection === "function") {
  66. ammoInjection(this.bjsAMMO);
  67. } else {
  68. this.bjsAMMO = ammoInjection;
  69. }
  70. if (!this.isSupported()) {
  71. Logger.Error("AmmoJS is not available. Please make sure you included the js file.");
  72. return;
  73. }
  74. // Initialize the physics world
  75. this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration();
  76. this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);
  77. this._overlappingPairCache = overlappingPairCache || new this.bjsAMMO.btDbvtBroadphase();
  78. this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();
  79. this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver();
  80. this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration, this._softBodySolver);
  81. this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();
  82. this._tmpAmmoConcreteContactResultCallback.addSingleResult = () => { this._tmpContactCallbackResult = true; };
  83. this._raycastResult = new PhysicsRaycastResult();
  84. // Create temp ammo variables
  85. this._tmpAmmoTransform = new this.bjsAMMO.btTransform();
  86. this._tmpAmmoTransform.setIdentity();
  87. this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);
  88. this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);
  89. this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);
  90. this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);
  91. this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0, 0, 0);
  92. }
  93. /**
  94. * Sets the gravity of the physics world (m/(s^2))
  95. * @param gravity Gravity to set
  96. */
  97. public setGravity(gravity: Vector3): void {
  98. this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);
  99. this.world.setGravity(this._tmpAmmoVectorA);
  100. this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA);
  101. }
  102. /**
  103. * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)
  104. * @param timeStep timestep to use in seconds
  105. */
  106. public setTimeStep(timeStep: number) {
  107. this._timeStep = timeStep;
  108. }
  109. /**
  110. * 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)
  111. * @param fixedTimeStep fixedTimeStep to use in seconds
  112. */
  113. public setFixedTimeStep(fixedTimeStep: number) {
  114. this._fixedTimeStep = fixedTimeStep;
  115. }
  116. /**
  117. * Sets the maximum number of steps by the physics engine per frame (Default: 5)
  118. * @param maxSteps the maximum number of steps by the physics engine per frame
  119. */
  120. public setMaxSteps(maxSteps: number) {
  121. this._maxSteps = maxSteps;
  122. }
  123. /**
  124. * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)
  125. * @returns the current timestep in seconds
  126. */
  127. public getTimeStep(): number {
  128. return this._timeStep;
  129. }
  130. /**
  131. * The create custom shape handler function to be called when using BABYLON.PhysicsImposter.CustomImpostor
  132. */
  133. public onCreateCustomShape: (impostor: PhysicsImpostor) => any;
  134. // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume
  135. private _isImpostorInContact(impostor: PhysicsImpostor) {
  136. this._tmpContactCallbackResult = false;
  137. this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  138. return this._tmpContactCallbackResult;
  139. }
  140. // Ammo's collision events have some weird quirks
  141. // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not
  142. // so only fire event if both contactTest and contactPairTest have a hit
  143. private _isImpostorPairInContact(impostorA: PhysicsImpostor, impostorB: PhysicsImpostor) {
  144. this._tmpContactCallbackResult = false;
  145. this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);
  146. return this._tmpContactCallbackResult;
  147. }
  148. // Ammo's behavior when maxSteps > 0 does not behave as described in docs
  149. // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  150. //
  151. // When maxSteps is 0 do the entire simulation in one step
  152. // 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)
  153. // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep
  154. private _stepSimulation(timeStep: number = 1 / 60, maxSteps: number = 10, fixedTimeStep: number = 1 / 60) {
  155. if (maxSteps == 0) {
  156. this.world.stepSimulation(timeStep, 0);
  157. } else {
  158. while (maxSteps > 0 && timeStep > 0) {
  159. if (timeStep - fixedTimeStep < fixedTimeStep) {
  160. this.world.stepSimulation(timeStep, 0);
  161. timeStep = 0;
  162. } else {
  163. timeStep -= fixedTimeStep;
  164. this.world.stepSimulation(fixedTimeStep, 0);
  165. }
  166. maxSteps--;
  167. }
  168. }
  169. }
  170. /**
  171. * Moves the physics simulation forward delta seconds and updates the given physics imposters
  172. * Prior to the step the imposters physics location is set to the position of the babylon meshes
  173. * After the step the babylon meshes are set to the position of the physics imposters
  174. * @param delta amount of time to step forward
  175. * @param impostors array of imposters to update before/after the step
  176. */
  177. public executeStep(delta: number, impostors: Array<PhysicsImpostor>): void {
  178. for (var impostor of impostors) {
  179. // Update physics world objects to match babylon world
  180. if (!impostor.soft) {
  181. impostor.beforeStep();
  182. }
  183. }
  184. this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);
  185. for (var mainImpostor of impostors) {
  186. // After physics update make babylon world objects match physics world objects
  187. if (mainImpostor.soft) {
  188. this._afterSoftStep(mainImpostor);
  189. }
  190. else {
  191. mainImpostor.afterStep();
  192. }
  193. // Handle collision event
  194. if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {
  195. if (this._isImpostorInContact(mainImpostor)) {
  196. for (var collideCallback of mainImpostor._onPhysicsCollideCallbacks) {
  197. for (var otherImpostor of collideCallback.otherImpostors) {
  198. if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {
  199. if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {
  200. mainImpostor.onCollide({ body: otherImpostor.physicsBody });
  201. otherImpostor.onCollide({ body: mainImpostor.physicsBody });
  202. }
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. }
  210. /**
  211. * Update babylon mesh to match physics world object
  212. * @param impostor imposter to match
  213. */
  214. private _afterSoftStep(impostor: PhysicsImpostor): void {
  215. if (impostor.type === PhysicsImpostor.RopeImpostor) {
  216. this._ropeStep(impostor);
  217. }
  218. else {
  219. this._softbodyOrClothStep(impostor);
  220. }
  221. }
  222. /**
  223. * Update babylon mesh vertices vertices to match physics world softbody or cloth
  224. * @param impostor imposter to match
  225. */
  226. private _ropeStep(impostor: PhysicsImpostor): void {
  227. var bodyVertices = impostor.physicsBody.get_m_nodes();
  228. var nbVertices = bodyVertices.size();
  229. var node: any;
  230. var nodePositions: any;
  231. var x, y, z: number;
  232. var path: Array<Vector3> = new Array();
  233. for (var n = 0; n < nbVertices; n++) {
  234. node = bodyVertices.at(n);
  235. nodePositions = node.get_m_x();
  236. x = nodePositions.x();
  237. y = nodePositions.y();
  238. z = nodePositions.z();
  239. path.push(new Vector3(x, y, z));
  240. }
  241. var object = impostor.object;
  242. var shape = impostor.getParam("shape");
  243. if (impostor._isFromLine) {
  244. impostor.object = LinesBuilder.CreateLines("lines", { points: path, instance: <LinesMesh>object });
  245. }
  246. else {
  247. impostor.object = ShapeBuilder.ExtrudeShape("ext", { shape: shape, path: path, instance: <Mesh>object });
  248. }
  249. }
  250. /**
  251. * Update babylon mesh vertices vertices to match physics world softbody or cloth
  252. * @param impostor imposter to match
  253. */
  254. private _softbodyOrClothStep(impostor: PhysicsImpostor): void {
  255. var normalDirection = (impostor.type === PhysicsImpostor.ClothImpostor) ? 1 : -1;
  256. var object = impostor.object;
  257. var vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
  258. if (!vertexPositions) {
  259. vertexPositions = [];
  260. }
  261. var vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);
  262. if (!vertexNormals) {
  263. vertexNormals = [];
  264. }
  265. var nbVertices = vertexPositions.length / 3;
  266. var bodyVertices = impostor.physicsBody.get_m_nodes();
  267. var node: any;
  268. var nodePositions: any;
  269. var nodeNormals: any;
  270. var x, y, z: number;
  271. var nx, ny, nz: number;
  272. for (var n = 0; n < nbVertices; n++) {
  273. node = bodyVertices.at(n);
  274. nodePositions = node.get_m_x();
  275. x = nodePositions.x();
  276. y = nodePositions.y();
  277. z = nodePositions.z() * normalDirection;
  278. var nodeNormals = node.get_m_n();
  279. nx = nodeNormals.x();
  280. ny = nodeNormals.y();
  281. nz = nodeNormals.z() * normalDirection;
  282. vertexPositions[3 * n] = x;
  283. vertexPositions[3 * n + 1] = y;
  284. vertexPositions[3 * n + 2] = z;
  285. vertexNormals[3 * n] = nx;
  286. vertexNormals[3 * n + 1] = ny;
  287. vertexNormals[3 * n + 2] = nz;
  288. }
  289. var vertex_data = new VertexData();
  290. vertex_data.positions = vertexPositions;
  291. vertex_data.normals = vertexNormals;
  292. vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);
  293. vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);
  294. if (object && object.getIndices) {
  295. vertex_data.indices = object.getIndices();
  296. }
  297. vertex_data.applyToMesh(<Mesh>object);
  298. }
  299. private _tmpMatrix = new Matrix();
  300. /**
  301. * Applies an impulse on the imposter
  302. * @param impostor imposter to apply impulse to
  303. * @param force amount of force to be applied to the imposter
  304. * @param contactPoint the location to apply the impulse on the imposter
  305. */
  306. public applyImpulse(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  307. if (!impostor.soft) {
  308. impostor.physicsBody.activate();
  309. var worldPoint = this._tmpAmmoVectorA;
  310. var impulse = this._tmpAmmoVectorB;
  311. // Convert contactPoint relative to center of mass
  312. if (impostor.object && impostor.object.getWorldMatrix) {
  313. contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation());
  314. }
  315. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  316. impulse.setValue(force.x, force.y, force.z);
  317. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  318. }
  319. else {
  320. Logger.Warn("Cannot be applied to a soft body");
  321. }
  322. }
  323. /**
  324. * Applies a force on the imposter
  325. * @param impostor imposter to apply force
  326. * @param force amount of force to be applied to the imposter
  327. * @param contactPoint the location to apply the force on the imposter
  328. */
  329. public applyForce(impostor: PhysicsImpostor, force: Vector3, contactPoint: Vector3) {
  330. if (!impostor.soft) {
  331. impostor.physicsBody.activate();
  332. var worldPoint = this._tmpAmmoVectorA;
  333. var impulse = this._tmpAmmoVectorB;
  334. // Convert contactPoint relative to center of mass
  335. if (impostor.object && impostor.object.getWorldMatrix) {
  336. contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation());
  337. }
  338. worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);
  339. impulse.setValue(force.x, force.y, force.z);
  340. impostor.physicsBody.applyForce(impulse, worldPoint);
  341. }
  342. else {
  343. Logger.Warn("Cannot be applied to a soft body");
  344. }
  345. }
  346. /**
  347. * Creates a physics body using the plugin
  348. * @param impostor the imposter to create the physics body on
  349. */
  350. public generatePhysicsBody(impostor: PhysicsImpostor) {
  351. // Note: this method will not be called on child imposotrs for compound impostors
  352. impostor._pluginData.toDispose = [];
  353. //parent-child relationship
  354. if (impostor.parent) {
  355. if (impostor.physicsBody) {
  356. this.removePhysicsBody(impostor);
  357. impostor.forceUpdate();
  358. }
  359. return;
  360. }
  361. if (impostor.isBodyInitRequired()) {
  362. var colShape = this._createShape(impostor);
  363. var mass = impostor.getParam("mass");
  364. impostor._pluginData.mass = mass;
  365. if (impostor.soft) {
  366. colShape.get_m_cfg().set_collisions(0x11);
  367. colShape.get_m_cfg().set_kDP(impostor.getParam("damping"));
  368. this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam("margin"));
  369. colShape.setActivationState(AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG);
  370. this.world.addSoftBody(colShape, 1, -1);
  371. impostor.physicsBody = colShape;
  372. impostor._pluginData.toDispose.push(colShape);
  373. this.setBodyPressure(impostor, 0);
  374. if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {
  375. this.setBodyPressure(impostor, impostor.getParam("pressure"));
  376. }
  377. this.setBodyStiffness(impostor, impostor.getParam("stiffness"));
  378. this.setBodyVelocityIterations(impostor, impostor.getParam("velocityIterations"));
  379. this.setBodyPositionIterations(impostor, impostor.getParam("positionIterations"));
  380. }
  381. else {
  382. var localInertia = new this.bjsAMMO.btVector3(0, 0, 0);
  383. var startTransform = new this.bjsAMMO.btTransform();
  384. startTransform.setIdentity();
  385. if (mass !== 0) {
  386. colShape.calculateLocalInertia(mass, localInertia);
  387. }
  388. this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);
  389. this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion!.x, impostor.object.rotationQuaternion!.y, impostor.object.rotationQuaternion!.z, impostor.object.rotationQuaternion!.w);
  390. startTransform.setOrigin(this._tmpAmmoVectorA);
  391. startTransform.setRotation(this._tmpAmmoQuaternion);
  392. var myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform);
  393. var rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);
  394. var body = new this.bjsAMMO.btRigidBody(rbInfo);
  395. // Make objects kinematic if it's mass is 0
  396. if (mass === 0) {
  397. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.KINEMATIC_FLAG);
  398. body.setActivationState(AmmoJSPlugin.DISABLE_DEACTIVATION_FLAG);
  399. }
  400. // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape
  401. if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) {
  402. body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin.DISABLE_COLLISION_FLAG);
  403. }
  404. let group = impostor.getParam("group");
  405. let mask = impostor.getParam("mask");
  406. if (group && mask) {
  407. this.world.addRigidBody(body, group, mask);
  408. } else {
  409. this.world.addRigidBody(body);
  410. }
  411. impostor.physicsBody = body;
  412. impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);
  413. }
  414. this.setBodyRestitution(impostor, impostor.getParam("restitution"));
  415. this.setBodyFriction(impostor, impostor.getParam("friction"));
  416. }
  417. }
  418. /**
  419. * Removes the physics body from the imposter and disposes of the body's memory
  420. * @param impostor imposter to remove the physics body from
  421. */
  422. public removePhysicsBody(impostor: PhysicsImpostor) {
  423. if (this.world) {
  424. if (impostor.soft) {
  425. this.world.removeSoftBody(impostor.physicsBody);
  426. } else {
  427. this.world.removeRigidBody(impostor.physicsBody);
  428. }
  429. if (impostor._pluginData) {
  430. impostor._pluginData.toDispose.forEach((d: any) => {
  431. this.bjsAMMO.destroy(d);
  432. });
  433. impostor._pluginData.toDispose = [];
  434. }
  435. }
  436. }
  437. /**
  438. * Generates a joint
  439. * @param impostorJoint the imposter joint to create the joint with
  440. */
  441. public generateJoint(impostorJoint: PhysicsImpostorJoint) {
  442. var mainBody = impostorJoint.mainImpostor.physicsBody;
  443. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  444. if (!mainBody || !connectedBody) {
  445. return;
  446. }
  447. var jointData = impostorJoint.joint.jointData;
  448. if (!jointData.mainPivot) {
  449. jointData.mainPivot = new Vector3(0, 0, 0);
  450. }
  451. if (!jointData.connectedPivot) {
  452. jointData.connectedPivot = new Vector3(0, 0, 0);
  453. }
  454. var joint: any;
  455. switch (impostorJoint.joint.type) {
  456. case PhysicsJoint.DistanceJoint:
  457. var distance = (<DistanceJointData>jointData).maxDistance;
  458. if (distance) {
  459. jointData.mainPivot = new Vector3(0, -distance / 2, 0);
  460. jointData.connectedPivot = new Vector3(0, distance / 2, 0);
  461. }
  462. joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  463. break;
  464. case PhysicsJoint.HingeJoint:
  465. if (!jointData.mainAxis) {
  466. jointData.mainAxis = new Vector3(0, 0, 0);
  467. }
  468. if (!jointData.connectedAxis) {
  469. jointData.connectedAxis = new Vector3(0, 0, 0);
  470. }
  471. var mainAxis = new this.bjsAMMO.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);
  472. var connectedAxis = new this.bjsAMMO.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);
  473. joint = new this.bjsAMMO.btHingeConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);
  474. break;
  475. case PhysicsJoint.BallAndSocketJoint:
  476. joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  477. break;
  478. default:
  479. Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");
  480. joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));
  481. break;
  482. }
  483. this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision);
  484. impostorJoint.joint.physicsJoint = joint;
  485. }
  486. /**
  487. * Removes a joint
  488. * @param impostorJoint the imposter joint to remove the joint from
  489. */
  490. public removeJoint(impostorJoint: PhysicsImpostorJoint) {
  491. if (this.world) {
  492. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  493. }
  494. }
  495. // adds all verticies (including child verticies) to the triangle mesh
  496. private _addMeshVerts(btTriangleMesh: any, topLevelObject: IPhysicsEnabledObject, object: IPhysicsEnabledObject) {
  497. var triangleCount = 0;
  498. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  499. var indices = object.getIndices();
  500. if (!indices) {
  501. indices = [];
  502. }
  503. var vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
  504. if (!vertexPositions) {
  505. vertexPositions = [];
  506. }
  507. object.computeWorldMatrix(false);
  508. var faceCount = indices.length / 3;
  509. for (var i = 0; i < faceCount; i++) {
  510. var triPoints = [];
  511. for (var point = 0; point < 3; point++) {
  512. 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]);
  513. // Adjust for initial scaling
  514. Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);
  515. v = Vector3.TransformCoordinates(v, this._tmpMatrix);
  516. var vec: any;
  517. if (point == 0) {
  518. vec = this._tmpAmmoVectorA;
  519. } else if (point == 1) {
  520. vec = this._tmpAmmoVectorB;
  521. } else {
  522. vec = this._tmpAmmoVectorC;
  523. }
  524. vec.setValue(v.x, v.y, v.z);
  525. triPoints.push(vec);
  526. }
  527. btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);
  528. triangleCount++;
  529. }
  530. object.getChildMeshes().forEach((m) => {
  531. triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);
  532. });
  533. }
  534. return triangleCount;
  535. }
  536. /**
  537. * Initialise the soft body vertices to match its object's (mesh) vertices
  538. * Softbody vertices (nodes) are in world space and to match this
  539. * The object's position and rotation is set to zero and so its vertices are also then set in world space
  540. * @param impostor to create the softbody for
  541. */
  542. private _softVertexData(impostor: PhysicsImpostor): VertexData {
  543. var object = impostor.object;
  544. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  545. var indices = object.getIndices();
  546. if (!indices) {
  547. indices = [];
  548. }
  549. var vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
  550. if (!vertexPositions) {
  551. vertexPositions = [];
  552. }
  553. var vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);
  554. if (!vertexNormals) {
  555. vertexNormals = [];
  556. }
  557. object.computeWorldMatrix(false);
  558. var newPoints = [];
  559. var newNorms = [];
  560. for (var i = 0; i < vertexPositions.length; i += 3) {
  561. var v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);
  562. var n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);
  563. v = Vector3.TransformCoordinates(v, object.getWorldMatrix());
  564. n = Vector3.TransformNormal(n, object.getWorldMatrix());
  565. newPoints.push(v.x, v.y, v.z);
  566. newNorms.push(n.x, n.y, n.z);
  567. }
  568. var vertex_data = new VertexData();
  569. vertex_data.positions = newPoints;
  570. vertex_data.normals = newNorms;
  571. vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);
  572. vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);
  573. if (object && object.getIndices) {
  574. vertex_data.indices = object.getIndices();
  575. }
  576. vertex_data.applyToMesh(<Mesh>object);
  577. object.position = Vector3.Zero();
  578. object.rotationQuaternion = null;
  579. object.rotation = Vector3.Zero();
  580. object.computeWorldMatrix(true);
  581. return vertex_data;
  582. }
  583. return VertexData.ExtractFromMesh(<Mesh>object);
  584. }
  585. /**
  586. * Create an impostor's soft body
  587. * @param impostor to create the softbody for
  588. */
  589. private _createSoftbody(impostor: PhysicsImpostor) {
  590. var object = impostor.object;
  591. if (object && object.getIndices) {
  592. var indices = object.getIndices();
  593. if (!indices) {
  594. indices = [];
  595. }
  596. var vertex_data = this._softVertexData(impostor);
  597. var vertexPositions = vertex_data.positions;
  598. var vertexNormals = vertex_data.normals;
  599. if (vertexPositions === null || vertexNormals === null) {
  600. return new this.bjsAMMO.btCompoundShape();
  601. }
  602. else {
  603. var triPoints = [];
  604. var triNorms = [];
  605. for (var i = 0; i < vertexPositions.length; i += 3) {
  606. var v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);
  607. var n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);
  608. triPoints.push(v.x, v.y, -v.z);
  609. triNorms.push(n.x, n.y, -n.z);
  610. }
  611. var softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(
  612. this.world.getWorldInfo(),
  613. triPoints,
  614. object.getIndices(),
  615. indices.length / 3,
  616. true
  617. );
  618. var nbVertices = vertexPositions.length / 3;
  619. var bodyVertices = softBody.get_m_nodes();
  620. var node: any;
  621. var nodeNormals: any;
  622. for (var i = 0; i < nbVertices; i++) {
  623. node = bodyVertices.at(i);
  624. var nodeNormals = node.get_m_n();
  625. nodeNormals.setX(triNorms[3 * i]);
  626. nodeNormals.setY(triNorms[3 * i + 1]);
  627. nodeNormals.setZ(triNorms[3 * i + 2]);
  628. }
  629. return softBody;
  630. }
  631. }
  632. }
  633. /**
  634. * Create cloth for an impostor
  635. * @param impostor to create the softbody for
  636. */
  637. private _createCloth(impostor: PhysicsImpostor) {
  638. var object = impostor.object;
  639. if (object && object.getIndices) {
  640. var indices = object.getIndices();
  641. if (!indices) {
  642. indices = [];
  643. }
  644. var vertex_data = this._softVertexData(impostor);
  645. var vertexPositions = vertex_data.positions;
  646. var vertexNormals = vertex_data.normals;
  647. if (vertexPositions === null || vertexNormals === null) {
  648. return new this.bjsAMMO.btCompoundShape();
  649. }
  650. else {
  651. var len = vertexPositions.length;
  652. var segments = Math.sqrt(len / 3);
  653. impostor.segments = segments;
  654. var segs = segments - 1;
  655. this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);
  656. this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]);
  657. this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);
  658. this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]);
  659. var clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(
  660. this.world.getWorldInfo(),
  661. this._tmpAmmoVectorA,
  662. this._tmpAmmoVectorB,
  663. this._tmpAmmoVectorC,
  664. this._tmpAmmoVectorD,
  665. segments,
  666. segments,
  667. impostor.getParam("fixedPoints"),
  668. true
  669. );
  670. return clothBody;
  671. }
  672. }
  673. }
  674. /**
  675. * Create rope for an impostor
  676. * @param impostor to create the softbody for
  677. */
  678. private _createRope(impostor: PhysicsImpostor) {
  679. var len: number;
  680. var segments: number;
  681. var vertex_data = this._softVertexData(impostor);
  682. var vertexPositions = vertex_data.positions;
  683. var vertexNormals = vertex_data.normals;
  684. if (vertexPositions === null || vertexNormals === null) {
  685. return new this.bjsAMMO.btCompoundShape();
  686. }
  687. //force the mesh to be updatable
  688. vertex_data.applyToMesh(<Mesh>impostor.object, true);
  689. impostor._isFromLine = true;
  690. // If in lines mesh all normals will be zero
  691. var vertexSquared: Array<number> = <Array<number>>vertexNormals.map((x: number) => x * x);
  692. var reducer = (accumulator: number, currentValue: number): number => accumulator + currentValue;
  693. var reduced: number = vertexSquared.reduce(reducer);
  694. if (reduced === 0) { // line mesh
  695. len = vertexPositions.length;
  696. segments = len / 3 - 1;
  697. this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);
  698. this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);
  699. }
  700. else { //extruded mesh
  701. impostor._isFromLine = false;
  702. var pathVectors = impostor.getParam("path");
  703. var shape = impostor.getParam("shape");
  704. if (shape === null) {
  705. Logger.Warn("No shape available for extruded mesh");
  706. return new this.bjsAMMO.btCompoundShape();
  707. }
  708. if ((vertexPositions!.length % (3 * pathVectors.length)) !== 0) {
  709. Logger.Warn("Path does not match extrusion");
  710. return new this.bjsAMMO.btCompoundShape();
  711. }
  712. len = pathVectors.length;
  713. segments = len - 1;
  714. this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z);
  715. this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z);
  716. }
  717. impostor.segments = segments;
  718. var fixedPoints = impostor.getParam("fixedPoints");
  719. fixedPoints = (fixedPoints > 3) ? 3 : fixedPoints;
  720. var ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(
  721. this.world.getWorldInfo(),
  722. this._tmpAmmoVectorA,
  723. this._tmpAmmoVectorB,
  724. segments - 1,
  725. fixedPoints
  726. );
  727. ropeBody.get_m_cfg().set_collisions(0x11);
  728. return ropeBody;
  729. }
  730. /**
  731. * Create a custom physics impostor shape using the plugin's onCreateCustomShape handler
  732. * @param impostor to create the custom physics shape for
  733. */
  734. private _createCustom(impostor: PhysicsImpostor): any {
  735. let returnValue: any = null;
  736. if (this.onCreateCustomShape) {
  737. returnValue = this.onCreateCustomShape(impostor);
  738. }
  739. if (returnValue == null) {
  740. returnValue = new this.bjsAMMO.btCompoundShape();
  741. }
  742. return returnValue;
  743. }
  744. // adds all verticies (including child verticies) to the convex hull shape
  745. private _addHullVerts(btConvexHullShape: any, topLevelObject: IPhysicsEnabledObject, object: IPhysicsEnabledObject) {
  746. var triangleCount = 0;
  747. if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {
  748. var indices = object.getIndices();
  749. if (!indices) {
  750. indices = [];
  751. }
  752. var vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);
  753. if (!vertexPositions) {
  754. vertexPositions = [];
  755. }
  756. object.computeWorldMatrix(false);
  757. var faceCount = indices.length / 3;
  758. for (var i = 0; i < faceCount; i++) {
  759. var triPoints = [];
  760. for (var point = 0; point < 3; point++) {
  761. 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]);
  762. // Adjust for initial scaling
  763. Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);
  764. v = Vector3.TransformCoordinates(v, this._tmpMatrix);
  765. var vec: any;
  766. if (point == 0) {
  767. vec = this._tmpAmmoVectorA;
  768. } else if (point == 1) {
  769. vec = this._tmpAmmoVectorB;
  770. } else {
  771. vec = this._tmpAmmoVectorC;
  772. }
  773. vec.setValue(v.x, v.y, v.z);
  774. triPoints.push(vec);
  775. }
  776. btConvexHullShape.addPoint(triPoints[0], true);
  777. btConvexHullShape.addPoint(triPoints[1], true);
  778. btConvexHullShape.addPoint(triPoints[2], true);
  779. triangleCount++;
  780. }
  781. object.getChildMeshes().forEach((m) => {
  782. triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m);
  783. });
  784. }
  785. return triangleCount;
  786. }
  787. private _createShape(impostor: PhysicsImpostor, ignoreChildren = false) {
  788. var object = impostor.object;
  789. var returnValue: any;
  790. var extendSize = impostor.getObjectExtendSize();
  791. if (!ignoreChildren) {
  792. var meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];
  793. returnValue = new this.bjsAMMO.btCompoundShape();
  794. // Add shape of all children to the compound shape
  795. var childrenAdded = 0;
  796. meshChildren.forEach((childMesh) => {
  797. var childImpostor = childMesh.getPhysicsImpostor();
  798. if (childImpostor) {
  799. if (childImpostor.type == PhysicsImpostor.MeshImpostor) {
  800. throw "A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";
  801. }
  802. var shape = this._createShape(childImpostor);
  803. // Position needs to be scaled based on parent's scaling
  804. var parentMat = childMesh.parent!.getWorldMatrix().clone();
  805. var s = new Vector3();
  806. parentMat.decompose(s);
  807. this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);
  808. this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion!.x, childMesh.rotationQuaternion!.y, childMesh.rotationQuaternion!.z, childMesh.rotationQuaternion!.w);
  809. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  810. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  811. childImpostor.dispose();
  812. childrenAdded++;
  813. }
  814. });
  815. if (childrenAdded > 0) {
  816. // Add parents shape as a child if present
  817. if (impostor.type != PhysicsImpostor.NoImpostor) {
  818. var shape = this._createShape(impostor, true);
  819. if (shape) {
  820. this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);
  821. this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);
  822. this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);
  823. returnValue.addChildShape(this._tmpAmmoTransform, shape);
  824. }
  825. }
  826. return returnValue;
  827. } else {
  828. // If no children with impostors create the actual shape below instead
  829. this.bjsAMMO.destroy(returnValue);
  830. returnValue = null;
  831. }
  832. }
  833. switch (impostor.type) {
  834. case PhysicsImpostor.SphereImpostor:
  835. // Is there a better way to compare floats number? With an epsylon or with a Math function
  836. if (Scalar.WithinEpsilon(extendSize.x, extendSize.y, 0.0001) && Scalar.WithinEpsilon(extendSize.x, extendSize.z, 0.0001)) {
  837. returnValue = new this.bjsAMMO.btSphereShape(extendSize.x / 2);
  838. } else {
  839. // create a btMultiSphereShape because it's not possible to set a local scaling on a btSphereShape
  840. var positions = [new this.bjsAMMO.btVector3(0, 0, 0)];
  841. var radii = [1];
  842. returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1);
  843. returnValue.setLocalScaling(new this.bjsAMMO.btVector3(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2));
  844. }
  845. break;
  846. case PhysicsImpostor.CapsuleImpostor:
  847. returnValue = new this.bjsAMMO.btCapsuleShape(extendSize.x / 2, extendSize.y / 2);
  848. break;
  849. case PhysicsImpostor.CylinderImpostor:
  850. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  851. returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);
  852. break;
  853. case PhysicsImpostor.PlaneImpostor:
  854. case PhysicsImpostor.BoxImpostor:
  855. this._tmpAmmoVectorA.setValue(extendSize.x / 2, extendSize.y / 2, extendSize.z / 2);
  856. returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);
  857. break;
  858. case PhysicsImpostor.MeshImpostor:
  859. if (impostor.getParam("mass") == 0) {
  860. // Only create btBvhTriangleMeshShape impostor is static
  861. // See https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=7283
  862. var tetraMesh = new this.bjsAMMO.btTriangleMesh();
  863. impostor._pluginData.toDispose.push(tetraMesh);
  864. var triangeCount = this._addMeshVerts(tetraMesh, object, object);
  865. if (triangeCount == 0) {
  866. returnValue = new this.bjsAMMO.btCompoundShape();
  867. } else {
  868. returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(tetraMesh);
  869. }
  870. break;
  871. }
  872. // Otherwise create convexHullImpostor
  873. case PhysicsImpostor.ConvexHullImpostor:
  874. var convexMesh = new this.bjsAMMO.btConvexHullShape();
  875. var triangeCount = this._addHullVerts(convexMesh, object, object);
  876. if (triangeCount == 0) {
  877. // Cleanup Unused Convex Hull Shape
  878. impostor._pluginData.toDispose.push(convexMesh);
  879. returnValue = new this.bjsAMMO.btCompoundShape();
  880. } else {
  881. returnValue = convexMesh;
  882. }
  883. break;
  884. case PhysicsImpostor.NoImpostor:
  885. // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints
  886. returnValue = new this.bjsAMMO.btSphereShape(extendSize.x / 2);
  887. break;
  888. case PhysicsImpostor.CustomImpostor:
  889. // Only usable when the plugin's onCreateCustomShape is set
  890. returnValue = this._createCustom(impostor);
  891. break;
  892. case PhysicsImpostor.SoftbodyImpostor:
  893. // Only usable with a mesh that has sufficient and shared vertices
  894. returnValue = this._createSoftbody(impostor);
  895. break;
  896. case PhysicsImpostor.ClothImpostor:
  897. // Only usable with a ground mesh that has sufficient and shared vertices
  898. returnValue = this._createCloth(impostor);
  899. break;
  900. case PhysicsImpostor.RopeImpostor:
  901. // Only usable with a line mesh or an extruded mesh that is updatable
  902. returnValue = this._createRope(impostor);
  903. break;
  904. default:
  905. Logger.Warn("The impostor type is not currently supported by the ammo plugin.");
  906. break;
  907. }
  908. return returnValue;
  909. }
  910. /**
  911. * Sets the physics body position/rotation from the babylon mesh's position/rotation
  912. * @param impostor imposter containing the physics body and babylon object
  913. */
  914. public setTransformationFromPhysicsBody(impostor: PhysicsImpostor) {
  915. impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  916. impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());
  917. if (!impostor.object.rotationQuaternion) {
  918. if (impostor.object.rotation) {
  919. this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  920. this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);
  921. }
  922. } else {
  923. impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());
  924. }
  925. }
  926. /**
  927. * Sets the babylon object's position/rotation from the physics body's position/rotation
  928. * @param impostor imposter containing the physics body and babylon object
  929. * @param newPosition new position
  930. * @param newRotation new rotation
  931. */
  932. public setPhysicsBodyTransformation(impostor: PhysicsImpostor, newPosition: Vector3, newRotation: Quaternion) {
  933. var trans = impostor.physicsBody.getWorldTransform();
  934. // If rotation/position has changed update and activate rigged body
  935. if (
  936. trans.getOrigin().x() != newPosition.x ||
  937. trans.getOrigin().y() != newPosition.y ||
  938. trans.getOrigin().z() != newPosition.z ||
  939. trans.getRotation().x() != newRotation.x ||
  940. trans.getRotation().y() != newRotation.y ||
  941. trans.getRotation().z() != newRotation.z ||
  942. trans.getRotation().w() != newRotation.w
  943. ) {
  944. this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);
  945. trans.setOrigin(this._tmpAmmoVectorA);
  946. this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);
  947. trans.setRotation(this._tmpAmmoQuaternion);
  948. impostor.physicsBody.setWorldTransform(trans);
  949. if (impostor.mass == 0) {
  950. // Kinematic objects must be updated using motion state
  951. var motionState = impostor.physicsBody.getMotionState();
  952. if (motionState) {
  953. motionState.setWorldTransform(trans);
  954. }
  955. } else {
  956. impostor.physicsBody.activate();
  957. }
  958. }
  959. }
  960. /**
  961. * If this plugin is supported
  962. * @returns true if its supported
  963. */
  964. public isSupported(): boolean {
  965. return this.bjsAMMO !== undefined;
  966. }
  967. /**
  968. * Sets the linear velocity of the physics body
  969. * @param impostor imposter to set the velocity on
  970. * @param velocity velocity to set
  971. */
  972. public setLinearVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  973. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  974. if (impostor.soft) {
  975. impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA);
  976. }
  977. else {
  978. impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);
  979. }
  980. }
  981. /**
  982. * Sets the angular velocity of the physics body
  983. * @param impostor imposter to set the velocity on
  984. * @param velocity velocity to set
  985. */
  986. public setAngularVelocity(impostor: PhysicsImpostor, velocity: Vector3) {
  987. this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);
  988. if (impostor.soft) {
  989. impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA);
  990. }
  991. else {
  992. impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);
  993. }
  994. }
  995. /**
  996. * gets the linear velocity
  997. * @param impostor imposter to get linear velocity from
  998. * @returns linear velocity
  999. */
  1000. public getLinearVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  1001. if (impostor.soft) {
  1002. var v = impostor.physicsBody.linearVelocity();
  1003. }
  1004. else {
  1005. var v = impostor.physicsBody.getLinearVelocity();
  1006. }
  1007. if (!v) {
  1008. return null;
  1009. }
  1010. var result = new Vector3(v.x(), v.y(), v.z());
  1011. this.bjsAMMO.destroy(v);
  1012. return result;
  1013. }
  1014. /**
  1015. * gets the angular velocity
  1016. * @param impostor imposter to get angular velocity from
  1017. * @returns angular velocity
  1018. */
  1019. public getAngularVelocity(impostor: PhysicsImpostor): Nullable<Vector3> {
  1020. if (impostor.soft) {
  1021. var v = impostor.physicsBody.angularVelocity();
  1022. }
  1023. else {
  1024. var v = impostor.physicsBody.getAngularVelocity();
  1025. }
  1026. if (!v) {
  1027. return null;
  1028. }
  1029. var result = new Vector3(v.x(), v.y(), v.z());
  1030. this.bjsAMMO.destroy(v);
  1031. return result;
  1032. }
  1033. /**
  1034. * Sets the mass of physics body
  1035. * @param impostor imposter to set the mass on
  1036. * @param mass mass to set
  1037. */
  1038. public setBodyMass(impostor: PhysicsImpostor, mass: number) {
  1039. if (impostor.soft) {
  1040. impostor.physicsBody.setTotalMass(mass, false);
  1041. }
  1042. else {
  1043. impostor.physicsBody.setMassProps(mass);
  1044. }
  1045. impostor._pluginData.mass = mass;
  1046. }
  1047. /**
  1048. * Gets the mass of the physics body
  1049. * @param impostor imposter to get the mass from
  1050. * @returns mass
  1051. */
  1052. public getBodyMass(impostor: PhysicsImpostor): number {
  1053. return impostor._pluginData.mass || 0;
  1054. }
  1055. /**
  1056. * Gets friction of the impostor
  1057. * @param impostor impostor to get friction from
  1058. * @returns friction value
  1059. */
  1060. public getBodyFriction(impostor: PhysicsImpostor): number {
  1061. return impostor._pluginData.friction || 0;
  1062. }
  1063. /**
  1064. * Sets friction of the impostor
  1065. * @param impostor impostor to set friction on
  1066. * @param friction friction value
  1067. */
  1068. public setBodyFriction(impostor: PhysicsImpostor, friction: number) {
  1069. if (impostor.soft) {
  1070. impostor.physicsBody.get_m_cfg().set_kDF(friction);
  1071. }
  1072. else {
  1073. impostor.physicsBody.setFriction(friction);
  1074. }
  1075. impostor._pluginData.friction = friction;
  1076. }
  1077. /**
  1078. * Gets restitution of the impostor
  1079. * @param impostor impostor to get restitution from
  1080. * @returns restitution value
  1081. */
  1082. public getBodyRestitution(impostor: PhysicsImpostor): number {
  1083. return impostor._pluginData.restitution || 0;
  1084. }
  1085. /**
  1086. * Sets resitution of the impostor
  1087. * @param impostor impostor to set resitution on
  1088. * @param restitution resitution value
  1089. */
  1090. public setBodyRestitution(impostor: PhysicsImpostor, restitution: number) {
  1091. impostor.physicsBody.setRestitution(restitution);
  1092. impostor._pluginData.restitution = restitution;
  1093. }
  1094. /**
  1095. * Gets pressure inside the impostor
  1096. * @param impostor impostor to get pressure from
  1097. * @returns pressure value
  1098. */
  1099. public getBodyPressure(impostor: PhysicsImpostor): number {
  1100. if (!impostor.soft) {
  1101. Logger.Warn("Pressure is not a property of a rigid body");
  1102. return 0;
  1103. }
  1104. return impostor._pluginData.pressure || 0;
  1105. }
  1106. /**
  1107. * Sets pressure inside a soft body impostor
  1108. * Cloth and rope must remain 0 pressure
  1109. * @param impostor impostor to set pressure on
  1110. * @param pressure pressure value
  1111. */
  1112. public setBodyPressure(impostor: PhysicsImpostor, pressure: number) {
  1113. if (impostor.soft) {
  1114. if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {
  1115. impostor.physicsBody.get_m_cfg().set_kPR(pressure);
  1116. impostor._pluginData.pressure = pressure;
  1117. }
  1118. else {
  1119. impostor.physicsBody.get_m_cfg().set_kPR(0);
  1120. impostor._pluginData.pressure = 0;
  1121. }
  1122. }
  1123. else {
  1124. Logger.Warn("Pressure can only be applied to a softbody");
  1125. }
  1126. }
  1127. /**
  1128. * Gets stiffness of the impostor
  1129. * @param impostor impostor to get stiffness from
  1130. * @returns pressure value
  1131. */
  1132. public getBodyStiffness(impostor: PhysicsImpostor): number {
  1133. if (!impostor.soft) {
  1134. Logger.Warn("Stiffness is not a property of a rigid body");
  1135. return 0;
  1136. }
  1137. return impostor._pluginData.stiffness || 0;
  1138. }
  1139. /**
  1140. * Sets stiffness of the impostor
  1141. * @param impostor impostor to set stiffness on
  1142. * @param stiffness stiffness value from 0 to 1
  1143. */
  1144. public setBodyStiffness(impostor: PhysicsImpostor, stiffness: number) {
  1145. if (impostor.soft) {
  1146. stiffness = stiffness < 0 ? 0 : stiffness;
  1147. stiffness = stiffness > 1 ? 1 : stiffness;
  1148. impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness);
  1149. impostor._pluginData.stiffness = stiffness;
  1150. }
  1151. else {
  1152. Logger.Warn("Stiffness cannot be applied to a rigid body");
  1153. }
  1154. }
  1155. /**
  1156. * Gets velocityIterations of the impostor
  1157. * @param impostor impostor to get velocity iterations from
  1158. * @returns velocityIterations value
  1159. */
  1160. public getBodyVelocityIterations(impostor: PhysicsImpostor): number {
  1161. if (!impostor.soft) {
  1162. Logger.Warn("Velocity iterations is not a property of a rigid body");
  1163. return 0;
  1164. }
  1165. return impostor._pluginData.velocityIterations || 0;
  1166. }
  1167. /**
  1168. * Sets velocityIterations of the impostor
  1169. * @param impostor impostor to set velocity iterations on
  1170. * @param velocityIterations velocityIterations value
  1171. */
  1172. public setBodyVelocityIterations(impostor: PhysicsImpostor, velocityIterations: number) {
  1173. if (impostor.soft) {
  1174. velocityIterations = velocityIterations < 0 ? 0 : velocityIterations;
  1175. impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations);
  1176. impostor._pluginData.velocityIterations = velocityIterations;
  1177. }
  1178. else {
  1179. Logger.Warn("Velocity iterations cannot be applied to a rigid body");
  1180. }
  1181. }
  1182. /**
  1183. * Gets positionIterations of the impostor
  1184. * @param impostor impostor to get position iterations from
  1185. * @returns positionIterations value
  1186. */
  1187. public getBodyPositionIterations(impostor: PhysicsImpostor): number {
  1188. if (!impostor.soft) {
  1189. Logger.Warn("Position iterations is not a property of a rigid body");
  1190. return 0;
  1191. }
  1192. return impostor._pluginData.positionIterations || 0;
  1193. }
  1194. /**
  1195. * Sets positionIterations of the impostor
  1196. * @param impostor impostor to set position on
  1197. * @param positionIterations positionIterations value
  1198. */
  1199. public setBodyPositionIterations(impostor: PhysicsImpostor, positionIterations: number) {
  1200. if (impostor.soft) {
  1201. positionIterations = positionIterations < 0 ? 0 : positionIterations;
  1202. impostor.physicsBody.get_m_cfg().set_piterations(positionIterations);
  1203. impostor._pluginData.positionIterations = positionIterations;
  1204. }
  1205. else {
  1206. Logger.Warn("Position iterations cannot be applied to a rigid body");
  1207. }
  1208. }
  1209. /**
  1210. * Append an anchor to a cloth object
  1211. * @param impostor is the cloth impostor to add anchor to
  1212. * @param otherImpostor is the rigid impostor to anchor to
  1213. * @param width ratio across width from 0 to 1
  1214. * @param height ratio up height from 0 to 1
  1215. * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little strech
  1216. * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false
  1217. */
  1218. public appendAnchor(impostor: PhysicsImpostor, otherImpostor: PhysicsImpostor, width: number, height: number, influence: number = 1, noCollisionBetweenLinkedBodies: boolean = false) {
  1219. var segs = impostor.segments;
  1220. var nbAcross = Math.round((segs - 1) * width);
  1221. var nbUp = Math.round((segs - 1) * height);
  1222. var nbDown = segs - 1 - nbUp;
  1223. var node = nbAcross + segs * nbDown;
  1224. impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);
  1225. }
  1226. /**
  1227. * Append an hook to a rope object
  1228. * @param impostor is the rope impostor to add hook to
  1229. * @param otherImpostor is the rigid impostor to hook to
  1230. * @param length ratio along the rope from 0 to 1
  1231. * @param influence the elasticity between soft impostor and anchor from 0, very stretchy to 1, little strech
  1232. * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false
  1233. */
  1234. public appendHook(impostor: PhysicsImpostor, otherImpostor: PhysicsImpostor, length: number, influence: number = 1, noCollisionBetweenLinkedBodies: boolean = false) {
  1235. var node = Math.round(impostor.segments * length);
  1236. impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);
  1237. }
  1238. /**
  1239. * Sleeps the physics body and stops it from being active
  1240. * @param impostor impostor to sleep
  1241. */
  1242. public sleepBody(impostor: PhysicsImpostor) {
  1243. Logger.Warn("sleepBody is not currently supported by the Ammo physics plugin");
  1244. }
  1245. /**
  1246. * Activates the physics body
  1247. * @param impostor impostor to activate
  1248. */
  1249. public wakeUpBody(impostor: PhysicsImpostor) {
  1250. impostor.physicsBody.activate();
  1251. }
  1252. /**
  1253. * Updates the distance parameters of the joint
  1254. * @param joint joint to update
  1255. * @param maxDistance maximum distance of the joint
  1256. * @param minDistance minimum distance of the joint
  1257. */
  1258. public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) {
  1259. Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin");
  1260. }
  1261. /**
  1262. * Sets a motor on the joint
  1263. * @param joint joint to set motor on
  1264. * @param speed speed of the motor
  1265. * @param maxForce maximum force of the motor
  1266. * @param motorIndex index of the motor
  1267. */
  1268. public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) {
  1269. joint.physicsJoint.enableAngularMotor(true, speed, maxForce);
  1270. }
  1271. /**
  1272. * Sets the motors limit
  1273. * @param joint joint to set limit on
  1274. * @param upperLimit upper limit
  1275. * @param lowerLimit lower limit
  1276. */
  1277. public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) {
  1278. Logger.Warn("setLimit is not currently supported by the Ammo physics plugin");
  1279. }
  1280. /**
  1281. * Syncs the position and rotation of a mesh with the impostor
  1282. * @param mesh mesh to sync
  1283. * @param impostor impostor to update the mesh with
  1284. */
  1285. public syncMeshWithImpostor(mesh: AbstractMesh, impostor: PhysicsImpostor) {
  1286. var body = impostor.physicsBody;
  1287. body.getMotionState().getWorldTransform(this._tmpAmmoTransform);
  1288. mesh.position.x = this._tmpAmmoTransform.getOrigin().x();
  1289. mesh.position.y = this._tmpAmmoTransform.getOrigin().y();
  1290. mesh.position.z = this._tmpAmmoTransform.getOrigin().z();
  1291. if (mesh.rotationQuaternion) {
  1292. mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();
  1293. mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();
  1294. mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();
  1295. mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();
  1296. }
  1297. }
  1298. /**
  1299. * Gets the radius of the impostor
  1300. * @param impostor impostor to get radius from
  1301. * @returns the radius
  1302. */
  1303. public getRadius(impostor: PhysicsImpostor): number {
  1304. var exntend = impostor.getObjectExtendSize();
  1305. return exntend.x / 2;
  1306. }
  1307. /**
  1308. * Gets the box size of the impostor
  1309. * @param impostor impostor to get box size from
  1310. * @param result the resulting box size
  1311. */
  1312. public getBoxSizeToRef(impostor: PhysicsImpostor, result: Vector3): void {
  1313. var exntend = impostor.getObjectExtendSize();
  1314. result.x = exntend.x;
  1315. result.y = exntend.y;
  1316. result.z = exntend.z;
  1317. }
  1318. /**
  1319. * Disposes of the impostor
  1320. */
  1321. public dispose() {
  1322. // Dispose of world
  1323. this.bjsAMMO.destroy(this.world);
  1324. this.bjsAMMO.destroy(this._solver);
  1325. this.bjsAMMO.destroy(this._overlappingPairCache);
  1326. this.bjsAMMO.destroy(this._dispatcher);
  1327. this.bjsAMMO.destroy(this._collisionConfiguration);
  1328. // Dispose of tmp variables
  1329. this.bjsAMMO.destroy(this._tmpAmmoVectorA);
  1330. this.bjsAMMO.destroy(this._tmpAmmoVectorB);
  1331. this.bjsAMMO.destroy(this._tmpAmmoVectorC);
  1332. this.bjsAMMO.destroy(this._tmpAmmoTransform);
  1333. this.bjsAMMO.destroy(this._tmpAmmoQuaternion);
  1334. this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback);
  1335. this.world = null;
  1336. }
  1337. /**
  1338. * Does a raycast in the physics world
  1339. * @param from when should the ray start?
  1340. * @param to when should the ray end?
  1341. * @returns PhysicsRaycastResult
  1342. */
  1343. public raycast(from: Vector3, to: Vector3): PhysicsRaycastResult {
  1344. this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z);
  1345. this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z);
  1346. var rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB);
  1347. this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback);
  1348. this._raycastResult.reset(from, to);
  1349. if (rayCallback.hasHit()) {
  1350. // TODO: do we want/need the body? If so, set all the data
  1351. /*
  1352. var rigidBody = this.bjsAMMO.btRigidBody.prototype.upcast(
  1353. rayCallback.get_m_collisionObject()
  1354. );
  1355. var body = {};
  1356. */
  1357. this._raycastResult.setHitData(
  1358. {
  1359. x: rayCallback.get_m_hitNormalWorld().x(),
  1360. y: rayCallback.get_m_hitNormalWorld().y(),
  1361. z: rayCallback.get_m_hitNormalWorld().z(),
  1362. },
  1363. {
  1364. x: rayCallback.get_m_hitPointWorld().x(),
  1365. y: rayCallback.get_m_hitPointWorld().y(),
  1366. z: rayCallback.get_m_hitPointWorld().z(),
  1367. }
  1368. );
  1369. this._raycastResult.calculateHitDistance();
  1370. }
  1371. this.bjsAMMO.destroy(rayCallback);
  1372. this.bjsAMMO.destroy(this._tmpAmmoVectorRCA);
  1373. this.bjsAMMO.destroy(this._tmpAmmoVectorRCB);
  1374. return this._raycastResult;
  1375. }
  1376. }