babylon.animation.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. module BABYLON {
  2. export class AnimationRange {
  3. constructor(public name: string, public from: number, public to: number) {
  4. }
  5. public clone(): AnimationRange {
  6. return new AnimationRange(this.name, this.from, this.to);
  7. }
  8. }
  9. /**
  10. * Composed of a frame, and an action function
  11. */
  12. export class AnimationEvent {
  13. public isDone: boolean = false;
  14. constructor(public frame: number, public action: () => void, public onlyOnce?: boolean) {
  15. }
  16. }
  17. export class PathCursor {
  18. private _onchange = new Array<(cursor: PathCursor) => void>();
  19. value: number = 0;
  20. animations = new Array<Animation>();
  21. constructor(private path: Path2) {
  22. }
  23. public getPoint(): Vector3 {
  24. var point = this.path.getPointAtLengthPosition(this.value);
  25. return new Vector3(point.x, 0, point.y);
  26. }
  27. public moveAhead(step: number = 0.002): PathCursor {
  28. this.move(step);
  29. return this;
  30. }
  31. public moveBack(step: number = 0.002): PathCursor {
  32. this.move(-step);
  33. return this;
  34. }
  35. public move(step: number): PathCursor {
  36. if (Math.abs(step) > 1) {
  37. throw "step size should be less than 1.";
  38. }
  39. this.value += step;
  40. this.ensureLimits();
  41. this.raiseOnChange();
  42. return this;
  43. }
  44. private ensureLimits(): PathCursor {
  45. while (this.value > 1) {
  46. this.value -= 1;
  47. }
  48. while (this.value < 0) {
  49. this.value += 1;
  50. }
  51. return this;
  52. }
  53. // used by animation engine
  54. private raiseOnChange(): PathCursor {
  55. this._onchange.forEach(f => f(this));
  56. return this;
  57. }
  58. public onchange(f: (cursor: PathCursor) => void): PathCursor {
  59. this._onchange.push(f);
  60. return this;
  61. }
  62. }
  63. export class Animation {
  64. public static AllowMatricesInterpolation = false;
  65. private _keys: Array<{ frame: number, value: any, inTangent?: any, outTangent?: any }>;
  66. private _easingFunction: IEasingFunction;
  67. public _runtimeAnimations = new Array<RuntimeAnimation>();
  68. // The set of event that will be linked to this animation
  69. private _events = new Array<AnimationEvent>();
  70. public targetPropertyPath: string[];
  71. public blendingSpeed = 0.01;
  72. private _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  73. static _PrepareAnimation(name: string, targetProperty: string, framePerSecond: number, totalFrame: number,
  74. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction): Nullable<Animation> {
  75. var dataType = undefined;
  76. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  77. dataType = Animation.ANIMATIONTYPE_FLOAT;
  78. } else if (from instanceof Quaternion) {
  79. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  80. } else if (from instanceof Vector3) {
  81. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  82. } else if (from instanceof Vector2) {
  83. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  84. } else if (from instanceof Color3) {
  85. dataType = Animation.ANIMATIONTYPE_COLOR3;
  86. } else if (from instanceof Size) {
  87. dataType = Animation.ANIMATIONTYPE_SIZE;
  88. }
  89. if (dataType == undefined) {
  90. return null;
  91. }
  92. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  93. var keys: Array<{ frame: number, value: any }> = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  94. animation.setKeys(keys);
  95. if (easingFunction !== undefined) {
  96. animation.setEasingFunction(easingFunction);
  97. }
  98. return animation;
  99. }
  100. /**
  101. * Sets up an animation.
  102. * @param property the property to animate
  103. * @param animationType the animation type to apply
  104. * @param easingFunction the easing function used in the animation
  105. * @returns The created animation
  106. */
  107. public static CreateAnimation(property: string, animationType: number, framePerSecond: number, easingFunction: EasingFunction): Animation {
  108. var animation: Animation = new Animation(property + "Animation",
  109. property,
  110. framePerSecond,
  111. animationType,
  112. Animation.ANIMATIONLOOPMODE_CONSTANT);
  113. animation.setEasingFunction(easingFunction);
  114. return animation;
  115. }
  116. public static CreateAndStartAnimation(name: string, node: Node, targetProperty: string,
  117. framePerSecond: number, totalFrame: number,
  118. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Nullable<Animatable> {
  119. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  120. if (!animation) {
  121. return null;
  122. }
  123. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  124. }
  125. public static CreateMergeAndStartAnimation(name: string, node: Node, targetProperty: string,
  126. framePerSecond: number, totalFrame: number,
  127. from: any, to: any, loopMode?: number, easingFunction?: EasingFunction, onAnimationEnd?: () => void): Nullable<Animatable> {
  128. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  129. if (!animation) {
  130. return null;
  131. }
  132. node.animations.push(animation);
  133. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  134. }
  135. /**
  136. * Transition property of the Camera to the target Value.
  137. * @param property The property to transition
  138. * @param targetValue The target Value of the property
  139. * @param host The object where the property to animate belongs
  140. * @param scene Scene used to run the animation
  141. * @param frameRate Framerate (in frame/s) to use
  142. * @param transition The transition type we want to use
  143. * @param duration The duration of the animation, in milliseconds
  144. * @param onAnimationEnd Call back trigger at the end of the animation.
  145. */
  146. public static TransitionTo(property: string, targetValue: any, host: any, scene: Scene, frameRate: number, transition: Animation, duration: number, onAnimationEnd: Nullable<() => void> = null): Nullable<Animatable> {
  147. if (duration <= 0) {
  148. host[property] = targetValue;
  149. if (onAnimationEnd) {
  150. onAnimationEnd();
  151. }
  152. return null;
  153. }
  154. var endFrame: number = frameRate * (duration / 1000);
  155. transition.setKeys([{
  156. frame: 0,
  157. value: host[property].clone ? host[property].clone() : host[property]
  158. },
  159. {
  160. frame: endFrame,
  161. value: targetValue
  162. }]);
  163. if (!host.animations) {
  164. host.animations = [];
  165. }
  166. host.animations.push(transition);
  167. var animation: Animatable = scene.beginAnimation(host, 0, endFrame, false);
  168. animation.onAnimationEnd = onAnimationEnd;
  169. return animation;
  170. }
  171. /**
  172. * Return the array of runtime animations currently using this animation
  173. */
  174. public get runtimeAnimations(): RuntimeAnimation[] {
  175. return this._runtimeAnimations;
  176. }
  177. public get hasRunningRuntimeAnimations(): boolean {
  178. for (var runtimeAnimation of this._runtimeAnimations) {
  179. if (!runtimeAnimation.isStopped) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. }
  185. constructor(public name: string, public targetProperty: string, public framePerSecond: number, public dataType: number, public loopMode?: number, public enableBlending?: boolean) {
  186. this.targetPropertyPath = targetProperty.split(".");
  187. this.dataType = dataType;
  188. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  189. }
  190. // Methods
  191. /**
  192. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  193. */
  194. public toString(fullDetails?: boolean): string {
  195. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  196. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  197. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  198. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  199. if (fullDetails) {
  200. ret += ", Ranges: {";
  201. var first = true;
  202. for (var name in this._ranges) {
  203. if (first) {
  204. ret += ", ";
  205. first = false;
  206. }
  207. ret += name;
  208. }
  209. ret += "}";
  210. }
  211. return ret;
  212. }
  213. /**
  214. * Add an event to this animation.
  215. */
  216. public addEvent(event: AnimationEvent): void {
  217. this._events.push(event);
  218. }
  219. /**
  220. * Remove all events found at the given frame
  221. * @param frame
  222. */
  223. public removeEvents(frame: number): void {
  224. for (var index = 0; index < this._events.length; index++) {
  225. if (this._events[index].frame === frame) {
  226. this._events.splice(index, 1);
  227. index--;
  228. }
  229. }
  230. }
  231. public getEvents(): AnimationEvent[] {
  232. return this._events;
  233. }
  234. public createRange(name: string, from: number, to: number): void {
  235. // check name not already in use; could happen for bones after serialized
  236. if (!this._ranges[name]) {
  237. this._ranges[name] = new AnimationRange(name, from, to);
  238. }
  239. }
  240. public deleteRange(name: string, deleteFrames = true): void {
  241. let range = this._ranges[name];
  242. if (!range) {
  243. return;
  244. }
  245. if (deleteFrames) {
  246. var from = range.from;
  247. var to = range.to;
  248. // this loop MUST go high to low for multiple splices to work
  249. for (var key = this._keys.length - 1; key >= 0; key--) {
  250. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  251. this._keys.splice(key, 1);
  252. }
  253. }
  254. }
  255. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  256. }
  257. public getRange(name: string): Nullable<AnimationRange> {
  258. return this._ranges[name];
  259. }
  260. public getKeys(): Array<{ frame: number, value: any, inTangent?: any, outTangent?: any }> {
  261. return this._keys;
  262. }
  263. public getHighestFrame(): number {
  264. var ret = 0;
  265. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  266. if (ret < this._keys[key].frame) {
  267. ret = this._keys[key].frame;
  268. }
  269. }
  270. return ret;
  271. }
  272. public getEasingFunction() {
  273. return this._easingFunction;
  274. }
  275. public setEasingFunction(easingFunction: EasingFunction) {
  276. this._easingFunction = easingFunction;
  277. }
  278. public floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number {
  279. return Scalar.Lerp(startValue, endValue, gradient);
  280. }
  281. public floatInterpolateFunctionWithTangents(startValue: number, outTangent: number, endValue: number, inTangent: number, gradient: number): number {
  282. return Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  283. }
  284. public quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion {
  285. return Quaternion.Slerp(startValue, endValue, gradient);
  286. }
  287. public quaternionInterpolateFunctionWithTangents(startValue: Quaternion, outTangent: Quaternion, endValue: Quaternion, inTangent: Quaternion, gradient: number): Quaternion {
  288. return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  289. }
  290. public vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 {
  291. return Vector3.Lerp(startValue, endValue, gradient);
  292. }
  293. public vector3InterpolateFunctionWithTangents(startValue: Vector3, outTangent: Vector3, endValue: Vector3, inTangent: Vector3, gradient: number): Vector3 {
  294. return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  295. }
  296. public vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 {
  297. return Vector2.Lerp(startValue, endValue, gradient);
  298. }
  299. public vector2InterpolateFunctionWithTangents(startValue: Vector2, outTangent: Vector2, endValue: Vector2, inTangent: Vector2, gradient: number): Vector2 {
  300. return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  301. }
  302. public sizeInterpolateFunction(startValue: Size, endValue: Size, gradient: number): Size {
  303. return Size.Lerp(startValue, endValue, gradient);
  304. }
  305. public color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3 {
  306. return Color3.Lerp(startValue, endValue, gradient);
  307. }
  308. public matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
  309. return Matrix.Lerp(startValue, endValue, gradient);
  310. }
  311. public clone(): Animation {
  312. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  313. clone.enableBlending = this.enableBlending;
  314. clone.blendingSpeed = this.blendingSpeed;
  315. if (this._keys) {
  316. clone.setKeys(this._keys);
  317. }
  318. if (this._ranges) {
  319. clone._ranges = {};
  320. for (var name in this._ranges) {
  321. let range = this._ranges[name];
  322. if (!range) {
  323. continue;
  324. }
  325. clone._ranges[name] = range.clone();
  326. }
  327. }
  328. return clone;
  329. }
  330. public setKeys(values: Array<{ frame: number, value: any }>): void {
  331. this._keys = values.slice(0);
  332. }
  333. public serialize(): any {
  334. var serializationObject: any = {};
  335. serializationObject.name = this.name;
  336. serializationObject.property = this.targetProperty;
  337. serializationObject.framePerSecond = this.framePerSecond;
  338. serializationObject.dataType = this.dataType;
  339. serializationObject.loopBehavior = this.loopMode;
  340. serializationObject.enableBlending = this.enableBlending;
  341. serializationObject.blendingSpeed = this.blendingSpeed;
  342. var dataType = this.dataType;
  343. serializationObject.keys = [];
  344. var keys = this.getKeys();
  345. for (var index = 0; index < keys.length; index++) {
  346. var animationKey = keys[index];
  347. var key: any = {};
  348. key.frame = animationKey.frame;
  349. switch (dataType) {
  350. case Animation.ANIMATIONTYPE_FLOAT:
  351. key.values = [animationKey.value];
  352. break;
  353. case Animation.ANIMATIONTYPE_QUATERNION:
  354. case Animation.ANIMATIONTYPE_MATRIX:
  355. case Animation.ANIMATIONTYPE_VECTOR3:
  356. case Animation.ANIMATIONTYPE_COLOR3:
  357. key.values = animationKey.value.asArray();
  358. break;
  359. }
  360. serializationObject.keys.push(key);
  361. }
  362. serializationObject.ranges = [];
  363. for (var name in this._ranges) {
  364. let source = this._ranges[name];
  365. if (!source) {
  366. continue;
  367. }
  368. var range: any = {};
  369. range.name = name;
  370. range.from = source.from;
  371. range.to = source.to;
  372. serializationObject.ranges.push(range);
  373. }
  374. return serializationObject;
  375. }
  376. // Statics
  377. private static _ANIMATIONTYPE_FLOAT = 0;
  378. private static _ANIMATIONTYPE_VECTOR3 = 1;
  379. private static _ANIMATIONTYPE_QUATERNION = 2;
  380. private static _ANIMATIONTYPE_MATRIX = 3;
  381. private static _ANIMATIONTYPE_COLOR3 = 4;
  382. private static _ANIMATIONTYPE_VECTOR2 = 5;
  383. private static _ANIMATIONTYPE_SIZE = 6;
  384. private static _ANIMATIONLOOPMODE_RELATIVE = 0;
  385. private static _ANIMATIONLOOPMODE_CYCLE = 1;
  386. private static _ANIMATIONLOOPMODE_CONSTANT = 2;
  387. public static get ANIMATIONTYPE_FLOAT(): number {
  388. return Animation._ANIMATIONTYPE_FLOAT;
  389. }
  390. public static get ANIMATIONTYPE_VECTOR3(): number {
  391. return Animation._ANIMATIONTYPE_VECTOR3;
  392. }
  393. public static get ANIMATIONTYPE_VECTOR2(): number {
  394. return Animation._ANIMATIONTYPE_VECTOR2;
  395. }
  396. public static get ANIMATIONTYPE_SIZE(): number {
  397. return Animation._ANIMATIONTYPE_SIZE;
  398. }
  399. public static get ANIMATIONTYPE_QUATERNION(): number {
  400. return Animation._ANIMATIONTYPE_QUATERNION;
  401. }
  402. public static get ANIMATIONTYPE_MATRIX(): number {
  403. return Animation._ANIMATIONTYPE_MATRIX;
  404. }
  405. public static get ANIMATIONTYPE_COLOR3(): number {
  406. return Animation._ANIMATIONTYPE_COLOR3;
  407. }
  408. public static get ANIMATIONLOOPMODE_RELATIVE(): number {
  409. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  410. }
  411. public static get ANIMATIONLOOPMODE_CYCLE(): number {
  412. return Animation._ANIMATIONLOOPMODE_CYCLE;
  413. }
  414. public static get ANIMATIONLOOPMODE_CONSTANT(): number {
  415. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  416. }
  417. public static Parse(parsedAnimation: any): Animation {
  418. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  419. var dataType = parsedAnimation.dataType;
  420. var keys: Array<{ frame: number, value: any, inTangent: any, outTangent: any }> = [];
  421. var data;
  422. var index: number;
  423. if (parsedAnimation.enableBlending) {
  424. animation.enableBlending = parsedAnimation.enableBlending;
  425. }
  426. if (parsedAnimation.blendingSpeed) {
  427. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  428. }
  429. for (index = 0; index < parsedAnimation.keys.length; index++) {
  430. var key = parsedAnimation.keys[index];
  431. var inTangent: any;
  432. var outTangent: any;
  433. switch (dataType) {
  434. case Animation.ANIMATIONTYPE_FLOAT:
  435. data = key.values[0];
  436. if (key.values.length >= 1) {
  437. inTangent = key.values[1];
  438. }
  439. if (key.values.length >= 2) {
  440. outTangent = key.values[2];
  441. }
  442. break;
  443. case Animation.ANIMATIONTYPE_QUATERNION:
  444. data = Quaternion.FromArray(key.values);
  445. if (key.values.length >= 8) {
  446. var _inTangent = Quaternion.FromArray(key.values.slice(4, 8));
  447. if (!_inTangent.equals(Quaternion.Zero())) {
  448. inTangent = _inTangent;
  449. }
  450. }
  451. if (key.values.length >= 12) {
  452. var _outTangent = Quaternion.FromArray(key.values.slice(8, 12));
  453. if (!_outTangent.equals(Quaternion.Zero())) {
  454. outTangent = _outTangent;
  455. }
  456. }
  457. break;
  458. case Animation.ANIMATIONTYPE_MATRIX:
  459. data = Matrix.FromArray(key.values);
  460. break;
  461. case Animation.ANIMATIONTYPE_COLOR3:
  462. data = Color3.FromArray(key.values);
  463. break;
  464. case Animation.ANIMATIONTYPE_VECTOR3:
  465. default:
  466. data = Vector3.FromArray(key.values);
  467. break;
  468. }
  469. var keyData: any = {};
  470. keyData.frame = key.frame;
  471. keyData.value = data;
  472. if (inTangent != undefined) {
  473. keyData.inTangent = inTangent;
  474. }
  475. if (outTangent != undefined) {
  476. keyData.outTangent = outTangent;
  477. }
  478. keys.push(keyData)
  479. }
  480. animation.setKeys(keys);
  481. if (parsedAnimation.ranges) {
  482. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  483. data = parsedAnimation.ranges[index];
  484. animation.createRange(data.name, data.from, data.to);
  485. }
  486. }
  487. return animation;
  488. }
  489. public static AppendSerializedAnimations(source: IAnimatable, destination: any): any {
  490. if (source.animations) {
  491. destination.animations = [];
  492. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  493. var animation = source.animations[animationIndex];
  494. destination.animations.push(animation.serialize());
  495. }
  496. }
  497. }
  498. }
  499. }