ModelAnimationCollection.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. import defaultValue from "../../Core/defaultValue.js";
  2. import defined from "../../Core/defined.js";
  3. import DeveloperError from "../../Core/DeveloperError.js";
  4. import Event from "../../Core/Event.js";
  5. import JulianDate from "../../Core/JulianDate.js";
  6. import CesiumMath from "../../Core/Math.js";
  7. import ModelAnimation from "./ModelAnimation.js";
  8. import ModelAnimationLoop from ".././ModelAnimationLoop.js";
  9. import ModelAnimationState from ".././ModelAnimationState.js";
  10. /**
  11. * <div class="notice">
  12. * Access a model's animations {@link Model#activeAnimations}. Do not call the constructor directly
  13. * </div>
  14. *
  15. * A collection of active model animations.
  16. *
  17. * @alias ModelAnimationCollection
  18. * @internalConstructor
  19. * @class
  20. *
  21. * @see Model#activeAnimations
  22. */
  23. function ModelAnimationCollection(model) {
  24. /**
  25. * The event fired when an animation is added to the collection. This can be used, for
  26. * example, to keep a UI in sync.
  27. *
  28. * @type {Event}
  29. * @default new Event()
  30. *
  31. * @example
  32. * model.activeAnimations.animationAdded.addEventListener(function(model, animation) {
  33. * console.log(`Animation added: ${animation.name}`);
  34. * });
  35. */
  36. this.animationAdded = new Event();
  37. /**
  38. * The event fired when an animation is removed from the collection. This can be used, for
  39. * example, to keep a UI in sync.
  40. *
  41. * @type {Event}
  42. * @default new Event()
  43. *
  44. * @example
  45. * model.activeAnimations.animationRemoved.addEventListener(function(model, animation) {
  46. * console.log(`Animation removed: ${animation.name}`);
  47. * });
  48. */
  49. this.animationRemoved = new Event();
  50. /**
  51. * When true, the animation will play even when the scene time is paused. However,
  52. * whether animation takes place will depend on the animationTime functions assigned
  53. * to the model's animations. By default, this is based on scene time, so models using
  54. * the default will not animate regardless of this setting.
  55. *
  56. * @type {boolean}
  57. * @default false
  58. */
  59. this.animateWhilePaused = false;
  60. this._model = model;
  61. this._runtimeAnimations = [];
  62. this._previousTime = undefined;
  63. }
  64. Object.defineProperties(ModelAnimationCollection.prototype, {
  65. /**
  66. * The number of animations in the collection.
  67. *
  68. * @memberof ModelAnimationCollection.prototype
  69. *
  70. * @type {number}
  71. * @readonly
  72. */
  73. length: {
  74. get: function () {
  75. return this._runtimeAnimations.length;
  76. },
  77. },
  78. /**
  79. * The model that owns this animation collection.
  80. *
  81. * @memberof ModelAnimationCollection.prototype
  82. *
  83. * @type {Model}
  84. * @readonly
  85. */
  86. model: {
  87. get: function () {
  88. return this._model;
  89. },
  90. },
  91. });
  92. function addAnimation(collection, animation, options) {
  93. const model = collection._model;
  94. const runtimeAnimation = new ModelAnimation(model, animation, options);
  95. collection._runtimeAnimations.push(runtimeAnimation);
  96. collection.animationAdded.raiseEvent(model, runtimeAnimation);
  97. return runtimeAnimation;
  98. }
  99. /**
  100. * Creates and adds an animation with the specified initial properties to the collection.
  101. * <p>
  102. * This raises the {@link ModelAnimationCollection#animationAdded} event so, for example, a UI can stay in sync.
  103. * </p>
  104. *
  105. * @param {object} options Object with the following properties:
  106. * @param {string} [options.name] The glTF animation name that identifies the animation. Must be defined if <code>options.index</code> is <code>undefined</code>.
  107. * @param {number} [options.index] The glTF animation index that identifies the animation. Must be defined if <code>options.name</code> is <code>undefined</code>.
  108. * @param {JulianDate} [options.startTime] The scene time to start playing the animation. When this is <code>undefined</code>, the animation starts at the next frame.
  109. * @param {number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
  110. * @param {JulianDate} [options.stopTime] The scene time to stop playing the animation. When this is <code>undefined</code>, the animation is played for its full duration.
  111. * @param {boolean} [options.removeOnStop=false] When <code>true</code>, the animation is removed after it stops playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
  112. * @param {number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animation is played relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
  113. * @param {boolean} [options.reverse=false] When <code>true</code>, the animation is played in reverse.
  114. * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animation is looped.
  115. * @param {ModelAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for this animation.
  116. * @returns {ModelAnimation} The animation that was added to the collection.
  117. *
  118. * @exception {DeveloperError} Animations are not loaded. Wait for the {@link Model#ready} to return trues.
  119. * @exception {DeveloperError} options.name must be a valid animation name.
  120. * @exception {DeveloperError} options.index must be a valid animation index.
  121. * @exception {DeveloperError} Either options.name or options.index must be defined.
  122. * @exception {DeveloperError} options.multiplier must be greater than zero.
  123. *
  124. * @example
  125. * // Example 1. Add an animation by name
  126. * model.activeAnimations.add({
  127. * name : 'animation name'
  128. * });
  129. *
  130. * @example
  131. * // Example 2. Add an animation by index
  132. * model.activeAnimations.add({
  133. * index : 0
  134. * });
  135. *
  136. * @example
  137. * // Example 3. Add an animation and provide all properties and events
  138. * const startTime = Cesium.JulianDate.now();
  139. *
  140. * const animation = model.activeAnimations.add({
  141. * name : 'another animation name',
  142. * startTime : startTime,
  143. * delay : 0.0, // Play at startTime (default)
  144. * stopTime : Cesium.JulianDate.addSeconds(startTime, 4.0, new Cesium.JulianDate()),
  145. * removeOnStop : false, // Do not remove when animation stops (default)
  146. * multiplier : 2.0, // Play at double speed
  147. * reverse : true, // Play in reverse
  148. * loop : Cesium.ModelAnimationLoop.REPEAT // Loop the animation
  149. * });
  150. *
  151. * animation.start.addEventListener(function(model, animation) {
  152. * console.log(`Animation started: ${animation.name}`);
  153. * });
  154. * animation.update.addEventListener(function(model, animation, time) {
  155. * console.log(`Animation updated: ${animation.name}. glTF animation time: ${time}`);
  156. * });
  157. * animation.stop.addEventListener(function(model, animation) {
  158. * console.log(`Animation stopped: ${animation.name}`);
  159. * });
  160. */
  161. ModelAnimationCollection.prototype.add = function (options) {
  162. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  163. const model = this._model;
  164. //>>includeStart('debug', pragmas.debug);
  165. if (!model.ready) {
  166. throw new DeveloperError(
  167. "Animations are not loaded. Wait for Model.ready to be true."
  168. );
  169. }
  170. //>>includeEnd('debug');
  171. const animations = model.sceneGraph.components.animations;
  172. //>>includeStart('debug', pragmas.debug);
  173. if (!defined(options.name) && !defined(options.index)) {
  174. throw new DeveloperError(
  175. "Either options.name or options.index must be defined."
  176. );
  177. }
  178. if (defined(options.multiplier) && options.multiplier <= 0.0) {
  179. throw new DeveloperError("options.multiplier must be greater than zero.");
  180. }
  181. if (
  182. defined(options.index) &&
  183. (options.index >= animations.length || options.index < 0)
  184. ) {
  185. throw new DeveloperError("options.index must be a valid animation index.");
  186. }
  187. //>>includeEnd('debug');
  188. let index = options.index;
  189. if (defined(index)) {
  190. return addAnimation(this, animations[index], options);
  191. }
  192. // Find the index of the animation with the given name
  193. const length = animations.length;
  194. for (let i = 0; i < length; ++i) {
  195. if (animations[i].name === options.name) {
  196. index = i;
  197. break;
  198. }
  199. }
  200. //>>includeStart('debug', pragmas.debug);
  201. if (!defined(index)) {
  202. throw new DeveloperError("options.name must be a valid animation name.");
  203. }
  204. //>>includeEnd('debug');
  205. return addAnimation(this, animations[index], options);
  206. };
  207. /**
  208. * Creates and adds animations with the specified initial properties to the collection
  209. * for all animations in the model.
  210. * <p>
  211. * This raises the {@link ModelAnimationCollection#animationAdded} event for each model so, for example, a UI can stay in sync.
  212. * </p>
  213. *
  214. * @param {object} [options] Object with the following properties:
  215. * @param {JulianDate} [options.startTime] The scene time to start playing the animations. When this is <code>undefined</code>, the animations starts at the next frame.
  216. * @param {number} [options.delay=0.0] The delay, in seconds, from <code>startTime</code> to start playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
  217. * @param {JulianDate} [options.stopTime] The scene time to stop playing the animations. When this is <code>undefined</code>, the animations are played for its full duration.
  218. * @param {boolean} [options.removeOnStop=false] When <code>true</code>, the animations are removed after they stop playing. This will only affect the animation if <code>options.loop</code> is ModelAnimationLoop.NONE.
  219. * @param {number} [options.multiplier=1.0] Values greater than <code>1.0</code> increase the speed that the animations play relative to the scene clock speed; values less than <code>1.0</code> decrease the speed.
  220. * @param {boolean} [options.reverse=false] When <code>true</code>, the animations are played in reverse.
  221. * @param {ModelAnimationLoop} [options.loop=ModelAnimationLoop.NONE] Determines if and how the animations are looped.
  222. * @param {ModelAnimation.AnimationTimeCallback} [options.animationTime=undefined] If defined, computes the local animation time for all of the animations.
  223. * @returns {ModelAnimation[]} An array of {@link ModelAnimation} objects, one for each animation added to the collection. If there are no glTF animations, the array is empty.
  224. *
  225. * @exception {DeveloperError} Animations are not loaded. Wait for the {@link Model#readyPromise} to resolve.
  226. * @exception {DeveloperError} options.multiplier must be greater than zero.
  227. *
  228. * @example
  229. * model.activeAnimations.addAll({
  230. * multiplier : 0.5, // Play at half-speed
  231. * loop : Cesium.ModelAnimationLoop.REPEAT // Loop the animations
  232. * });
  233. */
  234. ModelAnimationCollection.prototype.addAll = function (options) {
  235. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  236. const model = this._model;
  237. //>>includeStart('debug', pragmas.debug);
  238. if (!model.ready) {
  239. throw new DeveloperError(
  240. "Animations are not loaded. Wait for Model.ready to be true."
  241. );
  242. }
  243. if (defined(options.multiplier) && options.multiplier <= 0.0) {
  244. throw new DeveloperError("options.multiplier must be greater than zero.");
  245. }
  246. //>>includeEnd('debug');
  247. const animations = model.sceneGraph.components.animations;
  248. const addedAnimations = [];
  249. const length = animations.length;
  250. for (let i = 0; i < length; ++i) {
  251. const animation = addAnimation(this, animations[i], options);
  252. addedAnimations.push(animation);
  253. }
  254. return addedAnimations;
  255. };
  256. /**
  257. * Removes an animation from the collection.
  258. * <p>
  259. * This raises the {@link ModelAnimationCollection#animationRemoved} event so, for example, a UI can stay in sync.
  260. * </p>
  261. * <p>
  262. * An animation can also be implicitly removed from the collection by setting {@link ModelAnimationCollection#removeOnStop} to
  263. * <code>true</code>. The {@link ModelAnimationCollection#animationRemoved} event is still fired when the animation is removed.
  264. * </p>
  265. *
  266. * @param {ModelAnimation} runtimeAnimation The runtime animation to remove.
  267. * @returns {boolean} <code>true</code> if the animation was removed; <code>false</code> if the animation was not found in the collection.
  268. *
  269. * @example
  270. * const a = model.activeAnimations.add({
  271. * name : 'animation name'
  272. * });
  273. * model.activeAnimations.remove(a); // Returns true
  274. */
  275. ModelAnimationCollection.prototype.remove = function (runtimeAnimation) {
  276. if (!defined(runtimeAnimation)) {
  277. return false;
  278. }
  279. const animations = this._runtimeAnimations;
  280. const i = animations.indexOf(runtimeAnimation);
  281. if (i !== -1) {
  282. animations.splice(i, 1);
  283. this.animationRemoved.raiseEvent(this._model, runtimeAnimation);
  284. return true;
  285. }
  286. return false;
  287. };
  288. /**
  289. * Removes all animations from the collection.
  290. * <p>
  291. * This raises the {@link ModelAnimationCollection#animationRemoved} event for each
  292. * animation so, for example, a UI can stay in sync.
  293. * </p>
  294. */
  295. ModelAnimationCollection.prototype.removeAll = function () {
  296. const model = this._model;
  297. const animations = this._runtimeAnimations;
  298. const length = animations.length;
  299. this._runtimeAnimations.length = 0;
  300. for (let i = 0; i < length; ++i) {
  301. this.animationRemoved.raiseEvent(model, animations[i]);
  302. }
  303. };
  304. /**
  305. * Determines whether this collection contains a given animation.
  306. *
  307. * @param {ModelAnimation} runtimeAnimation The runtime animation to check for.
  308. * @returns {boolean} <code>true</code> if this collection contains the animation, <code>false</code> otherwise.
  309. */
  310. ModelAnimationCollection.prototype.contains = function (runtimeAnimation) {
  311. if (defined(runtimeAnimation)) {
  312. return this._runtimeAnimations.indexOf(runtimeAnimation) !== -1;
  313. }
  314. return false;
  315. };
  316. /**
  317. * Returns the animation in the collection at the specified index. Indices are zero-based
  318. * and increase as animations are added. Removing an animation shifts all animations after
  319. * it to the left, changing their indices. This function is commonly used to iterate over
  320. * all the animations in the collection.
  321. *
  322. * @param {number} index The zero-based index of the animation.
  323. * @returns {ModelAnimation} The runtime animation at the specified index.
  324. *
  325. * @example
  326. * // Output the names of all the animations in the collection.
  327. * const animations = model.activeAnimations;
  328. * const length = animations.length;
  329. * for (let i = 0; i < length; ++i) {
  330. * console.log(animations.get(i).name);
  331. * }
  332. */
  333. ModelAnimationCollection.prototype.get = function (index) {
  334. //>>includeStart('debug', pragmas.debug);
  335. if (!defined(index)) {
  336. throw new DeveloperError("index is required.");
  337. }
  338. if (index >= this._runtimeAnimations.length || index < 0) {
  339. throw new DeveloperError(
  340. "index must be valid within the range of the collection"
  341. );
  342. }
  343. //>>includeEnd('debug');
  344. return this._runtimeAnimations[index];
  345. };
  346. const animationsToRemove = [];
  347. function createAnimationRemovedFunction(
  348. modelAnimationCollection,
  349. model,
  350. animation
  351. ) {
  352. return function () {
  353. modelAnimationCollection.animationRemoved.raiseEvent(model, animation);
  354. };
  355. }
  356. /**
  357. * Updates the runtime animations in this collection, removing any animations
  358. * that have stopped.
  359. *
  360. * @param {FrameState} frameState The current frame state.
  361. * @returns {boolean} <code>true</code> if an animation played during this update, <code>false</code> otherwise.
  362. *
  363. * @private
  364. */
  365. ModelAnimationCollection.prototype.update = function (frameState) {
  366. const runtimeAnimations = this._runtimeAnimations;
  367. let length = runtimeAnimations.length;
  368. if (length === 0) {
  369. this._previousTime = undefined;
  370. return false;
  371. }
  372. if (
  373. !this.animateWhilePaused &&
  374. JulianDate.equals(frameState.time, this._previousTime)
  375. ) {
  376. return false;
  377. }
  378. this._previousTime = JulianDate.clone(frameState.time, this._previousTime);
  379. let animationOccurred = false;
  380. const sceneTime = frameState.time;
  381. const model = this._model;
  382. for (let i = 0; i < length; ++i) {
  383. const runtimeAnimation = runtimeAnimations[i];
  384. if (!defined(runtimeAnimation._computedStartTime)) {
  385. runtimeAnimation._computedStartTime = JulianDate.addSeconds(
  386. defaultValue(runtimeAnimation.startTime, sceneTime),
  387. runtimeAnimation.delay,
  388. new JulianDate()
  389. );
  390. }
  391. if (!defined(runtimeAnimation._duration)) {
  392. runtimeAnimation._duration =
  393. runtimeAnimation.localStopTime * (1.0 / runtimeAnimation.multiplier);
  394. }
  395. const startTime = runtimeAnimation._computedStartTime;
  396. const duration = runtimeAnimation._duration;
  397. const stopTime = runtimeAnimation.stopTime;
  398. const pastStartTime = JulianDate.lessThanOrEquals(startTime, sceneTime);
  399. const reachedStopTime =
  400. defined(stopTime) && JulianDate.greaterThan(sceneTime, stopTime);
  401. // [0.0, 1.0] normalized local animation time
  402. let delta = 0.0;
  403. if (duration !== 0.0) {
  404. const seconds = JulianDate.secondsDifference(
  405. reachedStopTime ? stopTime : sceneTime,
  406. startTime
  407. );
  408. delta = defined(runtimeAnimation._animationTime)
  409. ? runtimeAnimation._animationTime(duration, seconds)
  410. : seconds / duration;
  411. }
  412. // Play animation if
  413. // * we are after the start time or the animation is being repeated, and
  414. // * before the end of the animation's duration or the animation is being repeated, and
  415. // * we did not reach a user-provided stop time.
  416. const repeat =
  417. runtimeAnimation.loop === ModelAnimationLoop.REPEAT ||
  418. runtimeAnimation.loop === ModelAnimationLoop.MIRRORED_REPEAT;
  419. const play =
  420. (pastStartTime || (repeat && !defined(runtimeAnimation.startTime))) &&
  421. (delta <= 1.0 || repeat) &&
  422. !reachedStopTime;
  423. if (delta === runtimeAnimation._prevAnimationDelta) {
  424. const animationStopped =
  425. runtimeAnimation._state === ModelAnimationState.STOPPED;
  426. // no change to delta, and no change to the animation state means we can
  427. // skip the update this time around.
  428. if (play !== animationStopped) {
  429. continue;
  430. }
  431. }
  432. runtimeAnimation._prevAnimationDelta = delta;
  433. // If it IS, or WAS, animating...
  434. if (play || runtimeAnimation._state === ModelAnimationState.ANIMATING) {
  435. // ...transition from STOPPED to ANIMATING
  436. if (play && runtimeAnimation._state === ModelAnimationState.STOPPED) {
  437. runtimeAnimation._state = ModelAnimationState.ANIMATING;
  438. if (runtimeAnimation.start.numberOfListeners > 0) {
  439. frameState.afterRender.push(runtimeAnimation._raiseStartEvent);
  440. }
  441. }
  442. // Truncate to [0.0, 1.0] for repeating animations
  443. if (runtimeAnimation.loop === ModelAnimationLoop.REPEAT) {
  444. delta = delta - Math.floor(delta);
  445. } else if (runtimeAnimation.loop === ModelAnimationLoop.MIRRORED_REPEAT) {
  446. const floor = Math.floor(delta);
  447. const fract = delta - floor;
  448. // When odd use (1.0 - fract) to mirror repeat
  449. delta = floor % 2 === 1.0 ? 1.0 - fract : fract;
  450. }
  451. if (runtimeAnimation.reverse) {
  452. delta = 1.0 - delta;
  453. }
  454. let localAnimationTime = delta * duration * runtimeAnimation.multiplier;
  455. // Clamp in case floating-point roundoff goes outside the animation's first or last keyframe
  456. localAnimationTime = CesiumMath.clamp(
  457. localAnimationTime,
  458. runtimeAnimation.localStartTime,
  459. runtimeAnimation.localStopTime
  460. );
  461. runtimeAnimation.animate(localAnimationTime);
  462. if (runtimeAnimation.update.numberOfListeners > 0) {
  463. runtimeAnimation._updateEventTime = localAnimationTime;
  464. frameState.afterRender.push(runtimeAnimation._raiseUpdateEvent);
  465. }
  466. animationOccurred = true;
  467. if (!play) {
  468. // transition from ANIMATING to STOPPED
  469. runtimeAnimation._state = ModelAnimationState.STOPPED;
  470. if (runtimeAnimation.stop.numberOfListeners > 0) {
  471. frameState.afterRender.push(runtimeAnimation._raiseStopEvent);
  472. }
  473. if (runtimeAnimation.removeOnStop) {
  474. animationsToRemove.push(runtimeAnimation);
  475. }
  476. }
  477. }
  478. }
  479. // Remove animations that stopped
  480. length = animationsToRemove.length;
  481. for (let j = 0; j < length; ++j) {
  482. const animationToRemove = animationsToRemove[j];
  483. runtimeAnimations.splice(runtimeAnimations.indexOf(animationToRemove), 1);
  484. frameState.afterRender.push(
  485. createAnimationRemovedFunction(this, model, animationToRemove)
  486. );
  487. }
  488. animationsToRemove.length = 0;
  489. return animationOccurred;
  490. };
  491. export default ModelAnimationCollection;