runtimeAnimation.ts 22 KB

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