viewerModel.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. import { IDisposable } from "babylonjs/scene";
  2. import { ISceneLoaderPlugin, ISceneLoaderPluginAsync } from "babylonjs/Loading/sceneLoader";
  3. import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";
  4. import { IParticleSystem } from "babylonjs/Particles/IParticleSystem";
  5. import { Skeleton } from "babylonjs/Bones/skeleton";
  6. import { Observable } from "babylonjs/Misc/observable";
  7. import { SceneLoaderProgressEvent } from "babylonjs/Loading/sceneLoader";
  8. import { AnimationGroup } from "babylonjs/Animations/animationGroup";
  9. import { Animation, Animatable, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase } from "babylonjs/Animations/index";
  10. import { Nullable } from "babylonjs/types";
  11. import { Quaternion, Vector3 } from "babylonjs/Maths/math";
  12. import { Tags } from "babylonjs/Misc/tags";
  13. import { Material } from "babylonjs/Materials/material";
  14. import { PBRMaterial } from "babylonjs/Materials/PBR/pbrMaterial";
  15. import { MultiMaterial } from "babylonjs/Materials/multiMaterial";
  16. import { Tools } from "babylonjs/Misc/tools";
  17. import { GLTFFileLoader } from "babylonjs-loaders/glTF/index";
  18. import { IAsset } from "babylonjs-gltf2interface";
  19. import { IModelConfiguration } from "../configuration/interfaces/modelConfiguration";
  20. import { IModelAnimationConfiguration } from "../configuration/interfaces/modelAnimationConfiguration";
  21. import { IModelAnimation, GroupModelAnimation, AnimationPlayMode, ModelAnimationConfiguration, EasingFunction, AnimationState } from "./modelAnimation";
  22. import { deepmerge, extendClassWithConfig } from '../helper/';
  23. import { ObservablesManager } from "../managers/observablesManager";
  24. import { ConfigurationContainer } from "../configuration/configurationContainer";
  25. /**
  26. * The current state of the model
  27. */
  28. export enum ModelState {
  29. INIT,
  30. LOADING,
  31. LOADED,
  32. ENTRY,
  33. ENTRYDONE,
  34. COMPLETE,
  35. CANCELED,
  36. ERROR
  37. }
  38. /**
  39. * The viewer model is a container for all assets representing a sngle loaded model.
  40. */
  41. export class ViewerModel implements IDisposable {
  42. /**
  43. * The loader used to load this model.
  44. */
  45. public loader: ISceneLoaderPlugin | ISceneLoaderPluginAsync;
  46. private _animations: Array<IModelAnimation>;
  47. /**
  48. * the list of meshes that are a part of this model
  49. */
  50. private _meshes: Array<AbstractMesh> = [];
  51. /**
  52. * This model's root mesh (the parent of all other meshes).
  53. * This mesh does not(!) exist in the meshes array.
  54. */
  55. public rootMesh: AbstractMesh;
  56. private _pivotMesh: AbstractMesh;
  57. /**
  58. * ParticleSystems connected to this model
  59. */
  60. public particleSystems: Array<IParticleSystem> = [];
  61. /**
  62. * Skeletons defined in this model
  63. */
  64. public skeletons: Array<Skeleton> = [];
  65. /**
  66. * The current model animation.
  67. * On init, this will be undefined.
  68. */
  69. public currentAnimation: IModelAnimation;
  70. /**
  71. * Observers registered here will be executed when the model is done loading
  72. */
  73. public onLoadedObservable: Observable<ViewerModel>;
  74. /**
  75. * Observers registered here will be executed when the loader notified of a progress event
  76. */
  77. public onLoadProgressObservable: Observable<SceneLoaderProgressEvent>;
  78. /**
  79. * Observers registered here will be executed when the loader notified of an error.
  80. */
  81. public onLoadErrorObservable: Observable<{ message: string; exception: any }>;
  82. /**
  83. * Will be executed after the model finished loading and complete, including entry animation and lod
  84. */
  85. public onCompleteObservable: Observable<ViewerModel>;
  86. /**
  87. * Observers registered here will be executed every time the model is being configured.
  88. * This can be used to extend the model's configuration without extending the class itself
  89. */
  90. public onAfterConfigure: Observable<ViewerModel>;
  91. /**
  92. * The current model state (loaded, error, etc)
  93. */
  94. public state: ModelState;
  95. /**
  96. * A loadID provided by the modelLoader, unique to ths (Abstract)Viewer instance.
  97. */
  98. public loadId: number;
  99. public loadInfo: IAsset;
  100. private _loadedUrl: string;
  101. private _modelConfiguration: IModelConfiguration;
  102. private _loaderDone: boolean = false;
  103. private _entryAnimation: ModelAnimationConfiguration;
  104. private _exitAnimation: ModelAnimationConfiguration;
  105. private _scaleTransition: Animation;
  106. private _animatables: Array<Animatable> = [];
  107. private _frameRate: number = 60;
  108. private _shadowsRenderedAfterLoad: boolean = false;
  109. constructor(private _observablesManager: ObservablesManager, modelConfiguration: IModelConfiguration, private _configurationContainer?: ConfigurationContainer) {
  110. this.onLoadedObservable = new Observable();
  111. this.onLoadErrorObservable = new Observable();
  112. this.onLoadProgressObservable = new Observable();
  113. this.onCompleteObservable = new Observable();
  114. this.onAfterConfigure = new Observable();
  115. this.state = ModelState.INIT;
  116. let scene = this._configurationContainer && this._configurationContainer.scene;
  117. this.rootMesh = new AbstractMesh("modelRootMesh", scene);
  118. this._pivotMesh = new AbstractMesh("pivotMesh", scene);
  119. this._pivotMesh.parent = this.rootMesh;
  120. // rotate 180, gltf fun
  121. this._pivotMesh.rotation.y += Math.PI;
  122. this._scaleTransition = new Animation("scaleAnimation", "scaling", this._frameRate, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
  123. this._animations = [];
  124. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  125. this._modelConfiguration = deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  126. if (this._observablesManager) { this._observablesManager.onModelAddedObservable.notifyObservers(this); }
  127. if (this._modelConfiguration.entryAnimation) {
  128. this.rootMesh.setEnabled(false);
  129. }
  130. this.onLoadedObservable.add(() => {
  131. this.updateConfiguration(this._modelConfiguration);
  132. if (this._observablesManager) { this._observablesManager.onModelLoadedObservable.notifyObservers(this); }
  133. this._initAnimations();
  134. });
  135. this.onCompleteObservable.add(() => {
  136. this.state = ModelState.COMPLETE;
  137. });
  138. }
  139. public get shadowsRenderedAfterLoad() {
  140. return this._shadowsRenderedAfterLoad;
  141. }
  142. public set shadowsRenderedAfterLoad(rendered: boolean) {
  143. if (!rendered) {
  144. throw new Error("can only be enabled");
  145. } else {
  146. this._shadowsRenderedAfterLoad = rendered;
  147. }
  148. }
  149. public getViewerId() {
  150. return this._configurationContainer && this._configurationContainer.viewerId;
  151. }
  152. /**
  153. * Is this model enabled?
  154. */
  155. public get enabled() {
  156. return this.rootMesh.isEnabled();
  157. }
  158. /**
  159. * Set whether this model is enabled or not.
  160. */
  161. public set enabled(enable: boolean) {
  162. this.rootMesh.setEnabled(enable);
  163. }
  164. public set loaderDone(done: boolean) {
  165. this._loaderDone = done;
  166. this._checkCompleteState();
  167. }
  168. private _checkCompleteState() {
  169. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  170. this._modelComplete();
  171. }
  172. }
  173. /**
  174. * Add a mesh to this model.
  175. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  176. *
  177. * @param mesh the new mesh to add
  178. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  179. */
  180. public addMesh(mesh: AbstractMesh, triggerLoaded?: boolean) {
  181. if (!mesh.parent) {
  182. mesh.parent = this._pivotMesh;
  183. }
  184. if (mesh.getClassName() !== "InstancedMesh") {
  185. mesh.receiveShadows = !!this.configuration.receiveShadows;
  186. }
  187. this._meshes.push(mesh);
  188. if (triggerLoaded) {
  189. return this.onLoadedObservable.notifyObserversWithPromise(this);
  190. }
  191. }
  192. /**
  193. * get the list of meshes (excluding the root mesh)
  194. */
  195. public get meshes() {
  196. return this._meshes;
  197. }
  198. /**
  199. * Get the model's configuration
  200. */
  201. public get configuration(): IModelConfiguration {
  202. return this._modelConfiguration;
  203. }
  204. /**
  205. * (Re-)set the model's entire configuration
  206. * @param newConfiguration the new configuration to replace the new one
  207. */
  208. public set configuration(newConfiguration: IModelConfiguration) {
  209. this._modelConfiguration = newConfiguration;
  210. this._configureModel();
  211. }
  212. /**
  213. * Update the current configuration with new values.
  214. * Configuration will not be overwritten, but merged with the new configuration.
  215. * Priority is to the new configuration
  216. * @param newConfiguration the configuration to be merged into the current configuration;
  217. */
  218. public updateConfiguration(newConfiguration: Partial<IModelConfiguration>) {
  219. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  220. this._configureModel();
  221. }
  222. private _initAnimations() {
  223. // check if this is not a gltf loader and init the animations
  224. if (this.skeletons.length) {
  225. this.skeletons.forEach((skeleton, idx) => {
  226. let ag = new AnimationGroup("animation-" + idx, this._configurationContainer && this._configurationContainer.scene);
  227. let add = false;
  228. skeleton.getAnimatables().forEach((a) => {
  229. if (a.animations[0]) {
  230. ag.addTargetedAnimation(a.animations[0], a);
  231. add = true;
  232. }
  233. });
  234. if (add) {
  235. this.addAnimationGroup(ag);
  236. }
  237. });
  238. }
  239. let completeCallback = () => {
  240. };
  241. if (this._modelConfiguration.animation) {
  242. if (this._modelConfiguration.animation.playOnce) {
  243. this._animations.forEach((a) => {
  244. a.playMode = AnimationPlayMode.ONCE;
  245. });
  246. }
  247. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  248. let animationName = this._modelConfiguration.animation.autoStart === true ?
  249. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  250. completeCallback = () => {
  251. this.playAnimation(animationName);
  252. };
  253. }
  254. }
  255. this._enterScene(completeCallback);
  256. }
  257. /**
  258. * Animates the model from the current position to the default position
  259. * @param completeCallback A function to call when the animation has completed
  260. */
  261. private _enterScene(completeCallback?: () => void): void {
  262. const scene = this.rootMesh.getScene();
  263. let previousValue = scene.animationPropertiesOverride!.enableBlending;
  264. let callback = () => {
  265. this.state = ModelState.ENTRYDONE;
  266. scene.animationPropertiesOverride!.enableBlending = previousValue;
  267. this._checkCompleteState();
  268. if (completeCallback) { completeCallback(); }
  269. };
  270. if (!this._entryAnimation) {
  271. callback();
  272. return;
  273. }
  274. this.rootMesh.setEnabled(true);
  275. // disable blending for the sake of the entry animation;
  276. scene.animationPropertiesOverride!.enableBlending = false;
  277. this._applyAnimation(this._entryAnimation, true, callback);
  278. }
  279. /**
  280. * Animates the model from the current position to the exit-screen position
  281. * @param completeCallback A function to call when the animation has completed
  282. */
  283. private _exitScene(completeCallback: () => void): void {
  284. if (!this._exitAnimation) {
  285. completeCallback();
  286. return;
  287. }
  288. this._applyAnimation(this._exitAnimation, false, completeCallback);
  289. }
  290. private _modelComplete() {
  291. //reapply material defines to be sure:
  292. let meshes = this._pivotMesh.getChildMeshes(false);
  293. meshes.filter((m) => m.material).forEach((mesh) => {
  294. this._applyModelMaterialConfiguration(mesh.material!);
  295. });
  296. this.state = ModelState.COMPLETE;
  297. this.onCompleteObservable.notifyObservers(this);
  298. }
  299. /**
  300. * Add a new animation group to this model.
  301. * @param animationGroup the new animation group to be added
  302. */
  303. public addAnimationGroup(animationGroup: AnimationGroup) {
  304. this._animations.push(new GroupModelAnimation(animationGroup));
  305. }
  306. /**
  307. * Get the ModelAnimation array
  308. */
  309. public getAnimations(): Array<IModelAnimation> {
  310. return this._animations;
  311. }
  312. /**
  313. * Get the animations' names. Using the names you can play a specific animation.
  314. */
  315. public getAnimationNames(): Array<string> {
  316. return this._animations.map((a) => a.name);
  317. }
  318. /**
  319. * Get an animation by the provided name. Used mainly when playing n animation.
  320. * @param name the name of the animation to find
  321. */
  322. protected _getAnimationByName(name: string): Nullable<IModelAnimation> {
  323. // can't use .find, noe available on IE
  324. let filtered = this._animations.filter((a) => a.name === name.trim());
  325. // what the next line means - if two animations have the same name, they will not be returned!
  326. if (filtered.length === 1) {
  327. return filtered[0];
  328. } else {
  329. return null;
  330. }
  331. }
  332. /**
  333. * Choose an initialized animation using its name and start playing it
  334. * @param name the name of the animation to play
  335. * @returns The model aniamtion to be played.
  336. */
  337. public playAnimation(name: string): IModelAnimation {
  338. let animation = this.setCurrentAnimationByName(name);
  339. if (animation) {
  340. animation.start();
  341. }
  342. return animation;
  343. }
  344. public setCurrentAnimationByName(name: string) {
  345. let animation = this._getAnimationByName(name.trim());
  346. if (animation) {
  347. if (this.currentAnimation && this.currentAnimation.state !== AnimationState.STOPPED) {
  348. this.currentAnimation.stop();
  349. }
  350. this.currentAnimation = animation;
  351. return animation;
  352. } else {
  353. throw new Error("animation not found - " + name);
  354. }
  355. }
  356. private _configureModel() {
  357. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  358. let meshesWithNoParent: Array<AbstractMesh> = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  359. let updateMeshesWithNoParent = (variable: string, value: any, param?: string) => {
  360. meshesWithNoParent.forEach((mesh) => {
  361. if (param) {
  362. mesh[variable][param] = value;
  363. } else {
  364. mesh[variable] = value;
  365. }
  366. });
  367. };
  368. let updateXYZ = (variable: string, configValues: { x: number, y: number, z: number, w?: number }) => {
  369. if (configValues.x !== undefined) {
  370. updateMeshesWithNoParent(variable, configValues.x, 'x');
  371. }
  372. if (configValues.y !== undefined) {
  373. updateMeshesWithNoParent(variable, configValues.y, 'y');
  374. }
  375. if (configValues.z !== undefined) {
  376. updateMeshesWithNoParent(variable, configValues.z, 'z');
  377. }
  378. if (configValues.w !== undefined) {
  379. updateMeshesWithNoParent(variable, configValues.w, 'w');
  380. }
  381. };
  382. if (this._modelConfiguration.normalize) {
  383. let center = false;
  384. let unitSize = false;
  385. let parentIndex;
  386. if (this._modelConfiguration.normalize === true) {
  387. center = true;
  388. unitSize = true;
  389. } else {
  390. center = !!this._modelConfiguration.normalize.center;
  391. unitSize = !!this._modelConfiguration.normalize.unitSize;
  392. parentIndex = this._modelConfiguration.normalize.parentIndex;
  393. }
  394. let meshesToNormalize: Array<AbstractMesh> = [];
  395. if (parentIndex !== undefined) {
  396. meshesToNormalize.push(this._meshes[parentIndex]);
  397. } else {
  398. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  399. }
  400. if (unitSize) {
  401. meshesToNormalize.forEach((mesh) => {
  402. mesh.normalizeToUnitCube(true);
  403. mesh.computeWorldMatrix(true);
  404. });
  405. }
  406. if (center) {
  407. meshesToNormalize.forEach((mesh) => {
  408. const boundingInfo = mesh.getHierarchyBoundingVectors(true);
  409. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  410. const halfSizeVec = sizeVec.scale(0.5);
  411. const center = boundingInfo.min.add(halfSizeVec);
  412. mesh.position = center.scale(-1);
  413. mesh.position.y += halfSizeVec.y;
  414. // Recompute Info.
  415. mesh.computeWorldMatrix(true);
  416. });
  417. }
  418. } else {
  419. // if centered, should be done here
  420. }
  421. // position?
  422. if (this._modelConfiguration.position) {
  423. updateXYZ('position', this._modelConfiguration.position);
  424. }
  425. if (this._modelConfiguration.rotation) {
  426. //quaternion?
  427. if (this._modelConfiguration.rotation.w) {
  428. meshesWithNoParent.forEach((mesh) => {
  429. if (!mesh.rotationQuaternion) {
  430. mesh.rotationQuaternion = new Quaternion();
  431. }
  432. });
  433. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  434. } else {
  435. updateXYZ('rotation', this._modelConfiguration.rotation);
  436. }
  437. }
  438. if (this._modelConfiguration.rotationOffsetAxis) {
  439. let rotationAxis = new Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis as Vector3);
  440. meshesWithNoParent.forEach((m) => {
  441. if (this._modelConfiguration.rotationOffsetAngle) {
  442. m.rotate(rotationAxis, this._modelConfiguration.rotationOffsetAngle);
  443. }
  444. });
  445. }
  446. if (this._modelConfiguration.scaling) {
  447. updateXYZ('scaling', this._modelConfiguration.scaling);
  448. }
  449. if (this._modelConfiguration.castShadow) {
  450. this._meshes.forEach((mesh) => {
  451. Tags.AddTagsTo(mesh, 'castShadow');
  452. });
  453. }
  454. let meshes = this._pivotMesh.getChildMeshes(false);
  455. meshes.filter((m) => m.material).forEach((mesh) => {
  456. this._applyModelMaterialConfiguration(mesh.material!);
  457. });
  458. if (this._modelConfiguration.entryAnimation) {
  459. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  460. }
  461. if (this._modelConfiguration.exitAnimation) {
  462. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  463. }
  464. this.onAfterConfigure.notifyObservers(this);
  465. }
  466. private _modelAnimationConfigurationToObject(animConfig: IModelAnimationConfiguration): ModelAnimationConfiguration {
  467. let anim: ModelAnimationConfiguration = {
  468. time: 0.5
  469. };
  470. if (animConfig.scaling) {
  471. anim.scaling = Vector3.Zero();
  472. }
  473. if (animConfig.easingFunction !== undefined) {
  474. anim.easingFunction = animConfig.easingFunction;
  475. }
  476. if (animConfig.easingMode !== undefined) {
  477. anim.easingMode = animConfig.easingMode;
  478. }
  479. extendClassWithConfig(anim, animConfig);
  480. return anim;
  481. }
  482. /**
  483. * Apply a material configuration to a material
  484. * @param material Material to apply configuration to
  485. * @hidden
  486. */
  487. public _applyModelMaterialConfiguration(material: Material) {
  488. if (!this._modelConfiguration.material) { return; }
  489. extendClassWithConfig(material, this._modelConfiguration.material);
  490. if (material instanceof PBRMaterial) {
  491. if (this._modelConfiguration.material.directIntensity !== undefined) {
  492. material.directIntensity = this._modelConfiguration.material.directIntensity;
  493. }
  494. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  495. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  496. }
  497. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  498. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  499. }
  500. if (this._modelConfiguration.material.directEnabled !== undefined) {
  501. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  502. }
  503. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  504. material.reflectionColor = this._configurationContainer.reflectionColor.clone();
  505. }
  506. }
  507. else if (material instanceof MultiMaterial) {
  508. for (let i = 0; i < material.subMaterials.length; i++) {
  509. const subMaterial = material.subMaterials[i];
  510. if (subMaterial) {
  511. this._applyModelMaterialConfiguration(subMaterial);
  512. }
  513. }
  514. }
  515. }
  516. /**
  517. * Start entry/exit animation given an animation configuration
  518. * @param animationConfiguration Entry/Exit animation configuration
  519. * @param isEntry Pass true if the animation is an entry animation
  520. * @param completeCallback Callback to execute when the animation completes
  521. */
  522. private _applyAnimation(animationConfiguration: ModelAnimationConfiguration, isEntry: boolean, completeCallback?: () => void) {
  523. let animations: Animation[] = [];
  524. //scale
  525. if (animationConfiguration.scaling) {
  526. let scaleStart: Vector3 = isEntry ? animationConfiguration.scaling : new Vector3(1, 1, 1);
  527. let scaleEnd: Vector3 = isEntry ? new Vector3(1, 1, 1) : animationConfiguration.scaling;
  528. if (!scaleStart.equals(scaleEnd)) {
  529. this.rootMesh.scaling = scaleStart;
  530. this._setLinearKeys(
  531. this._scaleTransition,
  532. this.rootMesh.scaling,
  533. scaleEnd,
  534. animationConfiguration.time
  535. );
  536. animations.push(this._scaleTransition);
  537. }
  538. }
  539. //Start the animation(s)
  540. this.transitionTo(
  541. animations,
  542. animationConfiguration.time,
  543. this._createEasingFunction(animationConfiguration.easingFunction),
  544. animationConfiguration.easingMode,
  545. () => { if (completeCallback) { completeCallback(); } }
  546. );
  547. }
  548. /**
  549. * Begin @animations with the specified @easingFunction
  550. * @param animations The BABYLON Animations to begin
  551. * @param duration of transition, in seconds
  552. * @param easingFunction An easing function to apply
  553. * @param easingMode A easing mode to apply to the easingFunction
  554. * @param onAnimationEnd Call back trigger at the end of the animation.
  555. */
  556. public transitionTo(
  557. animations: Animation[],
  558. duration: number,
  559. easingFunction: any,
  560. easingMode: number = 2, // BABYLON.EasingFunction.EASINGMODE_EASEINOUT,
  561. onAnimationEnd: () => void): void {
  562. if (easingFunction) {
  563. for (let animation of animations) {
  564. easingFunction.setEasingMode(easingMode);
  565. animation.setEasingFunction(easingFunction);
  566. }
  567. }
  568. //Stop any current animations before starting the new one - merging not yet supported.
  569. this.stopAllAnimations();
  570. this.rootMesh.animations = animations;
  571. if (this.rootMesh.getScene().beginAnimation) {
  572. let animatable: Animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, () => {
  573. if (onAnimationEnd) {
  574. onAnimationEnd();
  575. }
  576. });
  577. this._animatables.push(animatable);
  578. }
  579. }
  580. /**
  581. * Sets key values on an Animation from first to last frame.
  582. * @param animation The Babylon animation object to set keys on
  583. * @param startValue The value of the first key
  584. * @param endValue The value of the last key
  585. * @param duration The duration of the animation, used to determine the end frame
  586. */
  587. private _setLinearKeys(animation: Animation, startValue: any, endValue: any, duration: number) {
  588. animation.setKeys([
  589. {
  590. frame: 0,
  591. value: startValue
  592. },
  593. {
  594. frame: this._frameRate * duration,
  595. value: endValue
  596. }
  597. ]);
  598. }
  599. /**
  600. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  601. * @param easingFunctionID The enum of the easing funtion to create
  602. * @return The newly created Babylon easing function object
  603. */
  604. private _createEasingFunction(easingFunctionID?: number): any {
  605. let easingFunction;
  606. switch (easingFunctionID) {
  607. case EasingFunction.CircleEase:
  608. easingFunction = new CircleEase();
  609. break;
  610. case EasingFunction.BackEase:
  611. easingFunction = new BackEase(0.3);
  612. break;
  613. case EasingFunction.BounceEase:
  614. easingFunction = new BounceEase();
  615. break;
  616. case EasingFunction.CubicEase:
  617. easingFunction = new CubicEase();
  618. break;
  619. case EasingFunction.ElasticEase:
  620. easingFunction = new ElasticEase();
  621. break;
  622. case EasingFunction.ExponentialEase:
  623. easingFunction = new ExponentialEase();
  624. break;
  625. case EasingFunction.PowerEase:
  626. easingFunction = new PowerEase();
  627. break;
  628. case EasingFunction.QuadraticEase:
  629. easingFunction = new QuadraticEase();
  630. break;
  631. case EasingFunction.QuarticEase:
  632. easingFunction = new QuarticEase();
  633. break;
  634. case EasingFunction.QuinticEase:
  635. easingFunction = new QuinticEase();
  636. break;
  637. case EasingFunction.SineEase:
  638. easingFunction = new SineEase();
  639. break;
  640. default:
  641. Tools.Log("No ease function found");
  642. break;
  643. }
  644. return easingFunction;
  645. }
  646. /**
  647. * Stops and removes all animations that have been applied to the model
  648. */
  649. public stopAllAnimations(): void {
  650. if (this.rootMesh) {
  651. this.rootMesh.animations = [];
  652. }
  653. if (this.currentAnimation) {
  654. this.currentAnimation.stop();
  655. }
  656. while (this._animatables.length) {
  657. this._animatables[0].onAnimationEnd = null;
  658. this._animatables[0].stop();
  659. this._animatables.shift();
  660. }
  661. }
  662. /**
  663. * Will remove this model from the viewer (but NOT dispose it).
  664. */
  665. public remove() {
  666. this.stopAllAnimations();
  667. // hide it
  668. this.rootMesh.isVisible = false;
  669. if (this._observablesManager) { this._observablesManager.onModelRemovedObservable.notifyObservers(this); }
  670. }
  671. /**
  672. * Dispose this model, including all of its associated assets.
  673. */
  674. public dispose() {
  675. this.remove();
  676. this.onAfterConfigure.clear();
  677. this.onLoadedObservable.clear();
  678. this.onLoadErrorObservable.clear();
  679. this.onLoadProgressObservable.clear();
  680. if (this.loader && this.loader.name === "gltf") {
  681. (<GLTFFileLoader>this.loader).dispose();
  682. }
  683. this.particleSystems.forEach((ps) => ps.dispose());
  684. this.particleSystems.length = 0;
  685. this.skeletons.forEach((s) => s.dispose());
  686. this.skeletons.length = 0;
  687. this._animations.forEach((ag) => ag.dispose());
  688. this._animations.length = 0;
  689. this.rootMesh.dispose(false, true);
  690. }
  691. }