babylon.runtimeAnimation.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. module BABYLON {
  2. export class RuntimeAnimation {
  3. public currentFrame: number = 0;
  4. private _animation: Animation;
  5. private _target: any;
  6. private _originalValue: any;
  7. private _originalBlendValue: any;
  8. private _offsetsCache: {[key: string]: any} = {};
  9. private _highLimitsCache: {[key: string]: any} = {};
  10. private _stopped = false;
  11. private _blendingFactor = 0;
  12. private _scene: Scene;
  13. private _currentValue: any;
  14. private _activeTarget: any;
  15. private _targetPath: string = "";
  16. private _weight = 1.0
  17. /**
  18. * Gets the weight of the runtime animation
  19. */
  20. public get weight(): number {
  21. return this._weight;
  22. }
  23. /**
  24. * Gets the original value of the runtime animation
  25. */
  26. public get originalValue(): any {
  27. return this._originalValue;
  28. }
  29. /**
  30. * Gets the current value of the runtime animation
  31. */
  32. public get currentValue(): any {
  33. return this._currentValue;
  34. }
  35. /**
  36. * Gets the path where to store the animated value in the target
  37. */
  38. public get targetPath(): string {
  39. return this._targetPath;
  40. }
  41. /**
  42. * Gets the actual target of the runtime animation
  43. */
  44. public get target(): any {
  45. return this._activeTarget;
  46. }
  47. /**
  48. * Create a new RuntimeAnimation object
  49. * @param target defines the target of the animation
  50. * @param animation defines the source {BABYLON.Animation} object
  51. * @param scene defines the hosting scene
  52. */
  53. public constructor(target: any, animation: Animation, scene: Scene) {
  54. this._animation = animation;
  55. this._target = target;
  56. this._scene = scene;
  57. animation._runtimeAnimations.push(this);
  58. }
  59. public get animation(): Animation {
  60. return this._animation;
  61. }
  62. public reset(): void {
  63. this._offsetsCache = {};
  64. this._highLimitsCache = {};
  65. this.currentFrame = 0;
  66. this._blendingFactor = 0;
  67. this._originalValue = null;
  68. }
  69. public isStopped(): boolean {
  70. return this._stopped;
  71. }
  72. public dispose(): void {
  73. let index = this._animation.runtimeAnimations.indexOf(this);
  74. if (index > -1) {
  75. this._animation.runtimeAnimations.splice(index, 1);
  76. }
  77. }
  78. private _getKeyValue(value: any): any {
  79. if (typeof value === "function") {
  80. return value();
  81. }
  82. return value;
  83. }
  84. private _interpolate(currentFrame: number, repeatCount: number, loopMode?: number, offsetValue?: any, highLimitValue?: any) {
  85. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  86. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  87. }
  88. this.currentFrame = currentFrame;
  89. let keys = this._animation.getKeys();
  90. // Try to get a hash to find the right key
  91. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  92. if (keys[startKeyIndex].frame >= currentFrame) {
  93. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  94. startKeyIndex--;
  95. }
  96. }
  97. for (var key = startKeyIndex; key < keys.length; key++) {
  98. var endKey = keys[key + 1];
  99. if (endKey.frame >= currentFrame) {
  100. var startKey = keys[key];
  101. var startValue = this._getKeyValue(startKey.value);
  102. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  103. return startValue;
  104. }
  105. var endValue = this._getKeyValue(endKey.value);
  106. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  107. var frameDelta = endKey.frame - startKey.frame;
  108. // gradient : percent of currentFrame between the frame inf and the frame sup
  109. var gradient = (currentFrame - startKey.frame) / frameDelta;
  110. // check for easingFunction and correction of gradient
  111. let easingFunction = this._animation.getEasingFunction();
  112. if (easingFunction != null) {
  113. gradient = easingFunction.ease(gradient);
  114. }
  115. switch (this._animation.dataType) {
  116. // Float
  117. case Animation.ANIMATIONTYPE_FLOAT:
  118. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  119. switch (loopMode) {
  120. case Animation.ANIMATIONLOOPMODE_CYCLE:
  121. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  122. return floatValue;
  123. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  124. return offsetValue * repeatCount + floatValue;
  125. }
  126. break;
  127. // Quaternion
  128. case Animation.ANIMATIONTYPE_QUATERNION:
  129. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  130. switch (loopMode) {
  131. case Animation.ANIMATIONLOOPMODE_CYCLE:
  132. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  133. return quatValue;
  134. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  135. return quatValue.add(offsetValue.scale(repeatCount));
  136. }
  137. return quatValue;
  138. // Vector3
  139. case Animation.ANIMATIONTYPE_VECTOR3:
  140. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  141. switch (loopMode) {
  142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  144. return vec3Value;
  145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  146. return vec3Value.add(offsetValue.scale(repeatCount));
  147. }
  148. // Vector2
  149. case Animation.ANIMATIONTYPE_VECTOR2:
  150. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  151. switch (loopMode) {
  152. case Animation.ANIMATIONLOOPMODE_CYCLE:
  153. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  154. return vec2Value;
  155. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  156. return vec2Value.add(offsetValue.scale(repeatCount));
  157. }
  158. // Size
  159. case Animation.ANIMATIONTYPE_SIZE:
  160. switch (loopMode) {
  161. case Animation.ANIMATIONLOOPMODE_CYCLE:
  162. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  163. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  164. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  165. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  166. }
  167. // Color3
  168. case Animation.ANIMATIONTYPE_COLOR3:
  169. switch (loopMode) {
  170. case Animation.ANIMATIONLOOPMODE_CYCLE:
  171. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  172. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  173. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  174. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  175. }
  176. // Matrix
  177. case Animation.ANIMATIONTYPE_MATRIX:
  178. switch (loopMode) {
  179. case Animation.ANIMATIONLOOPMODE_CYCLE:
  180. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  181. if (Animation.AllowMatricesInterpolation) {
  182. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  183. }
  184. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  185. return startValue;
  186. }
  187. default:
  188. break;
  189. }
  190. break;
  191. }
  192. }
  193. return this._getKeyValue(keys[keys.length - 1].value);
  194. }
  195. /**
  196. * Affect the interpolated value to the target
  197. * @param currentValue defines the value computed by the animation
  198. * @param weight defines the weight to apply to this value
  199. */
  200. public setValue(currentValue: any, weight = 1.0): void {
  201. // Set value
  202. var path: any;
  203. var destination: any;
  204. let targetPropertyPath = this._animation.targetPropertyPath
  205. if (targetPropertyPath.length > 1) {
  206. var property = this._target[targetPropertyPath[0]];
  207. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  208. property = property[targetPropertyPath[index]];
  209. }
  210. path = targetPropertyPath[targetPropertyPath.length - 1];
  211. destination = property;
  212. } else {
  213. path = targetPropertyPath[0];
  214. destination = this._target;
  215. }
  216. this._targetPath = path;
  217. this._activeTarget = destination;
  218. this._weight = weight;
  219. // Blending
  220. let enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  221. let blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  222. if (enableBlending && this._blendingFactor <= 1.0) {
  223. if (!this._originalBlendValue) {
  224. let originalValue = destination[path];
  225. if (originalValue.clone) {
  226. this._originalBlendValue = originalValue.clone();
  227. } else {
  228. this._originalBlendValue = originalValue;
  229. }
  230. }
  231. }
  232. if (weight !== -1.0) {
  233. if (!this._originalValue) {
  234. let originalValue: any;
  235. if (destination.getRestPose) { // For bones
  236. originalValue = destination.getRestPose();
  237. } else {
  238. originalValue = destination[path];
  239. }
  240. if (originalValue.clone) {
  241. this._originalValue = originalValue.clone();
  242. } else {
  243. this._originalValue = originalValue;
  244. }
  245. }
  246. }
  247. if (enableBlending && this._blendingFactor <= 1.0) {
  248. if (this._originalBlendValue.prototype) { // Complex value
  249. if (this._originalBlendValue.prototype.Lerp) { // Lerp supported
  250. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  251. } else { // Blending not supported
  252. this._currentValue = currentValue;
  253. }
  254. } else if (this._originalBlendValue.m) { // Matrix
  255. this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  256. } else { // Direct value
  257. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  258. }
  259. this._blendingFactor += blendingSpeed;
  260. } else {
  261. this._currentValue = currentValue;
  262. }
  263. if (weight !== -1.0) {
  264. this._scene._registerTargetForLateAnimationBinding(this);
  265. } else {
  266. destination[path] = this._currentValue;
  267. }
  268. if (this._target.markAsDirty) {
  269. this._target.markAsDirty(this._animation.targetProperty);
  270. }
  271. }
  272. private _getCorrectLoopMode(): number | undefined {
  273. if ( this._target && this._target.animationPropertiesOverride) {
  274. return this._target.animationPropertiesOverride.loopMode;
  275. }
  276. return this._animation.loopMode;
  277. }
  278. /**
  279. * Move the current animation to a given frame
  280. * @param frame defines the frame to move to
  281. */
  282. public goToFrame(frame: number): void {
  283. let keys = this._animation.getKeys();
  284. if (frame < keys[0].frame) {
  285. frame = keys[0].frame;
  286. } else if (frame > keys[keys.length - 1].frame) {
  287. frame = keys[keys.length - 1].frame;
  288. }
  289. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  290. this.setValue(currentValue, -1);
  291. }
  292. public _prepareForSpeedRatioChange(newSpeedRatio: number): void {
  293. let newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  294. this._ratioOffset = this._previousRatio - newRatio;
  295. }
  296. private _ratioOffset = 0;
  297. private _previousDelay: number = 0;
  298. private _previousRatio: number = 0;
  299. /**
  300. * Execute the current animation
  301. * @param delay defines the delay to add to the current frame
  302. * @param from defines the lower bound of the animation range
  303. * @param to defines the upper bound of the animation range
  304. * @param loop defines if the current animation must loop
  305. * @param speedRatio defines the current speed ratio
  306. * @param weight defines the weight of the animation (default is -1 so no weight)
  307. * @returns a boolean indicating if the animation has ended
  308. */
  309. public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number, weight = -1.0): boolean {
  310. let targetPropertyPath = this._animation.targetPropertyPath
  311. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  312. this._stopped = true;
  313. return false;
  314. }
  315. var returnValue = true;
  316. let keys = this._animation.getKeys();
  317. // Adding a start key at frame 0 if missing
  318. if (keys[0].frame !== 0) {
  319. var newKey = { frame: 0, value: keys[0].value };
  320. keys.splice(0, 0, newKey);
  321. }
  322. // Check limits
  323. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  324. from = keys[0].frame;
  325. }
  326. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  327. to = keys[keys.length - 1].frame;
  328. }
  329. //to and from cannot be the same key
  330. if(from === to) {
  331. if (from > keys[0].frame) {
  332. from--;
  333. } else if (to < keys[keys.length - 1].frame) {
  334. to++;
  335. }
  336. }
  337. // Compute ratio
  338. var range = to - from;
  339. var offsetValue;
  340. // ratio represents the frame delta between from and to
  341. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  342. var highLimitValue = 0;
  343. this._previousDelay = delay;
  344. this._previousRatio = ratio;
  345. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  346. returnValue = false;
  347. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  348. } else {
  349. // Get max value if required
  350. if (this._getCorrectLoopMode() !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  351. var keyOffset = to.toString() + from.toString();
  352. if (!this._offsetsCache[keyOffset]) {
  353. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  354. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  355. switch (this._animation.dataType) {
  356. // Float
  357. case Animation.ANIMATIONTYPE_FLOAT:
  358. this._offsetsCache[keyOffset] = toValue - fromValue;
  359. break;
  360. // Quaternion
  361. case Animation.ANIMATIONTYPE_QUATERNION:
  362. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  363. break;
  364. // Vector3
  365. case Animation.ANIMATIONTYPE_VECTOR3:
  366. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  367. // Vector2
  368. case Animation.ANIMATIONTYPE_VECTOR2:
  369. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  370. // Size
  371. case Animation.ANIMATIONTYPE_SIZE:
  372. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  373. // Color3
  374. case Animation.ANIMATIONTYPE_COLOR3:
  375. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  376. default:
  377. break;
  378. }
  379. this._highLimitsCache[keyOffset] = toValue;
  380. }
  381. highLimitValue = this._highLimitsCache[keyOffset];
  382. offsetValue = this._offsetsCache[keyOffset];
  383. }
  384. }
  385. if (offsetValue === undefined) {
  386. switch (this._animation.dataType) {
  387. // Float
  388. case Animation.ANIMATIONTYPE_FLOAT:
  389. offsetValue = 0;
  390. break;
  391. // Quaternion
  392. case Animation.ANIMATIONTYPE_QUATERNION:
  393. offsetValue = new Quaternion(0, 0, 0, 0);
  394. break;
  395. // Vector3
  396. case Animation.ANIMATIONTYPE_VECTOR3:
  397. offsetValue = Vector3.Zero();
  398. break;
  399. // Vector2
  400. case Animation.ANIMATIONTYPE_VECTOR2:
  401. offsetValue = Vector2.Zero();
  402. break;
  403. // Size
  404. case Animation.ANIMATIONTYPE_SIZE:
  405. offsetValue = Size.Zero();
  406. break;
  407. // Color3
  408. case Animation.ANIMATIONTYPE_COLOR3:
  409. offsetValue = Color3.Black();
  410. }
  411. }
  412. // Compute value
  413. var repeatCount = (ratio / range) >> 0;
  414. var currentFrame = returnValue ? from + ratio % range : to;
  415. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  416. // Set value
  417. this.setValue(currentValue, weight);
  418. // Check events
  419. let events = this._animation.getEvents();
  420. for (var index = 0; index < events.length; index++) {
  421. // Make sure current frame has passed event frame and that event frame is within the current range
  422. // Also, handle both forward and reverse animations
  423. if (
  424. (range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  425. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)
  426. ){
  427. var event = events[index];
  428. if (!event.isDone) {
  429. // If event should be done only once, remove it.
  430. if (event.onlyOnce) {
  431. events.splice(index, 1);
  432. index--;
  433. }
  434. event.isDone = true;
  435. event.action();
  436. } // Don't do anything if the event has already be done.
  437. } else if (events[index].isDone && !events[index].onlyOnce) {
  438. // reset event, the animation is looping
  439. events[index].isDone = false;
  440. }
  441. }
  442. if (!returnValue) {
  443. this._stopped = true;
  444. }
  445. return returnValue;
  446. }
  447. }
  448. }