runtimeAnimation.ts 22 KB

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