runtimeAnimation.ts 21 KB

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