physicsImpostor.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. import { Nullable, IndicesArray } from "../types";
  2. import { Logger } from "../Misc/logger";
  3. import { ArrayTools } from "../Misc/arrayTools";
  4. import { Vector3, Matrix, Quaternion } from "../Maths/math.vector";
  5. import { TransformNode } from "../Meshes/transformNode";
  6. import { AbstractMesh } from "../Meshes/abstractMesh";
  7. import { Mesh } from "../Meshes/mesh";
  8. import { Scene } from "../scene";
  9. import { Bone } from "../Bones/bone";
  10. import { BoundingInfo } from "../Culling/boundingInfo";
  11. import { IPhysicsEngine } from "./IPhysicsEngine";
  12. import { PhysicsJoint, PhysicsJointData } from "./physicsJoint";
  13. import { Space } from '../Maths/math.axis';
  14. /**
  15. * The interface for the physics imposter parameters
  16. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  17. */
  18. export interface PhysicsImpostorParameters {
  19. /**
  20. * The mass of the physics imposter
  21. */
  22. mass: number;
  23. /**
  24. * The friction of the physics imposter
  25. */
  26. friction?: number;
  27. /**
  28. * The coefficient of restitution of the physics imposter
  29. */
  30. restitution?: number;
  31. /**
  32. * The native options of the physics imposter
  33. */
  34. nativeOptions?: any;
  35. /**
  36. * Specifies if the parent should be ignored
  37. */
  38. ignoreParent?: boolean;
  39. /**
  40. * Specifies if bi-directional transformations should be disabled
  41. */
  42. disableBidirectionalTransformation?: boolean;
  43. /**
  44. * The pressure inside the physics imposter, soft object only
  45. */
  46. pressure?: number;
  47. /**
  48. * The stiffness the physics imposter, soft object only
  49. */
  50. stiffness?: number;
  51. /**
  52. * The number of iterations used in maintaining consistent vertex velocities, soft object only
  53. */
  54. velocityIterations?: number;
  55. /**
  56. * The number of iterations used in maintaining consistent vertex positions, soft object only
  57. */
  58. positionIterations?: number;
  59. /**
  60. * The number used to fix points on a cloth (0, 1, 2, 4, 8) or rope (0, 1, 2) only
  61. * 0 None, 1, back left or top, 2, back right or bottom, 4, front left, 8, front right
  62. * Add to fix multiple points
  63. */
  64. fixedPoints?: number;
  65. /**
  66. * The collision margin around a soft object
  67. */
  68. margin?: number;
  69. /**
  70. * The collision margin around a soft object
  71. */
  72. damping?: number;
  73. /**
  74. * The path for a rope based on an extrusion
  75. */
  76. path?: any;
  77. /**
  78. * The shape of an extrusion used for a rope based on an extrusion
  79. */
  80. shape?: any;
  81. }
  82. /**
  83. * Interface for a physics-enabled object
  84. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  85. */
  86. export interface IPhysicsEnabledObject {
  87. /**
  88. * The position of the physics-enabled object
  89. */
  90. position: Vector3;
  91. /**
  92. * The rotation of the physics-enabled object
  93. */
  94. rotationQuaternion: Nullable<Quaternion>;
  95. /**
  96. * The scale of the physics-enabled object
  97. */
  98. scaling: Vector3;
  99. /**
  100. * The rotation of the physics-enabled object
  101. */
  102. rotation?: Vector3;
  103. /**
  104. * The parent of the physics-enabled object
  105. */
  106. parent?: any;
  107. /**
  108. * The bounding info of the physics-enabled object
  109. * @returns The bounding info of the physics-enabled object
  110. */
  111. getBoundingInfo(): BoundingInfo;
  112. /**
  113. * Computes the world matrix
  114. * @param force Specifies if the world matrix should be computed by force
  115. * @returns A world matrix
  116. */
  117. computeWorldMatrix(force: boolean): Matrix;
  118. /**
  119. * Gets the world matrix
  120. * @returns A world matrix
  121. */
  122. getWorldMatrix?(): Matrix;
  123. /**
  124. * Gets the child meshes
  125. * @param directDescendantsOnly Specifies if only direct-descendants should be obtained
  126. * @returns An array of abstract meshes
  127. */
  128. getChildMeshes?(directDescendantsOnly?: boolean): Array<AbstractMesh>;
  129. /**
  130. * Gets the vertex data
  131. * @param kind The type of vertex data
  132. * @returns A nullable array of numbers, or a float32 array
  133. */
  134. getVerticesData(kind: string): Nullable<Array<number> | Float32Array>;
  135. /**
  136. * Gets the indices from the mesh
  137. * @returns A nullable array of index arrays
  138. */
  139. getIndices?(): Nullable<IndicesArray>;
  140. /**
  141. * Gets the scene from the mesh
  142. * @returns the indices array or null
  143. */
  144. getScene?(): Scene;
  145. /**
  146. * Gets the absolute position from the mesh
  147. * @returns the absolute position
  148. */
  149. getAbsolutePosition(): Vector3;
  150. /**
  151. * Gets the absolute pivot point from the mesh
  152. * @returns the absolute pivot point
  153. */
  154. getAbsolutePivotPoint(): Vector3;
  155. /**
  156. * Rotates the mesh
  157. * @param axis The axis of rotation
  158. * @param amount The amount of rotation
  159. * @param space The space of the rotation
  160. * @returns The rotation transform node
  161. */
  162. rotate(axis: Vector3, amount: number, space?: Space): TransformNode;
  163. /**
  164. * Translates the mesh
  165. * @param axis The axis of translation
  166. * @param distance The distance of translation
  167. * @param space The space of the translation
  168. * @returns The transform node
  169. */
  170. translate(axis: Vector3, distance: number, space?: Space): TransformNode;
  171. /**
  172. * Sets the absolute position of the mesh
  173. * @param absolutePosition The absolute position of the mesh
  174. * @returns The transform node
  175. */
  176. setAbsolutePosition(absolutePosition: Vector3): TransformNode;
  177. /**
  178. * Gets the class name of the mesh
  179. * @returns The class name
  180. */
  181. getClassName(): string;
  182. }
  183. Mesh._PhysicsImpostorParser = function(scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor {
  184. return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, {
  185. mass: jsonObject.physicsMass,
  186. friction: jsonObject.physicsFriction,
  187. restitution: jsonObject.physicsRestitution
  188. }, scene);
  189. };
  190. /**
  191. * Represents a physics imposter
  192. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  193. */
  194. export class PhysicsImpostor {
  195. /**
  196. * The default object size of the imposter
  197. */
  198. public static DEFAULT_OBJECT_SIZE: Vector3 = new Vector3(1, 1, 1);
  199. /**
  200. * The identity quaternion of the imposter
  201. */
  202. public static IDENTITY_QUATERNION = Quaternion.Identity();
  203. /** @hidden */
  204. public _pluginData: any = {};
  205. private _physicsEngine: Nullable<IPhysicsEngine>;
  206. //The native cannon/oimo/energy physics body object.
  207. private _physicsBody: any;
  208. private _bodyUpdateRequired: boolean = false;
  209. private _onBeforePhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
  210. private _onAfterPhysicsStepCallbacks = new Array<(impostor: PhysicsImpostor) => void>();
  211. /** @hidden */
  212. public _onPhysicsCollideCallbacks: Array<{ callback: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void, otherImpostors: Array<PhysicsImpostor> }> = [];
  213. private _deltaPosition: Vector3 = Vector3.Zero();
  214. private _deltaRotation: Quaternion;
  215. private _deltaRotationConjugated: Quaternion;
  216. /** @hidden */
  217. public _isFromLine: boolean;
  218. //If set, this is this impostor's parent
  219. private _parent: Nullable<PhysicsImpostor>;
  220. private _isDisposed = false;
  221. private static _tmpVecs: Vector3[] = ArrayTools.BuildArray(3, Vector3.Zero);
  222. private static _tmpQuat: Quaternion = Quaternion.Identity();
  223. /**
  224. * Specifies if the physics imposter is disposed
  225. */
  226. get isDisposed(): boolean {
  227. return this._isDisposed;
  228. }
  229. /**
  230. * Gets the mass of the physics imposter
  231. */
  232. get mass(): number {
  233. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  234. }
  235. set mass(value: number) {
  236. this.setMass(value);
  237. }
  238. /**
  239. * Gets the coefficient of friction
  240. */
  241. get friction(): number {
  242. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  243. }
  244. /**
  245. * Sets the coefficient of friction
  246. */
  247. set friction(value: number) {
  248. if (!this._physicsEngine) {
  249. return;
  250. }
  251. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  252. }
  253. /**
  254. * Gets the coefficient of restitution
  255. */
  256. get restitution(): number {
  257. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  258. }
  259. /**
  260. * Sets the coefficient of restitution
  261. */
  262. set restitution(value: number) {
  263. if (!this._physicsEngine) {
  264. return;
  265. }
  266. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  267. }
  268. /**
  269. * Gets the pressure of a soft body; only supported by the AmmoJSPlugin
  270. */
  271. get pressure(): number {
  272. if (!this._physicsEngine) {
  273. return 0;
  274. }
  275. const plugin = this._physicsEngine.getPhysicsPlugin();
  276. if (!plugin.setBodyPressure) {
  277. return 0;
  278. }
  279. return plugin.getBodyPressure!(this);
  280. }
  281. /**
  282. * Sets the pressure of a soft body; only supported by the AmmoJSPlugin
  283. */
  284. set pressure(value: number) {
  285. if (!this._physicsEngine) {
  286. return;
  287. }
  288. const plugin = this._physicsEngine.getPhysicsPlugin();
  289. if (!plugin.setBodyPressure) {
  290. return;
  291. }
  292. plugin.setBodyPressure!(this, value);
  293. }
  294. /**
  295. * Gets the stiffness of a soft body; only supported by the AmmoJSPlugin
  296. */
  297. get stiffness(): number {
  298. if (!this._physicsEngine) {
  299. return 0;
  300. }
  301. const plugin = this._physicsEngine.getPhysicsPlugin();
  302. if (!plugin.getBodyStiffness) {
  303. return 0;
  304. }
  305. return plugin.getBodyStiffness!(this);
  306. }
  307. /**
  308. * Sets the stiffness of a soft body; only supported by the AmmoJSPlugin
  309. */
  310. set stiffness(value: number) {
  311. if (!this._physicsEngine) {
  312. return;
  313. }
  314. const plugin = this._physicsEngine.getPhysicsPlugin();
  315. if (!plugin.setBodyStiffness) {
  316. return;
  317. }
  318. plugin.setBodyStiffness!(this, value);
  319. }
  320. /**
  321. * Gets the velocityIterations of a soft body; only supported by the AmmoJSPlugin
  322. */
  323. get velocityIterations(): number {
  324. if (!this._physicsEngine) {
  325. return 0;
  326. }
  327. const plugin = this._physicsEngine.getPhysicsPlugin();
  328. if (!plugin.getBodyVelocityIterations) {
  329. return 0;
  330. }
  331. return plugin.getBodyVelocityIterations!(this);
  332. }
  333. /**
  334. * Sets the velocityIterations of a soft body; only supported by the AmmoJSPlugin
  335. */
  336. set velocityIterations(value: number) {
  337. if (!this._physicsEngine) {
  338. return;
  339. }
  340. const plugin = this._physicsEngine.getPhysicsPlugin();
  341. if (!plugin.setBodyVelocityIterations) {
  342. return;
  343. }
  344. plugin.setBodyVelocityIterations!(this, value);
  345. }
  346. /**
  347. * Gets the positionIterations of a soft body; only supported by the AmmoJSPlugin
  348. */
  349. get positionIterations(): number {
  350. if (!this._physicsEngine) {
  351. return 0;
  352. }
  353. const plugin = this._physicsEngine.getPhysicsPlugin();
  354. if (!plugin.getBodyPositionIterations) {
  355. return 0;
  356. }
  357. return plugin.getBodyPositionIterations!(this);
  358. }
  359. /**
  360. * Sets the positionIterations of a soft body; only supported by the AmmoJSPlugin
  361. */
  362. set positionIterations(value: number) {
  363. if (!this._physicsEngine) {
  364. return;
  365. }
  366. const plugin = this._physicsEngine.getPhysicsPlugin();
  367. if (!plugin.setBodyPositionIterations) {
  368. return;
  369. }
  370. plugin.setBodyPositionIterations!(this, value);
  371. }
  372. /**
  373. * The unique id of the physics imposter
  374. * set by the physics engine when adding this impostor to the array
  375. */
  376. public uniqueId: number;
  377. /**
  378. * @hidden
  379. */
  380. public soft: boolean = false;
  381. /**
  382. * @hidden
  383. */
  384. public segments: number = 0;
  385. private _joints: Array<{
  386. joint: PhysicsJoint,
  387. otherImpostor: PhysicsImpostor
  388. }>;
  389. /**
  390. * Initializes the physics imposter
  391. * @param object The physics-enabled object used as the physics imposter
  392. * @param type The type of the physics imposter
  393. * @param _options The options for the physics imposter
  394. * @param _scene The Babylon scene
  395. */
  396. constructor(
  397. /**
  398. * The physics-enabled object used as the physics imposter
  399. */
  400. public object: IPhysicsEnabledObject,
  401. /**
  402. * The type of the physics imposter
  403. */
  404. public type: number, private _options: PhysicsImpostorParameters = { mass: 0 }, private _scene?: Scene) {
  405. //sanity check!
  406. if (!this.object) {
  407. Logger.Error("No object was provided. A physics object is obligatory");
  408. return;
  409. }
  410. if (this.object.parent && _options.mass !== 0) {
  411. Logger.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur.");
  412. }
  413. // Legacy support for old syntax.
  414. if (!this._scene && object.getScene) {
  415. this._scene = object.getScene();
  416. }
  417. if (!this._scene) {
  418. return;
  419. }
  420. if (this.type > 100) {
  421. this.soft = true;
  422. }
  423. this._physicsEngine = this._scene.getPhysicsEngine();
  424. if (!this._physicsEngine) {
  425. Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  426. } else {
  427. //set the object's quaternion, if not set
  428. if (!this.object.rotationQuaternion) {
  429. if (this.object.rotation) {
  430. this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  431. } else {
  432. this.object.rotationQuaternion = new Quaternion();
  433. }
  434. }
  435. //default options params
  436. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  437. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  438. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  439. if (this.soft) {
  440. //softbody mass must be above 0;
  441. this._options.mass = this._options.mass > 0 ? this._options.mass : 1;
  442. this._options.pressure = (_options.pressure === void 0) ? 200 : _options.pressure;
  443. this._options.stiffness = (_options.stiffness === void 0) ? 1 : _options.stiffness;
  444. this._options.velocityIterations = (_options.velocityIterations === void 0) ? 20 : _options.velocityIterations;
  445. this._options.positionIterations = (_options.positionIterations === void 0) ? 20 : _options.positionIterations;
  446. this._options.fixedPoints = (_options.fixedPoints === void 0) ? 0 : _options.fixedPoints;
  447. this._options.margin = (_options.margin === void 0) ? 0 : _options.margin;
  448. this._options.damping = (_options.damping === void 0) ? 0 : _options.damping;
  449. this._options.path = (_options.path === void 0) ? null : _options.path;
  450. this._options.shape = (_options.shape === void 0) ? null : _options.shape;
  451. }
  452. this._joints = [];
  453. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  454. if (!this.object.parent || this._options.ignoreParent) {
  455. this._init();
  456. } else if (this.object.parent.physicsImpostor) {
  457. Logger.Warn("You must affect impostors to children before affecting impostor to parent.");
  458. }
  459. }
  460. }
  461. /**
  462. * This function will completly initialize this impostor.
  463. * It will create a new body - but only if this mesh has no parent.
  464. * If it has, this impostor will not be used other than to define the impostor
  465. * of the child mesh.
  466. * @hidden
  467. */
  468. public _init() {
  469. if (!this._physicsEngine) {
  470. return;
  471. }
  472. this._physicsEngine.removeImpostor(this);
  473. this.physicsBody = null;
  474. this._parent = this._parent || this._getPhysicsParent();
  475. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  476. this._physicsEngine.addImpostor(this);
  477. }
  478. }
  479. private _getPhysicsParent(): Nullable<PhysicsImpostor> {
  480. if (this.object.parent instanceof AbstractMesh) {
  481. var parentMesh: AbstractMesh = <AbstractMesh>this.object.parent;
  482. return parentMesh.physicsImpostor;
  483. }
  484. return null;
  485. }
  486. /**
  487. * Should a new body be generated.
  488. * @returns boolean specifying if body initialization is required
  489. */
  490. public isBodyInitRequired(): boolean {
  491. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  492. }
  493. /**
  494. * Sets the updated scaling
  495. * @param updated Specifies if the scaling is updated
  496. */
  497. public setScalingUpdated() {
  498. this.forceUpdate();
  499. }
  500. /**
  501. * Force a regeneration of this or the parent's impostor's body.
  502. * Use under cautious - This will remove all joints already implemented.
  503. */
  504. public forceUpdate() {
  505. this._init();
  506. if (this.parent && !this._options.ignoreParent) {
  507. this.parent.forceUpdate();
  508. }
  509. }
  510. /*public get mesh(): AbstractMesh {
  511. return this._mesh;
  512. }*/
  513. /**
  514. * Gets the body that holds this impostor. Either its own, or its parent.
  515. */
  516. public get physicsBody(): any {
  517. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  518. }
  519. /**
  520. * Get the parent of the physics imposter
  521. * @returns Physics imposter or null
  522. */
  523. public get parent(): Nullable<PhysicsImpostor> {
  524. return !this._options.ignoreParent && this._parent ? this._parent : null;
  525. }
  526. /**
  527. * Sets the parent of the physics imposter
  528. */
  529. public set parent(value: Nullable<PhysicsImpostor>) {
  530. this._parent = value;
  531. }
  532. /**
  533. * Set the physics body. Used mainly by the physics engine/plugin
  534. */
  535. public set physicsBody(physicsBody: any) {
  536. if (this._physicsBody && this._physicsEngine) {
  537. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  538. }
  539. this._physicsBody = physicsBody;
  540. this.resetUpdateFlags();
  541. }
  542. /**
  543. * Resets the update flags
  544. */
  545. public resetUpdateFlags() {
  546. this._bodyUpdateRequired = false;
  547. }
  548. /**
  549. * Gets the object extend size
  550. * @returns the object extend size
  551. */
  552. public getObjectExtendSize(): Vector3 {
  553. if (this.object.getBoundingInfo) {
  554. let q = this.object.rotationQuaternion;
  555. //reset rotation
  556. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  557. //calculate the world matrix with no rotation
  558. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  559. let boundingInfo = this.object.getBoundingInfo();
  560. let size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  561. //bring back the rotation
  562. this.object.rotationQuaternion = q;
  563. //calculate the world matrix with the new rotation
  564. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  565. return size;
  566. } else {
  567. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  568. }
  569. }
  570. /**
  571. * Gets the object center
  572. * @returns The object center
  573. */
  574. public getObjectCenter(): Vector3 {
  575. if (this.object.getBoundingInfo) {
  576. let boundingInfo = this.object.getBoundingInfo();
  577. return boundingInfo.boundingBox.centerWorld;
  578. } else {
  579. return this.object.position;
  580. }
  581. }
  582. /**
  583. * Get a specific parameter from the options parameters
  584. * @param paramName The object parameter name
  585. * @returns The object parameter
  586. */
  587. public getParam(paramName: string): any {
  588. return (<any>this._options)[paramName];
  589. }
  590. /**
  591. * Sets a specific parameter in the options given to the physics plugin
  592. * @param paramName The parameter name
  593. * @param value The value of the parameter
  594. */
  595. public setParam(paramName: string, value: number) {
  596. (<any>this._options)[paramName] = value;
  597. this._bodyUpdateRequired = true;
  598. }
  599. /**
  600. * Specifically change the body's mass option. Won't recreate the physics body object
  601. * @param mass The mass of the physics imposter
  602. */
  603. public setMass(mass: number) {
  604. if (this.getParam("mass") !== mass) {
  605. this.setParam("mass", mass);
  606. }
  607. if (this._physicsEngine) {
  608. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  609. }
  610. }
  611. /**
  612. * Gets the linear velocity
  613. * @returns linear velocity or null
  614. */
  615. public getLinearVelocity(): Nullable<Vector3> {
  616. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero();
  617. }
  618. /**
  619. * Sets the linear velocity
  620. * @param velocity linear velocity or null
  621. */
  622. public setLinearVelocity(velocity: Nullable<Vector3>) {
  623. if (this._physicsEngine) {
  624. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  625. }
  626. }
  627. /**
  628. * Gets the angular velocity
  629. * @returns angular velocity or null
  630. */
  631. public getAngularVelocity(): Nullable<Vector3> {
  632. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero();
  633. }
  634. /**
  635. * Sets the angular velocity
  636. * @param velocity The velocity or null
  637. */
  638. public setAngularVelocity(velocity: Nullable<Vector3>) {
  639. if (this._physicsEngine) {
  640. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  641. }
  642. }
  643. /**
  644. * Execute a function with the physics plugin native code
  645. * Provide a function the will have two variables - the world object and the physics body object
  646. * @param func The function to execute with the physics plugin native code
  647. */
  648. public executeNativeFunction(func: (world: any, physicsBody: any) => void) {
  649. if (this._physicsEngine) {
  650. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  651. }
  652. }
  653. /**
  654. * Register a function that will be executed before the physics world is stepping forward
  655. * @param func The function to execute before the physics world is stepped forward
  656. */
  657. public registerBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  658. this._onBeforePhysicsStepCallbacks.push(func);
  659. }
  660. /**
  661. * Unregister a function that will be executed before the physics world is stepping forward
  662. * @param func The function to execute before the physics world is stepped forward
  663. */
  664. public unregisterBeforePhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  665. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  666. if (index > -1) {
  667. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  668. } else {
  669. Logger.Warn("Function to remove was not found");
  670. }
  671. }
  672. /**
  673. * Register a function that will be executed after the physics step
  674. * @param func The function to execute after physics step
  675. */
  676. public registerAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  677. this._onAfterPhysicsStepCallbacks.push(func);
  678. }
  679. /**
  680. * Unregisters a function that will be executed after the physics step
  681. * @param func The function to execute after physics step
  682. */
  683. public unregisterAfterPhysicsStep(func: (impostor: PhysicsImpostor) => void): void {
  684. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  685. if (index > -1) {
  686. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  687. } else {
  688. Logger.Warn("Function to remove was not found");
  689. }
  690. }
  691. /**
  692. * register a function that will be executed when this impostor collides against a different body
  693. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  694. * @param func Callback that is executed on collision
  695. */
  696. public registerOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor) => void): void {
  697. var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst];
  698. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  699. }
  700. /**
  701. * Unregisters the physics imposter on contact
  702. * @param collideAgainst The physics object to collide against
  703. * @param func Callback to execute on collision
  704. */
  705. public unregisterOnPhysicsCollide(collideAgainst: PhysicsImpostor | Array<PhysicsImpostor>, func: (collider: PhysicsImpostor, collidedAgainst: PhysicsImpostor | Array<PhysicsImpostor>) => void): void {
  706. var collidedAgainstList: Array<PhysicsImpostor> = collideAgainst instanceof Array ? <Array<PhysicsImpostor>>collideAgainst : [<PhysicsImpostor>collideAgainst];
  707. var index = -1;
  708. let found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => {
  709. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  710. // chcek the arrays match
  711. let sameList = cbDef.otherImpostors.every((impostor) => {
  712. return collidedAgainstList.indexOf(impostor) > -1;
  713. });
  714. if (sameList) {
  715. index = idx;
  716. }
  717. return sameList;
  718. }
  719. return false;
  720. });
  721. if (found) {
  722. this._onPhysicsCollideCallbacks.splice(index, 1);
  723. } else {
  724. Logger.Warn("Function to remove was not found");
  725. }
  726. }
  727. //temp variables for parent rotation calculations
  728. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  729. private _tmpQuat: Quaternion = new Quaternion();
  730. private _tmpQuat2: Quaternion = new Quaternion();
  731. /**
  732. * Get the parent rotation
  733. * @returns The parent rotation
  734. */
  735. public getParentsRotation(): Quaternion {
  736. let parent = this.object.parent;
  737. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  738. while (parent) {
  739. if (parent.rotationQuaternion) {
  740. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  741. } else {
  742. Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  743. }
  744. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  745. parent = parent.parent;
  746. }
  747. return this._tmpQuat;
  748. }
  749. /**
  750. * this function is executed by the physics engine.
  751. */
  752. public beforeStep = () => {
  753. if (!this._physicsEngine) {
  754. return;
  755. }
  756. this.object.translate(this._deltaPosition, -1);
  757. this._deltaRotationConjugated && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion);
  758. this.object.computeWorldMatrix(false);
  759. if (this.object.parent && this.object.rotationQuaternion) {
  760. this.getParentsRotation();
  761. this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat);
  762. } else {
  763. this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion());
  764. }
  765. if (!this._options.disableBidirectionalTransformation) {
  766. this.object.rotationQuaternion && this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePosition(), this._tmpQuat);
  767. }
  768. this._onBeforePhysicsStepCallbacks.forEach((func) => {
  769. func(this);
  770. });
  771. }
  772. /**
  773. * this function is executed by the physics engine
  774. */
  775. public afterStep = () => {
  776. if (!this._physicsEngine) {
  777. return;
  778. }
  779. this._onAfterPhysicsStepCallbacks.forEach((func) => {
  780. func(this);
  781. });
  782. this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);
  783. // object has now its world rotation. needs to be converted to local.
  784. if (this.object.parent && this.object.rotationQuaternion) {
  785. this.getParentsRotation();
  786. this._tmpQuat.conjugateInPlace();
  787. this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion);
  788. }
  789. // take the position set and make it the absolute position of this object.
  790. this.object.setAbsolutePosition(this.object.position);
  791. this._deltaRotation && this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);
  792. this.object.translate(this._deltaPosition, 1);
  793. }
  794. /**
  795. * Legacy collision detection event support
  796. */
  797. public onCollideEvent: Nullable<(collider: PhysicsImpostor, collidedWith: PhysicsImpostor) => void> = null;
  798. /**
  799. * event and body object due to cannon's event-based architecture.
  800. */
  801. public onCollide = (e: { body: any }) => {
  802. if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) {
  803. return;
  804. }
  805. if (!this._physicsEngine) {
  806. return;
  807. }
  808. var otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  809. if (otherImpostor) {
  810. // Legacy collision detection event support
  811. if (this.onCollideEvent) {
  812. this.onCollideEvent(this, otherImpostor);
  813. }
  814. this._onPhysicsCollideCallbacks.filter((obj) => {
  815. return obj.otherImpostors.indexOf((<PhysicsImpostor>otherImpostor)) !== -1;
  816. }).forEach((obj) => {
  817. obj.callback(this, <PhysicsImpostor>otherImpostor);
  818. });
  819. }
  820. }
  821. /**
  822. * Apply a force
  823. * @param force The force to apply
  824. * @param contactPoint The contact point for the force
  825. * @returns The physics imposter
  826. */
  827. public applyForce(force: Vector3, contactPoint: Vector3): PhysicsImpostor {
  828. if (this._physicsEngine) {
  829. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  830. }
  831. return this;
  832. }
  833. /**
  834. * Apply an impulse
  835. * @param force The impulse force
  836. * @param contactPoint The contact point for the impulse force
  837. * @returns The physics imposter
  838. */
  839. public applyImpulse(force: Vector3, contactPoint: Vector3): PhysicsImpostor {
  840. if (this._physicsEngine) {
  841. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  842. }
  843. return this;
  844. }
  845. /**
  846. * A help function to create a joint
  847. * @param otherImpostor A physics imposter used to create a joint
  848. * @param jointType The type of joint
  849. * @param jointData The data for the joint
  850. * @returns The physics imposter
  851. */
  852. public createJoint(otherImpostor: PhysicsImpostor, jointType: number, jointData: PhysicsJointData): PhysicsImpostor {
  853. var joint = new PhysicsJoint(jointType, jointData);
  854. this.addJoint(otherImpostor, joint);
  855. return this;
  856. }
  857. /**
  858. * Add a joint to this impostor with a different impostor
  859. * @param otherImpostor A physics imposter used to add a joint
  860. * @param joint The joint to add
  861. * @returns The physics imposter
  862. */
  863. public addJoint(otherImpostor: PhysicsImpostor, joint: PhysicsJoint): PhysicsImpostor {
  864. this._joints.push({
  865. otherImpostor: otherImpostor,
  866. joint: joint
  867. });
  868. if (this._physicsEngine) {
  869. this._physicsEngine.addJoint(this, otherImpostor, joint);
  870. }
  871. return this;
  872. }
  873. /**
  874. * Add an anchor to a cloth impostor
  875. * @param otherImpostor rigid impostor to anchor to
  876. * @param width ratio across width from 0 to 1
  877. * @param height ratio up height from 0 to 1
  878. * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little strech
  879. * @param noCollisionBetweenLinkedBodies when true collisions between cloth impostor and anchor are ignored; default false
  880. * @returns impostor the soft imposter
  881. */
  882. public addAnchor(otherImpostor: PhysicsImpostor, width: number, height: number, influence: number, noCollisionBetweenLinkedBodies: boolean): PhysicsImpostor {
  883. if (!this._physicsEngine) {
  884. return this;
  885. }
  886. const plugin = this._physicsEngine.getPhysicsPlugin();
  887. if (!plugin.appendAnchor) {
  888. return this;
  889. }
  890. if (this._physicsEngine) {
  891. plugin.appendAnchor!(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies);
  892. }
  893. return this;
  894. }
  895. /**
  896. * Add a hook to a rope impostor
  897. * @param otherImpostor rigid impostor to anchor to
  898. * @param length ratio across rope from 0 to 1
  899. * @param influence the elasticity between rope impostor and anchor from 0, very stretchy to 1, little strech
  900. * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false
  901. * @returns impostor the rope imposter
  902. */
  903. public addHook(otherImpostor: PhysicsImpostor, length: number, influence: number, noCollisionBetweenLinkedBodies: boolean): PhysicsImpostor {
  904. if (!this._physicsEngine) {
  905. return this;
  906. }
  907. const plugin = this._physicsEngine.getPhysicsPlugin();
  908. if (!plugin.appendAnchor) {
  909. return this;
  910. }
  911. if (this._physicsEngine) {
  912. plugin.appendHook!(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies);
  913. }
  914. return this;
  915. }
  916. /**
  917. * Will keep this body still, in a sleep mode.
  918. * @returns the physics imposter
  919. */
  920. public sleep(): PhysicsImpostor {
  921. if (this._physicsEngine) {
  922. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  923. }
  924. return this;
  925. }
  926. /**
  927. * Wake the body up.
  928. * @returns The physics imposter
  929. */
  930. public wakeUp(): PhysicsImpostor {
  931. if (this._physicsEngine) {
  932. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  933. }
  934. return this;
  935. }
  936. /**
  937. * Clones the physics imposter
  938. * @param newObject The physics imposter clones to this physics-enabled object
  939. * @returns A nullable physics imposter
  940. */
  941. public clone(newObject: IPhysicsEnabledObject): Nullable<PhysicsImpostor> {
  942. if (!newObject) { return null; }
  943. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  944. }
  945. /**
  946. * Disposes the physics imposter
  947. */
  948. public dispose(/*disposeChildren: boolean = true*/) {
  949. //no dispose if no physics engine is available.
  950. if (!this._physicsEngine) {
  951. return;
  952. }
  953. this._joints.forEach((j) => {
  954. if (this._physicsEngine) {
  955. this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);
  956. }
  957. });
  958. //dispose the physics body
  959. this._physicsEngine.removeImpostor(this);
  960. if (this.parent) {
  961. this.parent.forceUpdate();
  962. } else {
  963. /*this._object.getChildMeshes().forEach(function(mesh) {
  964. if (mesh.physicsImpostor) {
  965. if (disposeChildren) {
  966. mesh.physicsImpostor.dispose();
  967. mesh.physicsImpostor = null;
  968. }
  969. }
  970. })*/
  971. }
  972. this._isDisposed = true;
  973. }
  974. /**
  975. * Sets the delta position
  976. * @param position The delta position amount
  977. */
  978. public setDeltaPosition(position: Vector3) {
  979. this._deltaPosition.copyFrom(position);
  980. }
  981. /**
  982. * Sets the delta rotation
  983. * @param rotation The delta rotation amount
  984. */
  985. public setDeltaRotation(rotation: Quaternion) {
  986. if (!this._deltaRotation) {
  987. this._deltaRotation = new Quaternion();
  988. }
  989. this._deltaRotation.copyFrom(rotation);
  990. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  991. }
  992. /**
  993. * Gets the box size of the physics imposter and stores the result in the input parameter
  994. * @param result Stores the box size
  995. * @returns The physics imposter
  996. */
  997. public getBoxSizeToRef(result: Vector3): PhysicsImpostor {
  998. if (this._physicsEngine) {
  999. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  1000. }
  1001. return this;
  1002. }
  1003. /**
  1004. * Gets the radius of the physics imposter
  1005. * @returns Radius of the physics imposter
  1006. */
  1007. public getRadius(): number {
  1008. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  1009. }
  1010. /**
  1011. * Sync a bone with this impostor
  1012. * @param bone The bone to sync to the impostor.
  1013. * @param boneMesh The mesh that the bone is influencing.
  1014. * @param jointPivot The pivot of the joint / bone in local space.
  1015. * @param distToJoint Optional distance from the impostor to the joint.
  1016. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  1017. */
  1018. public syncBoneWithImpostor(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion) {
  1019. var tempVec = PhysicsImpostor._tmpVecs[0];
  1020. var mesh = <AbstractMesh>this.object;
  1021. if (mesh.rotationQuaternion) {
  1022. if (adjustRotation) {
  1023. var tempQuat = PhysicsImpostor._tmpQuat;
  1024. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  1025. bone.setRotationQuaternion(tempQuat, Space.WORLD, boneMesh);
  1026. } else {
  1027. bone.setRotationQuaternion(mesh.rotationQuaternion, Space.WORLD, boneMesh);
  1028. }
  1029. }
  1030. tempVec.x = 0;
  1031. tempVec.y = 0;
  1032. tempVec.z = 0;
  1033. if (jointPivot) {
  1034. tempVec.x = jointPivot.x;
  1035. tempVec.y = jointPivot.y;
  1036. tempVec.z = jointPivot.z;
  1037. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  1038. if (distToJoint === undefined || distToJoint === null) {
  1039. distToJoint = jointPivot.length();
  1040. }
  1041. tempVec.x *= distToJoint;
  1042. tempVec.y *= distToJoint;
  1043. tempVec.z *= distToJoint;
  1044. }
  1045. if (bone.getParent()) {
  1046. tempVec.addInPlace(mesh.getAbsolutePosition());
  1047. bone.setAbsolutePosition(tempVec, boneMesh);
  1048. } else {
  1049. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  1050. boneMesh.position.x -= tempVec.x;
  1051. boneMesh.position.y -= tempVec.y;
  1052. boneMesh.position.z -= tempVec.z;
  1053. }
  1054. }
  1055. /**
  1056. * Sync impostor to a bone
  1057. * @param bone The bone that the impostor will be synced to.
  1058. * @param boneMesh The mesh that the bone is influencing.
  1059. * @param jointPivot The pivot of the joint / bone in local space.
  1060. * @param distToJoint Optional distance from the impostor to the joint.
  1061. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  1062. * @param boneAxis Optional vector3 axis the bone is aligned with
  1063. */
  1064. public syncImpostorWithBone(bone: Bone, boneMesh: AbstractMesh, jointPivot: Vector3, distToJoint?: number, adjustRotation?: Quaternion, boneAxis?: Vector3) {
  1065. var mesh = <AbstractMesh>this.object;
  1066. if (mesh.rotationQuaternion) {
  1067. if (adjustRotation) {
  1068. var tempQuat = PhysicsImpostor._tmpQuat;
  1069. bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);
  1070. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  1071. } else {
  1072. bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);
  1073. }
  1074. }
  1075. var pos = PhysicsImpostor._tmpVecs[0];
  1076. var boneDir = PhysicsImpostor._tmpVecs[1];
  1077. if (!boneAxis) {
  1078. boneAxis = PhysicsImpostor._tmpVecs[2];
  1079. boneAxis.x = 0;
  1080. boneAxis.y = 1;
  1081. boneAxis.z = 0;
  1082. }
  1083. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  1084. bone.getAbsolutePositionToRef(boneMesh, pos);
  1085. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  1086. distToJoint = jointPivot.length();
  1087. }
  1088. if (distToJoint !== undefined && distToJoint !== null) {
  1089. pos.x += boneDir.x * distToJoint;
  1090. pos.y += boneDir.y * distToJoint;
  1091. pos.z += boneDir.z * distToJoint;
  1092. }
  1093. mesh.setAbsolutePosition(pos);
  1094. }
  1095. //Impostor types
  1096. /**
  1097. * No-Imposter type
  1098. */
  1099. public static NoImpostor = 0;
  1100. /**
  1101. * Sphere-Imposter type
  1102. */
  1103. public static SphereImpostor = 1;
  1104. /**
  1105. * Box-Imposter type
  1106. */
  1107. public static BoxImpostor = 2;
  1108. /**
  1109. * Plane-Imposter type
  1110. */
  1111. public static PlaneImpostor = 3;
  1112. /**
  1113. * Mesh-imposter type
  1114. */
  1115. public static MeshImpostor = 4;
  1116. /**
  1117. * Capsule-Impostor type (Ammo.js plugin only)
  1118. */
  1119. public static CapsuleImpostor = 6;
  1120. /**
  1121. * Cylinder-Imposter type
  1122. */
  1123. public static CylinderImpostor = 7;
  1124. /**
  1125. * Particle-Imposter type
  1126. */
  1127. public static ParticleImpostor = 8;
  1128. /**
  1129. * Heightmap-Imposter type
  1130. */
  1131. public static HeightmapImpostor = 9;
  1132. /**
  1133. * ConvexHull-Impostor type (Ammo.js plugin only)
  1134. */
  1135. public static ConvexHullImpostor = 10;
  1136. /**
  1137. * Custom-Imposter type (Ammo.js plugin only)
  1138. */
  1139. public static CustomImpostor = 100;
  1140. /**
  1141. * Rope-Imposter type
  1142. */
  1143. public static RopeImpostor = 101;
  1144. /**
  1145. * Cloth-Imposter type
  1146. */
  1147. public static ClothImpostor = 102;
  1148. /**
  1149. * Softbody-Imposter type
  1150. */
  1151. public static SoftbodyImpostor = 103;
  1152. }