runtimeAnimation.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. import { DeepImmutable, Nullable } from "../types";
  2. import { Quaternion, Vector3, Vector2, Size, Color3, Matrix } from "../Maths/math";
  3. import { Animation, _IAnimationState } from "./animation";
  4. import { AnimationEvent } from "./animationEvent";
  5. declare type Animatable = import("./animatable").Animatable;
  6. import { Scene } from "../scene";
  7. import { IAnimationKey } from './animationKey';
  8. // Static values to help the garbage collector
  9. // Quaternion
  10. const _staticOffsetValueQuaternion: DeepImmutable<Quaternion> = Object.freeze(new Quaternion(0, 0, 0, 0));
  11. // Vector3
  12. const _staticOffsetValueVector3: DeepImmutable<Vector3> = Object.freeze(Vector3.Zero());
  13. // Vector2
  14. const _staticOffsetValueVector2: DeepImmutable<Vector2> = Object.freeze(Vector2.Zero());
  15. // Size
  16. const _staticOffsetValueSize: DeepImmutable<Size> = Object.freeze(Size.Zero());
  17. // Color3
  18. const _staticOffsetValueColor3: DeepImmutable<Color3> = Object.freeze(Color3.Black());
  19. /**
  20. * Defines a runtime animation
  21. */
  22. export class RuntimeAnimation {
  23. private _events = new Array<AnimationEvent>();
  24. /**
  25. * The current frame of the runtime animation
  26. */
  27. private _currentFrame: number = 0;
  28. /**
  29. * The animation used by the runtime animation
  30. */
  31. private _animation: Animation;
  32. /**
  33. * The target of the runtime animation
  34. */
  35. private _target: any;
  36. /**
  37. * The initiating animatable
  38. */
  39. private _host: Animatable;
  40. /**
  41. * The original value of the runtime animation
  42. */
  43. private _originalValue = new Array<any>();
  44. /**
  45. * The original blend value of the runtime animation
  46. */
  47. private _originalBlendValue: Nullable<any> = null;
  48. /**
  49. * The offsets cache of the runtime animation
  50. */
  51. private _offsetsCache: { [key: string]: any } = {};
  52. /**
  53. * The high limits cache of the runtime animation
  54. */
  55. private _highLimitsCache: { [key: string]: any } = {};
  56. /**
  57. * Specifies if the runtime animation has been stopped
  58. */
  59. private _stopped = false;
  60. /**
  61. * The blending factor of the runtime animation
  62. */
  63. private _blendingFactor = 0;
  64. /**
  65. * The BabylonJS scene
  66. */
  67. private _scene: Scene;
  68. /**
  69. * The current value of the runtime animation
  70. */
  71. private _currentValue: Nullable<any> = null;
  72. /** @hidden */
  73. public _animationState: _IAnimationState;
  74. /**
  75. * The active target of the runtime animation
  76. */
  77. private _activeTargets: any[];
  78. private _currentActiveTarget: Nullable<any> = null;
  79. private _directTarget: Nullable<any> = null;
  80. /**
  81. * The target path of the runtime animation
  82. */
  83. private _targetPath: string = "";
  84. /**
  85. * The weight of the runtime animation
  86. */
  87. private _weight = 1.0;
  88. /**
  89. * The ratio offset of the runtime animation
  90. */
  91. private _ratioOffset = 0;
  92. /**
  93. * The previous delay of the runtime animation
  94. */
  95. private _previousDelay: number = 0;
  96. /**
  97. * The previous ratio of the runtime animation
  98. */
  99. private _previousRatio: number = 0;
  100. private _enableBlending: boolean;
  101. private _keys: IAnimationKey[];
  102. private _minFrame: number;
  103. private _maxFrame: number;
  104. private _minValue: any;
  105. private _maxValue: any;
  106. private _targetIsArray = false;
  107. /**
  108. * Gets the current frame of the runtime animation
  109. */
  110. public get currentFrame(): number {
  111. return this._currentFrame;
  112. }
  113. /**
  114. * Gets the weight of the runtime animation
  115. */
  116. public get weight(): number {
  117. return this._weight;
  118. }
  119. /**
  120. * Gets the current value of the runtime animation
  121. */
  122. public get currentValue(): any {
  123. return this._currentValue;
  124. }
  125. /**
  126. * Gets the target path of the runtime animation
  127. */
  128. public get targetPath(): string {
  129. return this._targetPath;
  130. }
  131. /**
  132. * Gets the actual target of the runtime animation
  133. */
  134. public get target(): any {
  135. return this._currentActiveTarget;
  136. }
  137. /** @hidden */
  138. public _onLoop: () => void;
  139. /**
  140. * Create a new RuntimeAnimation object
  141. * @param target defines the target of the animation
  142. * @param animation defines the source animation object
  143. * @param scene defines the hosting scene
  144. * @param host defines the initiating Animatable
  145. */
  146. public constructor(target: any, animation: Animation, scene: Scene, host: Animatable) {
  147. this._animation = animation;
  148. this._target = target;
  149. this._scene = scene;
  150. this._host = host;
  151. this._activeTargets = [];
  152. animation._runtimeAnimations.push(this);
  153. // State
  154. this._animationState = {
  155. key: 0,
  156. repeatCount: 0,
  157. loopMode: this._getCorrectLoopMode()
  158. };
  159. if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {
  160. this._animationState.workValue = Matrix.Zero();
  161. }
  162. // Limits
  163. this._keys = this._animation.getKeys();
  164. this._minFrame = this._keys[0].frame;
  165. this._maxFrame = this._keys[this._keys.length - 1].frame;
  166. this._minValue = this._keys[0].value;
  167. this._maxValue = this._keys[this._keys.length - 1].value;
  168. // Add a start key at frame 0 if missing
  169. if (this._minFrame !== 0) {
  170. const newKey = { frame: 0, value: this._minValue };
  171. this._keys.splice(0, 0, newKey);
  172. }
  173. // Check data
  174. if (this._target instanceof Array) {
  175. var index = 0;
  176. for (const target of this._target) {
  177. this._preparePath(target, index);
  178. this._getOriginalValues(index);
  179. index++;
  180. }
  181. this._targetIsArray = true;
  182. }
  183. else {
  184. this._preparePath(this._target);
  185. this._getOriginalValues();
  186. this._targetIsArray = false;
  187. this._directTarget = this._activeTargets[0];
  188. }
  189. // Cloning events locally
  190. var events = animation.getEvents();
  191. if (events && events.length > 0) {
  192. events.forEach((e) => {
  193. this._events.push(e._clone());
  194. });
  195. }
  196. this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  197. }
  198. private _preparePath(target: any, targetIndex = 0) {
  199. let targetPropertyPath = this._animation.targetPropertyPath;
  200. if (targetPropertyPath.length > 1) {
  201. var property = target[targetPropertyPath[0]];
  202. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  203. property = property[targetPropertyPath[index]];
  204. }
  205. this._targetPath = targetPropertyPath[targetPropertyPath.length - 1];
  206. this._activeTargets[targetIndex] = property;
  207. } else {
  208. this._targetPath = targetPropertyPath[0];
  209. this._activeTargets[targetIndex] = target;
  210. }
  211. }
  212. /**
  213. * Gets the animation from the runtime animation
  214. */
  215. public get animation(): Animation {
  216. return this._animation;
  217. }
  218. /**
  219. * Resets the runtime animation to the beginning
  220. * @param restoreOriginal defines whether to restore the target property to the original value
  221. */
  222. public reset(restoreOriginal = false): void {
  223. if (restoreOriginal) {
  224. if (this._target instanceof Array) {
  225. var index = 0;
  226. for (const target of this._target) {
  227. if (this._originalValue[index] !== undefined) {
  228. this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index);
  229. }
  230. index++;
  231. }
  232. }
  233. else {
  234. if (this._originalValue[0] !== undefined) {
  235. this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0);
  236. }
  237. }
  238. }
  239. this._offsetsCache = {};
  240. this._highLimitsCache = {};
  241. this._currentFrame = 0;
  242. this._blendingFactor = 0;
  243. // Events
  244. for (var index = 0; index < this._events.length; index++) {
  245. this._events[index].isDone = false;
  246. }
  247. }
  248. /**
  249. * Specifies if the runtime animation is stopped
  250. * @returns Boolean specifying if the runtime animation is stopped
  251. */
  252. public isStopped(): boolean {
  253. return this._stopped;
  254. }
  255. /**
  256. * Disposes of the runtime animation
  257. */
  258. public dispose(): void {
  259. let index = this._animation.runtimeAnimations.indexOf(this);
  260. if (index > -1) {
  261. this._animation.runtimeAnimations.splice(index, 1);
  262. }
  263. }
  264. /**
  265. * Apply the interpolated value to the target
  266. * @param currentValue defines the value computed by the animation
  267. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  268. */
  269. public setValue(currentValue: any, weight: number) {
  270. if (this._targetIsArray) {
  271. for (var index = 0; index < this._target.length; index++) {
  272. const target = this._target[index];
  273. this._setValue(target, this._activeTargets[index], currentValue, weight, index);
  274. }
  275. return;
  276. }
  277. this._setValue(this._target, this._directTarget, currentValue, weight, 0);
  278. }
  279. private _getOriginalValues(targetIndex = 0) {
  280. let originalValue: any;
  281. let target = this._activeTargets[targetIndex];
  282. if (target.getRestPose && this._targetPath === "_matrix") { // For bones
  283. originalValue = target.getRestPose();
  284. } else {
  285. originalValue = target[this._targetPath];
  286. }
  287. if (originalValue && originalValue.clone) {
  288. this._originalValue[targetIndex] = originalValue.clone();
  289. } else {
  290. this._originalValue[targetIndex] = originalValue;
  291. }
  292. }
  293. private _setValue(target: any, destination: any, currentValue: any, weight: number, targetIndex: number): void {
  294. // Set value
  295. this._currentActiveTarget = destination;
  296. this._weight = weight;
  297. if (this._enableBlending && this._blendingFactor <= 1.0) {
  298. if (!this._originalBlendValue) {
  299. let originalValue = destination[this._targetPath];
  300. if (originalValue.clone) {
  301. this._originalBlendValue = originalValue.clone();
  302. } else {
  303. this._originalBlendValue = originalValue;
  304. }
  305. }
  306. if (this._originalBlendValue.m) { // Matrix
  307. if (Animation.AllowMatrixDecomposeForInterpolation) {
  308. if (this._currentValue) {
  309. Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  310. } else {
  311. this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  312. }
  313. } else {
  314. if (this._currentValue) {
  315. Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  316. } else {
  317. this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  318. }
  319. }
  320. } else {
  321. this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  322. }
  323. const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  324. this._blendingFactor += blendingSpeed;
  325. } else {
  326. this._currentValue = currentValue;
  327. }
  328. if (weight !== -1.0) {
  329. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  330. } else {
  331. destination[this._targetPath] = this._currentValue;
  332. }
  333. if (target.markAsDirty) {
  334. target.markAsDirty(this._animation.targetProperty);
  335. }
  336. }
  337. /**
  338. * Gets the loop pmode of the runtime animation
  339. * @returns Loop Mode
  340. */
  341. private _getCorrectLoopMode(): number | undefined {
  342. if (this._target && this._target.animationPropertiesOverride) {
  343. return this._target.animationPropertiesOverride.loopMode;
  344. }
  345. return this._animation.loopMode;
  346. }
  347. /**
  348. * Move the current animation to a given frame
  349. * @param frame defines the frame to move to
  350. */
  351. public goToFrame(frame: number): void {
  352. let keys = this._animation.getKeys();
  353. if (frame < keys[0].frame) {
  354. frame = keys[0].frame;
  355. } else if (frame > keys[keys.length - 1].frame) {
  356. frame = keys[keys.length - 1].frame;
  357. }
  358. this._currentFrame = frame;
  359. var currentValue = this._animation._interpolate(frame, this._animationState);
  360. this.setValue(currentValue, -1);
  361. }
  362. /**
  363. * @hidden Internal use only
  364. */
  365. public _prepareForSpeedRatioChange(newSpeedRatio: number): void {
  366. let newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  367. this._ratioOffset = this._previousRatio - newRatio;
  368. }
  369. /**
  370. * Execute the current animation
  371. * @param delay defines the delay to add to the current frame
  372. * @param from defines the lower bound of the animation range
  373. * @param to defines the upper bound of the animation range
  374. * @param loop defines if the current animation must loop
  375. * @param speedRatio defines the current speed ratio
  376. * @param weight defines the weight of the animation (default is -1 so no weight)
  377. * @param onLoop optional callback called when animation loops
  378. * @returns a boolean indicating if the animation is running
  379. */
  380. public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number, weight = -1.0): boolean {
  381. let animation = this._animation;
  382. let targetPropertyPath = animation.targetPropertyPath;
  383. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  384. this._stopped = true;
  385. return false;
  386. }
  387. let returnValue = true;
  388. // Check limits
  389. if (from < this._minFrame || from > this._maxFrame) {
  390. from = this._minFrame;
  391. }
  392. if (to < this._minFrame || to > this._maxFrame) {
  393. to = this._maxFrame;
  394. }
  395. const range = to - from;
  396. let offsetValue: any;
  397. // Compute ratio which represents the frame delta between from and to
  398. const ratio = (delay * (animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  399. let highLimitValue = 0;
  400. this._previousDelay = delay;
  401. this._previousRatio = ratio;
  402. if (!loop && (to >= from && ratio >= range)) { // If we are out of range and not looping get back to caller
  403. returnValue = false;
  404. highLimitValue = animation._getKeyValue(this._maxValue);
  405. } else if (!loop && (from > to && ratio <= range)) {
  406. returnValue = false;
  407. highLimitValue = animation._getKeyValue(this._minValue);
  408. } else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  409. var keyOffset = to.toString() + from.toString();
  410. if (!this._offsetsCache[keyOffset]) {
  411. this._animationState.repeatCount = 0;
  412. this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;
  413. var fromValue = animation._interpolate(from, this._animationState);
  414. var toValue = animation._interpolate(to, this._animationState);
  415. this._animationState.loopMode = this._getCorrectLoopMode();
  416. switch (animation.dataType) {
  417. // Float
  418. case Animation.ANIMATIONTYPE_FLOAT:
  419. this._offsetsCache[keyOffset] = toValue - fromValue;
  420. break;
  421. // Quaternion
  422. case Animation.ANIMATIONTYPE_QUATERNION:
  423. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  424. break;
  425. // Vector3
  426. case Animation.ANIMATIONTYPE_VECTOR3:
  427. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  428. // Vector2
  429. case Animation.ANIMATIONTYPE_VECTOR2:
  430. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  431. // Size
  432. case Animation.ANIMATIONTYPE_SIZE:
  433. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  434. // Color3
  435. case Animation.ANIMATIONTYPE_COLOR3:
  436. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  437. default:
  438. break;
  439. }
  440. this._highLimitsCache[keyOffset] = toValue;
  441. }
  442. highLimitValue = this._highLimitsCache[keyOffset];
  443. offsetValue = this._offsetsCache[keyOffset];
  444. }
  445. if (offsetValue === undefined) {
  446. switch (animation.dataType) {
  447. // Float
  448. case Animation.ANIMATIONTYPE_FLOAT:
  449. offsetValue = 0;
  450. break;
  451. // Quaternion
  452. case Animation.ANIMATIONTYPE_QUATERNION:
  453. offsetValue = _staticOffsetValueQuaternion;
  454. break;
  455. // Vector3
  456. case Animation.ANIMATIONTYPE_VECTOR3:
  457. offsetValue = _staticOffsetValueVector3;
  458. break;
  459. // Vector2
  460. case Animation.ANIMATIONTYPE_VECTOR2:
  461. offsetValue = _staticOffsetValueVector2;
  462. break;
  463. // Size
  464. case Animation.ANIMATIONTYPE_SIZE:
  465. offsetValue = _staticOffsetValueSize;
  466. break;
  467. // Color3
  468. case Animation.ANIMATIONTYPE_COLOR3:
  469. offsetValue = _staticOffsetValueColor3;
  470. }
  471. }
  472. // Compute value
  473. let currentFrame: number;
  474. if (this._host && this._host.syncRoot) {
  475. const syncRoot = this._host.syncRoot;
  476. const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  477. currentFrame = from + (to - from) * hostNormalizedFrame;
  478. } else {
  479. currentFrame = (returnValue && range !== 0) ? from + ratio % range : to;
  480. }
  481. // Reset events if looping
  482. const events = this._events;
  483. if (range > 0 && this.currentFrame > currentFrame ||
  484. range < 0 && this.currentFrame < currentFrame) {
  485. this._onLoop();
  486. // Need to reset animation events
  487. if (events.length) {
  488. for (var index = 0; index < events.length; index++) {
  489. if (!events[index].onlyOnce) {
  490. // reset event, the animation is looping
  491. events[index].isDone = false;
  492. }
  493. }
  494. }
  495. }
  496. this._currentFrame = currentFrame;
  497. this._animationState.repeatCount = range === 0 ? 0 : (ratio / range) >> 0;
  498. this._animationState.highLimitValue = highLimitValue;
  499. this._animationState.offsetValue = offsetValue;
  500. const currentValue = animation._interpolate(currentFrame, this._animationState);
  501. // Set value
  502. this.setValue(currentValue, weight);
  503. // Check events
  504. if (events.length) {
  505. for (var index = 0; index < events.length; index++) {
  506. // Make sure current frame has passed event frame and that event frame is within the current range
  507. // Also, handle both forward and reverse animations
  508. if (
  509. (range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  510. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)
  511. ) {
  512. var event = events[index];
  513. if (!event.isDone) {
  514. // If event should be done only once, remove it.
  515. if (event.onlyOnce) {
  516. events.splice(index, 1);
  517. index--;
  518. }
  519. event.isDone = true;
  520. event.action(currentFrame);
  521. } // Don't do anything if the event has already be done.
  522. }
  523. }
  524. }
  525. if (!returnValue) {
  526. this._stopped = true;
  527. }
  528. return returnValue;
  529. }
  530. }