ModelExperimentalAnimationCollection.js 19 KB

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