physicsHelper.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. import { Nullable } from "../types";
  2. import { Logger } from "../Misc/logger";
  3. import { Vector3 } from "../Maths/math";
  4. import { AbstractMesh } from "../Meshes/abstractMesh";
  5. import { Mesh } from "../Meshes/mesh";
  6. import { SphereBuilder } from "../Meshes/Builders/sphereBuilder";
  7. import { CylinderBuilder } from "../Meshes/Builders/cylinderBuilder";
  8. import { Ray } from "../Culling/ray";
  9. import { Scene } from "../scene";
  10. import { IPhysicsEngine } from "./IPhysicsEngine";
  11. import { PhysicsEngine } from "./physicsEngine";
  12. import { PhysicsImpostor } from "./physicsImpostor";
  13. /**
  14. * A helper for physics simulations
  15. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  16. */
  17. export class PhysicsHelper {
  18. private _scene: Scene;
  19. private _physicsEngine: Nullable<IPhysicsEngine>;
  20. /**
  21. * Initializes the Physics helper
  22. * @param scene Babylon.js scene
  23. */
  24. constructor(scene: Scene) {
  25. this._scene = scene;
  26. this._physicsEngine = this._scene.getPhysicsEngine();
  27. if (!this._physicsEngine) {
  28. Logger.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  29. return;
  30. }
  31. }
  32. /**
  33. * Applies a radial explosion impulse
  34. * @param origin the origin of the explosion
  35. * @param radiusOrEventOptions the radius or the options of radial explosion
  36. * @param strength the explosion strength
  37. * @param falloff possible options: Constant & Linear. Defaults to Constant
  38. * @returns A physics radial explosion event, or null
  39. */
  40. public applyRadialExplosionImpulse(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsRadialExplosionEvent> {
  41. if (!this._physicsEngine) {
  42. Logger.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  43. return null;
  44. }
  45. var impostors = this._physicsEngine.getImpostors();
  46. if (impostors.length === 0) {
  47. return null;
  48. }
  49. if (typeof radiusOrEventOptions === 'number') {
  50. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  51. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  52. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  53. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  54. }
  55. var event = new PhysicsRadialExplosionEvent(this, this._scene, radiusOrEventOptions);
  56. impostors.forEach((impostor) => {
  57. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin);
  58. if (!impostorForceAndContactPoint) {
  59. return;
  60. }
  61. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  62. });
  63. event.dispose(false);
  64. return event;
  65. }
  66. /**
  67. * Applies a radial explosion force
  68. * @param origin the origin of the explosion
  69. * @param radiusOrEventOptions the radius or the options of radial explosion
  70. * @param strength the explosion strength
  71. * @param falloff possible options: Constant & Linear. Defaults to Constant
  72. * @returns A physics radial explosion event, or null
  73. */
  74. public applyRadialExplosionForce(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsRadialExplosionEvent> {
  75. if (!this._physicsEngine) {
  76. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77. return null;
  78. }
  79. var impostors = this._physicsEngine.getImpostors();
  80. if (impostors.length === 0) {
  81. return null;
  82. }
  83. if (typeof radiusOrEventOptions === 'number') {
  84. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  85. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  86. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  87. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  88. }
  89. var event = new PhysicsRadialExplosionEvent(this, this._scene, radiusOrEventOptions);
  90. impostors.forEach((impostor) => {
  91. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin);
  92. if (!impostorForceAndContactPoint) {
  93. return;
  94. }
  95. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96. });
  97. event.dispose(false);
  98. return event;
  99. }
  100. /**
  101. * Creates a gravitational field
  102. * @param origin the origin of the explosion
  103. * @param radiusOrEventOptions the radius or the options of radial explosion
  104. * @param strength the explosion strength
  105. * @param falloff possible options: Constant & Linear. Defaults to Constant
  106. * @returns A physics gravitational field event, or null
  107. */
  108. public gravitationalField(origin: Vector3, radiusOrEventOptions: number | PhysicsRadialExplosionEventOptions, strength?: number, falloff?: PhysicsRadialImpulseFalloff): Nullable<PhysicsGravitationalFieldEvent> {
  109. if (!this._physicsEngine) {
  110. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  111. return null;
  112. }
  113. var impostors = this._physicsEngine.getImpostors();
  114. if (impostors.length === 0) {
  115. return null;
  116. }
  117. if (typeof radiusOrEventOptions === 'number') {
  118. radiusOrEventOptions = new PhysicsRadialExplosionEventOptions();
  119. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  120. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  121. radiusOrEventOptions.falloff = falloff || radiusOrEventOptions.falloff;
  122. }
  123. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radiusOrEventOptions);
  124. event.dispose(false);
  125. return event;
  126. }
  127. /**
  128. * Creates a physics updraft event
  129. * @param origin the origin of the updraft
  130. * @param radiusOrEventOptions the radius or the options of the updraft
  131. * @param strength the strength of the updraft
  132. * @param height the height of the updraft
  133. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  134. * @returns A physics updraft event, or null
  135. */
  136. public updraft(origin: Vector3, radiusOrEventOptions: number | PhysicsUpdraftEventOptions, strength?: number, height?: number, updraftMode?: PhysicsUpdraftMode): Nullable<PhysicsUpdraftEvent> {
  137. if (!this._physicsEngine) {
  138. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  139. return null;
  140. }
  141. if (this._physicsEngine.getImpostors().length === 0) {
  142. return null;
  143. }
  144. if (typeof radiusOrEventOptions === 'number') {
  145. radiusOrEventOptions = new PhysicsUpdraftEventOptions();
  146. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  147. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  148. radiusOrEventOptions.height = height || radiusOrEventOptions.height;
  149. radiusOrEventOptions.updraftMode = updraftMode || radiusOrEventOptions.updraftMode;
  150. }
  151. var event = new PhysicsUpdraftEvent(this, this._scene, origin, radiusOrEventOptions);
  152. event.dispose(false);
  153. return event;
  154. }
  155. /**
  156. * Creates a physics vortex event
  157. * @param origin the of the vortex
  158. * @param radiusOrEventOptions the radius or the options of the vortex
  159. * @param strength the strength of the vortex
  160. * @param height the height of the vortex
  161. * @returns a Physics vortex event, or null
  162. * A physics vortex event or null
  163. */
  164. public vortex(origin: Vector3, radiusOrEventOptions: number | PhysicsVortexEventOptions, strength?: number, height?: number): Nullable<PhysicsVortexEvent> {
  165. if (!this._physicsEngine) {
  166. Logger.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  167. return null;
  168. }
  169. if (this._physicsEngine.getImpostors().length === 0) {
  170. return null;
  171. }
  172. if (typeof radiusOrEventOptions === 'number') {
  173. radiusOrEventOptions = new PhysicsVortexEventOptions();
  174. radiusOrEventOptions.radius = <number><any>radiusOrEventOptions;
  175. radiusOrEventOptions.strength = strength || radiusOrEventOptions.strength;
  176. radiusOrEventOptions.height = height || radiusOrEventOptions.height;
  177. }
  178. var event = new PhysicsVortexEvent(this, this._scene, origin, radiusOrEventOptions);
  179. event.dispose(false);
  180. return event;
  181. }
  182. }
  183. /**
  184. * Represents a physics radial explosion event
  185. */
  186. class PhysicsRadialExplosionEvent {
  187. private _sphere: Mesh; // create a sphere, so we can get the intersecting meshes inside
  188. private _dataFetched: boolean = false; // check if the data has been fetched. If not, do cleanup
  189. /**
  190. * Initializes a radial explosioin event
  191. * @param _physicsHelper A physics helper
  192. * @param _scene BabylonJS scene
  193. * @param _options The options for the vortex event
  194. */
  195. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _options: PhysicsRadialExplosionEventOptions) {
  196. this._options = {...(new PhysicsRadialExplosionEventOptions()), ...this._options};
  197. }
  198. /**
  199. * Returns the data related to the radial explosion event (sphere).
  200. * @returns The radial explosion event data
  201. */
  202. public getData(): PhysicsRadialExplosionEventData {
  203. this._dataFetched = true;
  204. return {
  205. sphere: this._sphere,
  206. };
  207. }
  208. /**
  209. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  210. * @param impostor A physics imposter
  211. * @param origin the origin of the explosion
  212. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  213. */
  214. public getImpostorForceAndContactPoint(impostor: PhysicsImpostor, origin: Vector3): Nullable<PhysicsForceAndContactPoint> {
  215. if (impostor.mass === 0) {
  216. return null;
  217. }
  218. if (!this._intersectsWithSphere(impostor, origin, this._options.radius)) {
  219. return null;
  220. }
  221. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  222. return null;
  223. }
  224. var impostorObjectCenter = impostor.getObjectCenter();
  225. var direction = impostorObjectCenter.subtract(origin);
  226. var ray = new Ray(origin, direction, this._options.radius);
  227. var hit = ray.intersectsMesh(<AbstractMesh>impostor.object);
  228. var contactPoint = hit.pickedPoint;
  229. if (!contactPoint) {
  230. return null;
  231. }
  232. var distanceFromOrigin = Vector3.Distance(origin, contactPoint);
  233. if (distanceFromOrigin > this._options.radius) {
  234. return null;
  235. }
  236. var multiplier = this._options.falloff === PhysicsRadialImpulseFalloff.Constant
  237. ? this._options.strength
  238. : this._options.strength * (1 - (distanceFromOrigin / this._options.radius));
  239. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  240. return { force: force, contactPoint: contactPoint };
  241. }
  242. /**
  243. * Disposes the sphere.
  244. * @param force Specifies if the sphere should be disposed by force
  245. */
  246. public dispose(force: boolean = true) {
  247. if (force) {
  248. this._sphere.dispose();
  249. } else {
  250. setTimeout(() => {
  251. if (!this._dataFetched) {
  252. this._sphere.dispose();
  253. }
  254. }, 0);
  255. }
  256. }
  257. /*** Helpers ***/
  258. private _prepareSphere(): void {
  259. if (!this._sphere) {
  260. this._sphere = SphereBuilder.CreateSphere("radialExplosionEventSphere", this._options.sphere, this._scene);
  261. this._sphere.isVisible = false;
  262. }
  263. }
  264. private _intersectsWithSphere(impostor: PhysicsImpostor, origin: Vector3, radius: number): boolean {
  265. var impostorObject = <AbstractMesh>impostor.object;
  266. this._prepareSphere();
  267. this._sphere.position = origin;
  268. this._sphere.scaling = new Vector3(radius * 2, radius * 2, radius * 2);
  269. this._sphere._updateBoundingInfo();
  270. this._sphere.computeWorldMatrix(true);
  271. return this._sphere.intersectsMesh(impostorObject, true);
  272. }
  273. }
  274. /**
  275. * Represents a gravitational field event
  276. */
  277. class PhysicsGravitationalFieldEvent {
  278. private _tickCallback: any;
  279. private _sphere: Mesh;
  280. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  281. /**
  282. * Initializes the physics gravitational field event
  283. * @param _physicsHelper A physics helper
  284. * @param _scene BabylonJS scene
  285. * @param _origin The origin position of the gravitational field event
  286. * @param _options The options for the vortex event
  287. */
  288. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsRadialExplosionEventOptions) {
  289. this._options = {...(new PhysicsRadialExplosionEventOptions()), ...this._options};
  290. this._tickCallback = this._tick.bind(this);
  291. this._options.strength = this._options.strength * -1;
  292. }
  293. /**
  294. * Returns the data related to the gravitational field event (sphere).
  295. * @returns A gravitational field event
  296. */
  297. public getData(): PhysicsGravitationalFieldEventData {
  298. this._dataFetched = true;
  299. return {
  300. sphere: this._sphere,
  301. };
  302. }
  303. /**
  304. * Enables the gravitational field.
  305. */
  306. public enable() {
  307. this._tickCallback.call(this);
  308. this._scene.registerBeforeRender(this._tickCallback);
  309. }
  310. /**
  311. * Disables the gravitational field.
  312. */
  313. public disable() {
  314. this._scene.unregisterBeforeRender(this._tickCallback);
  315. }
  316. /**
  317. * Disposes the sphere.
  318. * @param force The force to dispose from the gravitational field event
  319. */
  320. public dispose(force: boolean = true) {
  321. if (force) {
  322. this._sphere.dispose();
  323. } else {
  324. setTimeout(() => {
  325. if (!this._dataFetched) {
  326. this._sphere.dispose();
  327. }
  328. }, 0);
  329. }
  330. }
  331. private _tick() {
  332. // Since the params won't change, we fetch the event only once
  333. if (this._sphere) {
  334. this._physicsHelper.applyRadialExplosionForce(this._origin, this._options);
  335. } else {
  336. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._options);
  337. if (radialExplosionEvent) {
  338. this._sphere = <Mesh>radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  339. }
  340. }
  341. }
  342. }
  343. /**
  344. * Represents a physics updraft event
  345. */
  346. class PhysicsUpdraftEvent {
  347. private _physicsEngine: PhysicsEngine;
  348. private _originTop: Vector3 = Vector3.Zero(); // the most upper part of the cylinder
  349. private _originDirection: Vector3 = Vector3.Zero(); // used if the updraftMode is perpendicular
  350. private _tickCallback: any;
  351. private _cylinder: Mesh;
  352. private _cylinderPosition: Vector3 = Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  353. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  354. /**
  355. * Initializes the physics updraft event
  356. * @param _physicsHelper A physics helper
  357. * @param _scene BabylonJS scene
  358. * @param _origin The origin position of the updraft
  359. * @param _options The options for the updraft event
  360. */
  361. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsUpdraftEventOptions) {
  362. this._physicsEngine = <PhysicsEngine>this._scene.getPhysicsEngine();
  363. this._options = {...(new PhysicsUpdraftEventOptions()), ...this._options};
  364. this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
  365. this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
  366. if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) {
  367. this._originDirection = this._origin.subtract(this._originTop).normalize();
  368. }
  369. this._tickCallback = this._tick.bind(this);
  370. this._prepareCylinder();
  371. }
  372. /**
  373. * Returns the data related to the updraft event (cylinder).
  374. * @returns A physics updraft event
  375. */
  376. public getData(): PhysicsUpdraftEventData {
  377. this._dataFetched = true;
  378. return {
  379. cylinder: this._cylinder,
  380. };
  381. }
  382. /**
  383. * Enables the updraft.
  384. */
  385. public enable() {
  386. this._tickCallback.call(this);
  387. this._scene.registerBeforeRender(this._tickCallback);
  388. }
  389. /**
  390. * Disables the updraft.
  391. */
  392. public disable() {
  393. this._scene.unregisterBeforeRender(this._tickCallback);
  394. }
  395. /**
  396. * Disposes the cylinder.
  397. * @param force Specifies if the updraft should be disposed by force
  398. */
  399. public dispose(force: boolean = true) {
  400. if (!this._cylinder) {
  401. return;
  402. }
  403. if (force) {
  404. this._cylinder.dispose();
  405. } else {
  406. setTimeout(() => {
  407. if (!this._dataFetched) {
  408. this._cylinder.dispose();
  409. }
  410. }, 0);
  411. }
  412. }
  413. private getImpostorForceAndContactPoint(impostor: PhysicsImpostor): Nullable<PhysicsForceAndContactPoint> {
  414. if (impostor.mass === 0) {
  415. return null;
  416. }
  417. if (!this._intersectsWithCylinder(impostor)) {
  418. return null;
  419. }
  420. var impostorObjectCenter = impostor.getObjectCenter();
  421. if (this._options.updraftMode === PhysicsUpdraftMode.Perpendicular) {
  422. var direction = this._originDirection;
  423. } else {
  424. var direction = impostorObjectCenter.subtract(this._originTop);
  425. }
  426. var multiplier = this._options.strength * -1;
  427. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  428. return { force: force, contactPoint: impostorObjectCenter };
  429. }
  430. private _tick() {
  431. this._physicsEngine.getImpostors().forEach((impostor) => {
  432. var impostorForceAndContactPoint = this.getImpostorForceAndContactPoint(impostor);
  433. if (!impostorForceAndContactPoint) {
  434. return;
  435. }
  436. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  437. });
  438. }
  439. /*** Helpers ***/
  440. private _prepareCylinder(): void {
  441. if (!this._cylinder) {
  442. this._cylinder = CylinderBuilder.CreateCylinder("updraftEventCylinder", {
  443. height: this._options.height,
  444. diameter: this._options.radius * 2,
  445. }, this._scene);
  446. this._cylinder.isVisible = false;
  447. }
  448. }
  449. private _intersectsWithCylinder(impostor: PhysicsImpostor): boolean {
  450. var impostorObject = <AbstractMesh>impostor.object;
  451. this._cylinder.position = this._cylinderPosition;
  452. return this._cylinder.intersectsMesh(impostorObject, true);
  453. }
  454. }
  455. /**
  456. * Represents a physics vortex event
  457. */
  458. class PhysicsVortexEvent {
  459. private _physicsEngine: PhysicsEngine;
  460. private _originTop: Vector3 = Vector3.Zero(); // the most upper part of the cylinder
  461. private _tickCallback: any;
  462. private _cylinder: Mesh;
  463. private _cylinderPosition: Vector3 = Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  464. private _dataFetched: boolean = false; // check if the has been fetched the data. If not, do cleanup
  465. /**
  466. * Initializes the physics vortex event
  467. * @param _physicsHelper A physics helper
  468. * @param _scene The BabylonJS scene
  469. * @param _origin The origin position of the vortex
  470. * @param _options The options for the vortex event
  471. */
  472. constructor(private _physicsHelper: PhysicsHelper, private _scene: Scene, private _origin: Vector3, private _options: PhysicsVortexEventOptions) {
  473. this._physicsEngine = <PhysicsEngine>this._scene.getPhysicsEngine();
  474. this._options = {...(new PhysicsVortexEventOptions()), ...this._options};
  475. this._origin.addToRef(new Vector3(0, this._options.height / 2, 0), this._cylinderPosition);
  476. this._origin.addToRef(new Vector3(0, this._options.height, 0), this._originTop);
  477. this._tickCallback = this._tick.bind(this);
  478. this._prepareCylinder();
  479. }
  480. /**
  481. * Returns the data related to the vortex event (cylinder).
  482. * @returns The physics vortex event data
  483. */
  484. public getData(): PhysicsVortexEventData {
  485. this._dataFetched = true;
  486. return {
  487. cylinder: this._cylinder,
  488. };
  489. }
  490. /**
  491. * Enables the vortex.
  492. */
  493. public enable() {
  494. this._tickCallback.call(this);
  495. this._scene.registerBeforeRender(this._tickCallback);
  496. }
  497. /**
  498. * Disables the cortex.
  499. */
  500. public disable() {
  501. this._scene.unregisterBeforeRender(this._tickCallback);
  502. }
  503. /**
  504. * Disposes the sphere.
  505. * @param force
  506. */
  507. public dispose(force: boolean = true) {
  508. if (force) {
  509. this._cylinder.dispose();
  510. } else {
  511. setTimeout(() => {
  512. if (!this._dataFetched) {
  513. this._cylinder.dispose();
  514. }
  515. }, 0);
  516. }
  517. }
  518. private getImpostorForceAndContactPoint(impostor: PhysicsImpostor): Nullable<PhysicsForceAndContactPoint> {
  519. if (impostor.mass === 0) {
  520. return null;
  521. }
  522. if (!this._intersectsWithCylinder(impostor)) {
  523. return null;
  524. }
  525. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  526. return null;
  527. }
  528. var impostorObjectCenter = impostor.getObjectCenter();
  529. var originOnPlane = new Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  530. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  531. var ray = new Ray(originOnPlane, originToImpostorDirection, this._options.radius);
  532. var hit = ray.intersectsMesh(<AbstractMesh>impostor.object);
  533. var contactPoint = hit.pickedPoint;
  534. if (!contactPoint) {
  535. return null;
  536. }
  537. var absoluteDistanceFromOrigin = hit.distance / this._options.radius;
  538. var directionToOrigin = contactPoint.normalize();
  539. if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
  540. directionToOrigin = directionToOrigin.negate();
  541. }
  542. if (absoluteDistanceFromOrigin > this._options.centripetalForceThreshold) {
  543. var forceX = directionToOrigin.x * this._options.centripetalForceMultiplier;
  544. var forceY = directionToOrigin.y * this._options.updraftForceMultiplier;
  545. var forceZ = directionToOrigin.z * this._options.centripetalForceMultiplier;
  546. } else {
  547. var perpendicularDirection = Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  548. var forceX = (perpendicularDirection.x + directionToOrigin.x) * this._options.centrifugalForceMultiplier;
  549. var forceY = this._originTop.y * this._options.updraftForceMultiplier;
  550. var forceZ = (perpendicularDirection.z + directionToOrigin.z) * this._options.centrifugalForceMultiplier;
  551. }
  552. var force = new Vector3(forceX, forceY, forceZ);
  553. force = force.multiplyByFloats(this._options.strength, this._options.strength, this._options.strength);
  554. return { force: force, contactPoint: impostorObjectCenter };
  555. }
  556. private _tick() {
  557. this._physicsEngine.getImpostors().forEach((impostor) => {
  558. var impostorForceAndContactPoint = this.getImpostorForceAndContactPoint(impostor);
  559. if (!impostorForceAndContactPoint) {
  560. return;
  561. }
  562. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  563. });
  564. }
  565. /*** Helpers ***/
  566. private _prepareCylinder(): void {
  567. if (!this._cylinder) {
  568. this._cylinder = CylinderBuilder.CreateCylinder("vortexEventCylinder", {
  569. height: this._options.height,
  570. diameter: this._options.radius * 2,
  571. }, this._scene);
  572. this._cylinder.isVisible = false;
  573. }
  574. }
  575. private _intersectsWithCylinder(impostor: PhysicsImpostor): boolean {
  576. var impostorObject = <AbstractMesh>impostor.object;
  577. this._cylinder.position = this._cylinderPosition;
  578. return this._cylinder.intersectsMesh(impostorObject, true);
  579. }
  580. }
  581. /**
  582. * Options fot the radial explosion event
  583. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  584. */
  585. export class PhysicsRadialExplosionEventOptions {
  586. /**
  587. * The radius of the sphere for the radial explosion.
  588. */
  589. radius: number = 5;
  590. /**
  591. * The strenth of the explosion.
  592. */
  593. strength: number = 10;
  594. /**
  595. * The strenght of the force in correspondence to the distance of the affected object
  596. */
  597. falloff: PhysicsRadialImpulseFalloff = PhysicsRadialImpulseFalloff.Constant;
  598. /**
  599. * Sphere options for the radial explosion.
  600. */
  601. sphere: { segments: number, diameter: number } = { segments: 32, diameter: 1 };
  602. }
  603. /**
  604. * Options fot the updraft event
  605. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  606. */
  607. export class PhysicsUpdraftEventOptions {
  608. /**
  609. * The radius of the cylinder for the vortex
  610. */
  611. radius: number = 5;
  612. /**
  613. * The strenth of the updraft.
  614. */
  615. strength: number = 10;
  616. /**
  617. * The height of the cylinder for the updraft.
  618. */
  619. height: number = 10;
  620. /**
  621. * The mode for the the updraft.
  622. */
  623. updraftMode: PhysicsUpdraftMode = PhysicsUpdraftMode.Center;
  624. }
  625. /**
  626. * Options fot the vortex event
  627. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  628. */
  629. export class PhysicsVortexEventOptions {
  630. /**
  631. * The radius of the cylinder for the vortex
  632. */
  633. radius: number = 5;
  634. /**
  635. * The strenth of the vortex.
  636. */
  637. strength: number = 10;
  638. /**
  639. * The height of the cylinder for the vortex.
  640. */
  641. height: number = 10;
  642. /**
  643. * At which distance, relative to the radius the centripetal forces should kick in? Range: 0-1
  644. */
  645. centripetalForceThreshold: number = 0.7;
  646. /**
  647. * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when below the treshold.
  648. */
  649. centripetalForceMultiplier: number = 5;
  650. /**
  651. * This multiplier determines with how much force the objects will be pushed sideways/around the vortex, when above the treshold.
  652. */
  653. centrifugalForceMultiplier: number = 0.5;
  654. /**
  655. * This multiplier determines with how much force the objects will be pushed upwards, when in the vortex.
  656. */
  657. updraftForceMultiplier: number = 0.02;
  658. }
  659. /**
  660. * The strenght of the force in correspondence to the distance of the affected object
  661. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  662. */
  663. export enum PhysicsRadialImpulseFalloff {
  664. /** Defines that impulse is constant in strength across it's whole radius */
  665. Constant,
  666. /** Defines that impulse gets weaker if it's further from the origin */
  667. Linear
  668. }
  669. /**
  670. * The strength of the force in correspondence to the distance of the affected object
  671. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  672. */
  673. export enum PhysicsUpdraftMode {
  674. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  675. Center,
  676. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  677. Perpendicular
  678. }
  679. /**
  680. * Interface for a physics force and contact point
  681. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  682. */
  683. export interface PhysicsForceAndContactPoint {
  684. /**
  685. * The force applied at the contact point
  686. */
  687. force: Vector3;
  688. /**
  689. * The contact point
  690. */
  691. contactPoint: Vector3;
  692. }
  693. /**
  694. * Interface for radial explosion event data
  695. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  696. */
  697. export interface PhysicsRadialExplosionEventData {
  698. /**
  699. * A sphere used for the radial explosion event
  700. */
  701. sphere: Mesh;
  702. }
  703. /**
  704. * Interface for gravitational field event data
  705. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  706. */
  707. export interface PhysicsGravitationalFieldEventData {
  708. /**
  709. * A sphere mesh used for the gravitational field event
  710. */
  711. sphere: Mesh;
  712. }
  713. /**
  714. * Interface for updraft event data
  715. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  716. */
  717. export interface PhysicsUpdraftEventData {
  718. /**
  719. * A cylinder used for the updraft event
  720. */
  721. cylinder: Mesh;
  722. }
  723. /**
  724. * Interface for vortex event data
  725. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine#further-functionality-of-the-impostor-class
  726. */
  727. export interface PhysicsVortexEventData {
  728. /**
  729. * A cylinder used for the vortex event
  730. */
  731. cylinder: Mesh;
  732. }