animationCurveEditorComponent.tsx 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. import * as React from "react";
  2. import { Animation } from 'babylonjs/Animations/animation';
  3. import { Vector2 } from 'babylonjs/Maths/math.vector';
  4. import { EasingFunction } from 'babylonjs/Animations/easing';
  5. import { IAnimationKey } from 'babylonjs/Animations/animationKey';
  6. import { IKeyframeSvgPoint } from './keyframeSvgPoint';
  7. import { SvgDraggableArea } from './svgDraggableArea';
  8. import { Timeline } from './timeline';
  9. import { Playhead } from './playhead';
  10. import { Notification } from './notification';
  11. import { GraphActionsBar } from './graphActionsBar';
  12. import { Scene } from "babylonjs/scene";
  13. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  14. import { TargetedAnimation } from "babylonjs/Animations/animationGroup";
  15. import { EditorControls } from './editorControls';
  16. require("./curveEditor.scss");
  17. interface IAnimationCurveEditorComponentProps {
  18. close: (event: any) => void;
  19. playOrPause?: () => void;
  20. scene: Scene;
  21. entity: IAnimatable | TargetedAnimation;
  22. }
  23. interface ICanvasAxis {
  24. value: number;
  25. label: number;
  26. }
  27. export class AnimationCurveEditorComponent extends React.Component<IAnimationCurveEditorComponentProps, {
  28. isOpen: boolean,
  29. selected: Animation | null,
  30. currentPathData: string | undefined,
  31. svgKeyframes: IKeyframeSvgPoint[] | undefined,
  32. currentFrame: number,
  33. currentValue: number,
  34. frameAxisLength: ICanvasAxis[],
  35. valueAxisLength: ICanvasAxis[],
  36. isFlatTangentMode: boolean,
  37. isTangentMode: boolean,
  38. isBrokenMode: boolean,
  39. lerpMode: boolean,
  40. scale: number,
  41. playheadOffset: number,
  42. notification: string,
  43. currentPoint: SVGPoint | undefined,
  44. lastFrame: number,
  45. playheadPos: number,
  46. isPlaying: boolean,
  47. }> {
  48. // Height scale *Review this functionaliy
  49. private _heightScale: number = 100;
  50. // Canvas Length *Review this functionality
  51. readonly _entityName: string;
  52. readonly _canvasLength: number = 20;
  53. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  54. private _frames: Vector2[] = [];
  55. private _isPlaying: boolean = false;
  56. private _graphCanvas: React.RefObject<HTMLDivElement>;
  57. private _selectedCurve: React.RefObject<SVGPathElement>;
  58. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  59. private _isTargetedAnimation: boolean;
  60. constructor(props: IAnimationCurveEditorComponentProps) {
  61. super(props);
  62. this._entityName = (this.props.entity as any).id;
  63. // Review is we really need this refs
  64. this._graphCanvas = React.createRef();
  65. this._selectedCurve = React.createRef();
  66. this._svgCanvas = React.createRef();
  67. console.log(this.props.entity instanceof TargetedAnimation)
  68. let initialSelection;
  69. let initialPathData;
  70. let initialLerpMode;
  71. if (this.props.entity instanceof TargetedAnimation) {
  72. this._isTargetedAnimation = true;
  73. initialSelection = this.props.entity.animation;
  74. initialLerpMode = initialSelection !== undefined ? this.analizeAnimation(initialSelection) : false;
  75. initialPathData = initialSelection !== undefined ? this.getPathData(initialSelection) : "";
  76. } else {
  77. this._isTargetedAnimation = false;
  78. let hasAnimations = this.props.entity.animations !== undefined || this.props.entity.animations !== null ? this.props.entity.animations : false;
  79. initialSelection = hasAnimations !== false ? hasAnimations && hasAnimations[0] : null;
  80. initialLerpMode = initialSelection !== undefined ? this.analizeAnimation(this.props.entity.animations && initialSelection) : false;
  81. initialPathData = initialSelection && this.getPathData(initialSelection);
  82. initialPathData = initialPathData === null || initialPathData === undefined ? "" : initialPathData;
  83. }
  84. // will update this until we have a top scroll/zoom feature
  85. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  86. this.state = {
  87. selected: initialSelection,
  88. isOpen: true,
  89. currentPathData: initialPathData,
  90. svgKeyframes: this._svgKeyframes,
  91. currentFrame: 0,
  92. currentValue: 1,
  93. isFlatTangentMode: false,
  94. isTangentMode: false,
  95. isBrokenMode: false,
  96. lerpMode: initialLerpMode,
  97. playheadOffset: this._graphCanvas.current ? (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10) : 0,
  98. frameAxisLength: (new Array(this._canvasLength)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } }),
  99. valueAxisLength: (new Array(10)).fill(0).map((s, i) => { return { value: i * 10, label: valueInd[i] } }),
  100. notification: "",
  101. lastFrame: 0,
  102. currentPoint: undefined,
  103. scale: 1,
  104. playheadPos: 0,
  105. isPlaying: this.isAnimationPlaying(),
  106. }
  107. }
  108. componentDidMount() {
  109. setTimeout(() => this.resetPlayheadOffset(), 500);
  110. }
  111. /**
  112. * Notifications
  113. * To add notification we set the state and clear to make the notification bar hide.
  114. */
  115. clearNotification() {
  116. this.setState({ notification: "" });
  117. }
  118. /**
  119. * Zoom and Scroll
  120. * This section handles zoom and scroll
  121. * of the graph area.
  122. */
  123. zoom(e: React.WheelEvent<HTMLDivElement>) {
  124. e.nativeEvent.stopImmediatePropagation();
  125. console.log(e.deltaY);
  126. let scaleX = 1;
  127. if (Math.sign(e.deltaY) === -1) {
  128. scaleX = (this.state.scale - 0.01);
  129. } else {
  130. scaleX = (this.state.scale + 0.01);
  131. }
  132. this.setState({ scale: scaleX }, this.setAxesLength);
  133. }
  134. setAxesLength() {
  135. let length = Math.round(this._canvasLength * this.state.scale);// Check Undefined, or NaN
  136. let highestFrame = 100;
  137. if (this.state.selected !== null) {
  138. highestFrame = this.state.selected.getHighestFrame();
  139. }
  140. if (length < (highestFrame * 2) / 10) {
  141. length = (highestFrame * 2) / 10
  142. }
  143. let valueLines = Math.round((this.state.scale * this._heightScale) / 10);
  144. let newFrameLength = (new Array(length)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } });
  145. let newValueLength = (new Array(valueLines)).fill(0).map((s, i) => { return { value: i * 10, label: this.getValueLabel(i * 10) } });
  146. this.setState({ frameAxisLength: newFrameLength, valueAxisLength: newValueLength });
  147. this.resetPlayheadOffset();
  148. }
  149. getValueLabel(i: number) {
  150. // Need to update this when Y axis grows
  151. let label = 0;
  152. if (i === 0) {
  153. label = 2;
  154. }
  155. if (i === 50) {
  156. label = 1;
  157. } else {
  158. label = ((100 - (i * 2)) * 0.01) + 1;
  159. }
  160. return label;
  161. }
  162. resetPlayheadOffset() {
  163. if (this._graphCanvas && this._graphCanvas.current) {
  164. this.setState({ playheadOffset: (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10 * this.state.scale) });
  165. }
  166. }
  167. /**
  168. * Keyframe Manipulation
  169. * This section handles events from SvgDraggableArea.
  170. */
  171. selectKeyframe(id: string) {
  172. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  173. if (kf.id === id) {
  174. kf.selected = !kf.selected
  175. }
  176. return kf;
  177. });
  178. this.setState({ svgKeyframes: updatedKeyframes });
  179. }
  180. selectedControlPoint(type: string, id: string) {
  181. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  182. if (kf.id === id) {
  183. this.setState({ isFlatTangentMode: false });
  184. if (type === "left") {
  185. kf.isLeftActive = !kf.isLeftActive;
  186. kf.isRightActive = false;
  187. }
  188. if (type === "right") {
  189. kf.isRightActive = !kf.isRightActive;
  190. kf.isLeftActive = false;
  191. }
  192. }
  193. return kf;
  194. });
  195. this.setState({ svgKeyframes: updatedKeyframes });
  196. }
  197. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) {
  198. let animation = this.state.selected as Animation;
  199. // Bug: After play/stop we get an extra keyframe at 0
  200. let keys = [...animation.getKeys()];
  201. let newFrame = 0;
  202. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  203. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  204. newFrame = 1;
  205. } else {
  206. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x);
  207. }
  208. }
  209. keys[index].frame = newFrame; // This value comes as percentage/frame/time
  210. keys[index].value = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2; // this value comes inverted svg from 0 = 100 to 100 = 0
  211. if (updatedSvgKeyFrame.isLeftActive) {
  212. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  213. // Rotate
  214. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.leftControlPoint.y) / this._heightScale) * 2;
  215. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  216. keys[index].inTangent = keyframeValue - updatedValue;
  217. if (!this.state.isBrokenMode) {
  218. // Right control point if exists
  219. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  220. // Sets opposite value
  221. keys[index].outTangent = keys[index].inTangent * -1
  222. }
  223. }
  224. }
  225. }
  226. if (updatedSvgKeyFrame.isRightActive) {
  227. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  228. // Rotate
  229. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.rightControlPoint.y) / this._heightScale) * 2;
  230. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  231. keys[index].outTangent = keyframeValue - updatedValue;
  232. if (!this.state.isBrokenMode) {
  233. if (updatedSvgKeyFrame.leftControlPoint !== null) { // Sets opposite value
  234. keys[index].inTangent = keys[index].outTangent * -1
  235. }
  236. }
  237. }
  238. }
  239. animation.setKeys(keys);
  240. this.selectAnimation(animation);
  241. }
  242. /**
  243. * Actions
  244. * This section handles events from GraphActionsBar.
  245. */
  246. handleFrameChange(event: React.ChangeEvent<HTMLInputElement>) {
  247. event.preventDefault();
  248. this.changeCurrentFrame(parseInt(event.target.value))
  249. }
  250. handleValueChange(event: React.ChangeEvent<HTMLInputElement>) {
  251. event.preventDefault();
  252. this.setState({ currentValue: parseFloat(event.target.value) }, () => {
  253. if (this.state.selected !== null) {
  254. let animation = this.state.selected;
  255. let keys = animation.getKeys();
  256. let isKeyframe = keys.find(k => k.frame === this.state.currentFrame);
  257. if (isKeyframe) {
  258. let updatedKeys = keys.map(k => {
  259. if (k.frame === this.state.currentFrame) {
  260. k.value = this.state.currentValue;
  261. }
  262. return k;
  263. });
  264. this.state.selected.setKeys(updatedKeys);
  265. this.selectAnimation(animation);
  266. }
  267. }
  268. });
  269. }
  270. setFlatTangent() {
  271. if (this.state.selected !== null) {
  272. let animation = this.state.selected;
  273. this.setState({ isFlatTangentMode: !this.state.isFlatTangentMode }, () => this.selectAnimation(animation));
  274. }
  275. }
  276. // Use this for Bezier curve mode
  277. setTangentMode() {
  278. if (this.state.selected !== null) {
  279. let animation = this.state.selected;
  280. this.setState({ isTangentMode: !this.state.isTangentMode }, () => this.selectAnimation(animation));
  281. }
  282. }
  283. setBrokenMode() {
  284. if (this.state.selected !== null) {
  285. let animation = this.state.selected;
  286. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () => this.selectAnimation(animation));
  287. }
  288. }
  289. setLerpMode() {
  290. if (this.state.selected !== null) {
  291. let animation = this.state.selected;
  292. this.setState({ lerpMode: !this.state.lerpMode }, () => this.selectAnimation(animation));
  293. }
  294. }
  295. addKeyframeClick() {
  296. if (this.state.selected !== null) {
  297. let currentAnimation = this.state.selected;
  298. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  299. let keys = currentAnimation.getKeys();
  300. let x = this.state.currentFrame;
  301. let y = this.state.currentValue;
  302. keys.push({ frame: x, value: y, inTangent: 0, outTangent: 0 });
  303. keys.sort((a, b) => a.frame - b.frame);
  304. currentAnimation.setKeys(keys);
  305. this.selectAnimation(currentAnimation);
  306. }
  307. }
  308. }
  309. removeKeyframeClick() {
  310. if (this.state.selected !== null) {
  311. let currentAnimation = this.state.selected;
  312. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  313. let keys = currentAnimation.getKeys();
  314. let x = this.state.currentFrame;
  315. let filteredKeys = keys.filter(kf => kf.frame !== x);
  316. currentAnimation.setKeys(filteredKeys);
  317. this.selectAnimation(currentAnimation);
  318. }
  319. }
  320. }
  321. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  322. event.preventDefault();
  323. if (this.state.selected !== null) {
  324. var svg = event.target as SVGSVGElement;
  325. var pt = svg.createSVGPoint();
  326. pt.x = event.clientX;
  327. pt.y = event.clientY;
  328. var inverse = svg.getScreenCTM()?.inverse();
  329. var cursorpt = pt.matrixTransform(inverse);
  330. var currentAnimation = this.state.selected;
  331. var keys = currentAnimation.getKeys();
  332. var height = 100;
  333. var middle = (height / 2);
  334. var keyValue;
  335. if (cursorpt.y < middle) {
  336. keyValue = 1 + ((100 / cursorpt.y) * .1)
  337. }
  338. if (cursorpt.y > middle) {
  339. keyValue = 1 - ((100 / cursorpt.y) * .1)
  340. }
  341. keys.push({ frame: cursorpt.x, value: keyValue });
  342. currentAnimation.setKeys(keys);
  343. this.selectAnimation(currentAnimation);
  344. }
  345. }
  346. updateKeyframe(keyframe: Vector2, index: number) {
  347. let anim = this.state.selected as Animation;
  348. var keys: IAnimationKey[] = [];
  349. var svgKeyframes = this.state.svgKeyframes?.map((k, i) => {
  350. if (i === index) {
  351. k.keyframePoint.x = keyframe.x;
  352. k.keyframePoint.y = keyframe.y;
  353. }
  354. var height = 100;
  355. var middle = (height / 2);
  356. var keyValue;
  357. if (k.keyframePoint.y < middle) {
  358. keyValue = 1 + ((100 / k.keyframePoint.y) * .1)
  359. }
  360. if (k.keyframePoint.y > middle) {
  361. keyValue = 1 - ((100 / k.keyframePoint.y) * .1)
  362. }
  363. keys.push({ frame: k.keyframePoint.x, value: keyValue })
  364. return k;
  365. });
  366. anim.setKeys(keys);
  367. this.setState({ svgKeyframes: svgKeyframes });
  368. }
  369. /**
  370. * Curve Rendering Functions
  371. * This section handles how to render curves.
  372. */
  373. getAnimationProperties(animation: Animation) {
  374. let easingType, easingMode;
  375. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  376. if (easingFunction === undefined) {
  377. easingType = undefined
  378. easingMode = undefined;
  379. } else {
  380. easingType = easingFunction.constructor.name;
  381. easingMode = easingFunction.getEasingMode();
  382. }
  383. return { easingType, easingMode }
  384. }
  385. linearInterpolation(keyframes: IAnimationKey[], data: string, middle: number): string {
  386. keyframes.forEach((key, i) => {
  387. var point = new Vector2(0, 0);
  388. point.x = key.frame;
  389. point.y = this._heightScale - (key.value * middle);
  390. this.setKeyframePointLinear(point, i);
  391. if (i !== 0) {
  392. data += ` L${point.x} ${point.y}`
  393. }
  394. });
  395. return data;
  396. }
  397. setKeyframePointLinear(point: Vector2, index: number) {
  398. let svgKeyframe = { keyframePoint: point, rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  399. this._svgKeyframes.push(svgKeyframe);
  400. }
  401. getPathData(animation: Animation | null) {
  402. if (animation === null){
  403. return "";
  404. }
  405. // Check if Tangent mode is active and broken mode is active. (Only one tangent moves)
  406. let keyframes = animation.getKeys();
  407. if (keyframes === undefined) {
  408. return "";
  409. }
  410. // Checks if Flat Tangent is active (tangents are set to zero)
  411. if (this.state && this.state.isFlatTangentMode) {
  412. keyframes = animation.getKeys().map(kf => {
  413. if (kf.inTangent !== undefined) {
  414. kf.inTangent = 0;
  415. }
  416. if (kf.outTangent !== undefined) {
  417. kf.outTangent = 0;
  418. }
  419. return kf;
  420. });
  421. } else {
  422. keyframes = animation.getKeys();
  423. }
  424. const startKey = keyframes[0];
  425. let middle = this._heightScale / 2;
  426. // START OF LINE/CURVE
  427. let data: string | undefined = `M${startKey.frame}, ${this._heightScale - (startKey.value * middle)}`;
  428. if (this.state && this.state.lerpMode) {
  429. data = this.linearInterpolation(keyframes, data, middle);
  430. } else {
  431. if (this.getAnimationData(animation).usesTangents) {
  432. data = this.curvePathWithTangents(keyframes, data, middle, animation.dataType);
  433. } else {
  434. const { easingMode, easingType } = this.getAnimationProperties(animation);
  435. if (easingType !== undefined && easingMode !== undefined) {
  436. let easingFunction = animation.getEasingFunction();
  437. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction)
  438. } else {
  439. if (this.state !== undefined) {
  440. let emptyTangents = keyframes.map((kf, i) => {
  441. if (i === 0) {
  442. kf.outTangent = 0;
  443. } else if (i === keyframes.length - 1) {
  444. kf.inTangent = 0;
  445. } else {
  446. kf.inTangent = 0;
  447. kf.outTangent = 0;
  448. }
  449. return kf;
  450. });
  451. data = this.curvePathWithTangents(emptyTangents, data, middle, animation.dataType);
  452. } else {
  453. data = this.linearInterpolation(keyframes, data, middle);
  454. }
  455. }
  456. }
  457. }
  458. return data;
  459. }
  460. getAnimationData(animation: Animation) {
  461. // General Props
  462. let loopMode = animation.loopMode;
  463. let name = animation.name;
  464. let blendingSpeed = animation.blendingSpeed;
  465. let targetProperty = animation.targetProperty;
  466. let targetPropertyPath = animation.targetPropertyPath;
  467. let framesPerSecond = animation.framePerSecond;
  468. let highestFrame = animation.getHighestFrame();
  469. let serialized = animation.serialize();
  470. let usesTangents = animation.getKeys().find(kf => kf.hasOwnProperty('inTangent') || kf.hasOwnProperty('outTangent')) !== undefined ? true : false;
  471. return { loopMode, name, blendingSpeed, targetPropertyPath, targetProperty, framesPerSecond, highestFrame, serialized, usesTangents }
  472. }
  473. drawAllFrames(initialKey: IAnimationKey, endKey: IAnimationKey, easingFunction: EasingFunction) {
  474. let i = initialKey.frame;
  475. for (i; i < endKey.frame; i++) {
  476. (i * 100 / endKey.frame)
  477. let dy = easingFunction.easeInCore(i);
  478. let value = this._heightScale - (dy * (this._heightScale / 2));
  479. this._frames.push(new Vector2(i, value));
  480. }
  481. }
  482. curvePathFlat(keyframes: IAnimationKey[], data: string, middle: number, dataType: number) {
  483. keyframes.forEach((key, i) => {
  484. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  485. var pointA = new Vector2(0, 0);
  486. if (i === 0) {
  487. pointA.set(key.frame, this._heightScale - (key.value * middle));
  488. this.setKeyframePoint([pointA], i, keyframes.length);
  489. } else {
  490. pointA.set(keyframes[i - 1].frame, this._heightScale - (keyframes[i - 1].value * middle));
  491. let defaultWeight = 10;
  492. let nextKeyframe = keyframes[i + 1];
  493. let prevKeyframe = keyframes[i - 1];
  494. if (nextKeyframe !== undefined) {
  495. let distance = keyframes[i + 1].frame - key.frame;
  496. defaultWeight = distance * .33;
  497. }
  498. if (prevKeyframe !== undefined) {
  499. let distance = key.frame - keyframes[i - 1].frame;
  500. defaultWeight = distance * .33;
  501. }
  502. let tangentA = new Vector2(pointA.x + defaultWeight, pointA.y);
  503. let pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  504. let tangentB = new Vector2(pointB.x - defaultWeight, pointB.y);
  505. this.setKeyframePoint([pointA, tangentA, tangentB, pointB], i, keyframes.length);
  506. data += ` C${tangentA.x} ${tangentA.y} ${tangentB.x} ${tangentB.y} ${pointB.x} ${pointB.y} `
  507. }
  508. }
  509. });
  510. return data;
  511. }
  512. curvePathWithTangents(keyframes: IAnimationKey[], data: string, middle: number, type: number) {
  513. keyframes.forEach((key, i) => {
  514. let svgKeyframe;
  515. let outTangent;
  516. let inTangent;
  517. let defaultWeight = 5;
  518. var inT = key.inTangent === undefined ? null : key.inTangent;
  519. var outT = key.outTangent === undefined ? null : key.outTangent;
  520. let y = this._heightScale - (key.value * middle);
  521. let nextKeyframe = keyframes[i + 1];
  522. let prevKeyframe = keyframes[i - 1];
  523. if (nextKeyframe !== undefined) {
  524. let distance = keyframes[i + 1].frame - key.frame;
  525. defaultWeight = distance * .33;
  526. }
  527. if (prevKeyframe !== undefined) {
  528. let distance = key.frame - keyframes[i - 1].frame;
  529. defaultWeight = distance * .33;
  530. }
  531. if (inT !== null) {
  532. let valueIn = (y * inT) + y;
  533. inTangent = new Vector2(key.frame - defaultWeight, valueIn)
  534. } else {
  535. inTangent = null;
  536. }
  537. if (outT !== null) {
  538. let valueOut = (y * outT) + y;
  539. outTangent = new Vector2(key.frame + defaultWeight, valueOut);
  540. } else {
  541. outTangent = null;
  542. }
  543. if (i === 0) {
  544. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: null, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  545. if (outTangent !== null) {
  546. data += ` C${outTangent.x} ${outTangent.y} `;
  547. }
  548. } else {
  549. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: inTangent, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  550. if (outTangent !== null && inTangent !== null) {
  551. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y} `
  552. } else if (inTangent !== null) {
  553. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `
  554. }
  555. }
  556. if (this.state) {
  557. let prev = this.state.svgKeyframes?.find(kf => kf.id === i.toString());
  558. if (prev) {
  559. svgKeyframe.isLeftActive = prev?.isLeftActive;
  560. svgKeyframe.isRightActive = prev?.isRightActive;
  561. svgKeyframe.selected = prev?.selected
  562. }
  563. }
  564. this._svgKeyframes.push(svgKeyframe);
  565. }, this);
  566. return data;
  567. }
  568. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  569. // This will get 1/4 and 3/4 of points in eased curve
  570. const u = .25;
  571. const v = .75;
  572. keyframes.forEach((key, i) => {
  573. // Gets previous initial point of curve segment
  574. var pointA = new Vector2(0, 0);
  575. if (i === 0) {
  576. pointA.x = key.frame;
  577. pointA.y = this._heightScale - (key.value * middle);
  578. this.setKeyframePoint([pointA], i, keyframes.length);
  579. } else {
  580. pointA.x = keyframes[i - 1].frame;
  581. pointA.y = this._heightScale - (keyframes[i - 1].value * middle)
  582. // Gets the end point of this curve segment
  583. var pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  584. // Get easing value of percentage to get the bezier control points below
  585. let du = easingFunction.easeInCore(u); // What to do here, when user edits the curve? Option 1: Modify the curve with the new control points as BezierEaseCurve(x,y,z,w)
  586. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  587. // Direction of curve up/down
  588. let yInt25 = 0;
  589. if (pointB.y > pointA.y) { // if pointB.y > pointA.y = goes down
  590. yInt25 = ((pointB.y - pointA.y) * du) + pointA.y
  591. } else if (pointB.y < pointA.y) { // if pointB.y < pointA.y = goes up
  592. yInt25 = pointA.y - ((pointA.y - pointB.y) * du);
  593. }
  594. let yInt75 = 0;
  595. if (pointB.y > pointA.y) {
  596. yInt75 = ((pointB.y - pointA.y) * dv) + pointA.y
  597. } else if (pointB.y < pointA.y) {
  598. yInt75 = pointA.y - ((pointA.y - pointB.y) * dv)
  599. }
  600. // Intermediate points in curve
  601. let intermediatePoint25 = new Vector2(((pointB.x - pointA.x) * u) + pointA.x, yInt25);
  602. let intermediatePoint75 = new Vector2(((pointB.x - pointA.x) * v) + pointA.x, yInt75);
  603. // Gets the four control points of bezier curve
  604. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  605. if (controlPoints === undefined) {
  606. console.log("error getting bezier control points");
  607. } else {
  608. this.setKeyframePoint(controlPoints, i, keyframes.length);
  609. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`
  610. }
  611. }
  612. });
  613. return data;
  614. }
  615. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  616. let svgKeyframe;
  617. if (index === 0) {
  618. svgKeyframe = { keyframePoint: controlPoints[0], rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  619. } else {
  620. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  621. svgKeyframe = { keyframePoint: controlPoints[3], rightControlPoint: null, leftControlPoint: controlPoints[2], id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  622. }
  623. this._svgKeyframes.push(svgKeyframe);
  624. }
  625. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v: number, p3: Vector2): Vector2[] | undefined {
  626. let a = 0.0;
  627. let b = 0.0;
  628. let c = 0.0;
  629. let d = 0.0;
  630. let det = 0.0;
  631. let q1: Vector2 = new Vector2();
  632. let q2: Vector2 = new Vector2();
  633. let controlA: Vector2 = p0;
  634. let controlB: Vector2 = new Vector2();
  635. let controlC: Vector2 = new Vector2();
  636. let controlD: Vector2 = p3;
  637. if ((u <= 0.0) || (u >= 1.0) || (v <= 0.0) || (v >= 1.0) || (u >= v)) {
  638. return undefined;
  639. }
  640. a = 3 * (1 - u) * (1 - u) * u; b = 3 * (1 - u) * u * u;
  641. c = 3 * (1 - v) * (1 - v) * v; d = 3 * (1 - v) * v * v;
  642. det = a * d - b * c;
  643. if (det == 0.0) return undefined;
  644. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  645. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  646. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  647. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  648. controlB.x = (d * q1.x - b * q2.x) / det;
  649. controlB.y = (d * q1.y - b * q2.y) / det;
  650. controlC.x = ((-c) * q1.x + a * q2.x) / det;
  651. controlC.y = ((-c) * q1.y + a * q2.y) / det;
  652. return [controlA, controlB, controlC, controlD];
  653. }
  654. /**
  655. * Core functions
  656. * This section handles main Curve Editor Functions.
  657. */
  658. selectAnimation(animation: Animation, axis?: string) {
  659. if (!axis){
  660. this.playStopAnimation();
  661. this._svgKeyframes = [];
  662. const pathData = this.getPathData(animation);
  663. let lastFrame = animation.getHighestFrame();
  664. if (pathData === "") {
  665. console.log("no keyframes in this animation");
  666. }
  667. this.setState({ selected: animation, currentPathData: pathData, svgKeyframes: this._svgKeyframes, lastFrame: lastFrame });
  668. } else {
  669. console.log(axis); // This will handle animations that are not Float type
  670. }
  671. }
  672. isAnimationPlaying() {
  673. let target = this.props.entity;
  674. if (this.props.entity instanceof TargetedAnimation) {
  675. target = this.props.entity.target;
  676. }
  677. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  678. }
  679. playPause(direction: number) {
  680. if (this.state.selected) {
  681. let target = this.props.entity;
  682. if (this.props.entity instanceof TargetedAnimation) {
  683. target = this.props.entity.target;
  684. }
  685. if (this.state.isPlaying) {
  686. this.props.scene.stopAnimation(target);
  687. this.setState({ isPlaying: false })
  688. this._isPlaying = false;
  689. this.forceUpdate();
  690. } else {
  691. let keys = this.state.selected.getKeys();
  692. let firstFrame = keys[0].frame;
  693. let LastFrame = keys[keys.length - 1].frame;
  694. if (direction === 1){
  695. this.props.scene.beginAnimation(target, firstFrame, LastFrame, true);
  696. }
  697. if (direction === -1){
  698. this.props.scene.beginAnimation(target, LastFrame, firstFrame, true);
  699. }
  700. this._isPlaying = true;
  701. this.setState({ isPlaying: true });
  702. this.forceUpdate();
  703. }
  704. }
  705. }
  706. playStopAnimation() {
  707. let target = this.props.entity;
  708. if (this.props.entity instanceof TargetedAnimation) {
  709. target = this.props.entity.target;
  710. }
  711. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  712. if (this._isPlaying) {
  713. this.props.playOrPause && this.props.playOrPause();
  714. return true;
  715. } else {
  716. this._isPlaying = false;
  717. return false;
  718. }
  719. }
  720. analizeAnimation(animation: Animation | null) {
  721. if (animation !== null) {
  722. const { easingMode, easingType } = this.getAnimationProperties(animation);
  723. let hasDefinedTangents = this.getAnimationData(animation).usesTangents;
  724. if (easingType === undefined && easingMode === undefined && !hasDefinedTangents) {
  725. return true;
  726. } else {
  727. return false;
  728. }
  729. } else {
  730. return false;
  731. }
  732. }
  733. /**
  734. * Timeline
  735. * This section controls the timeline.
  736. */
  737. changeCurrentFrame(frame: number) {
  738. let currentValue;
  739. let selectedCurve = this._selectedCurve.current;
  740. if (selectedCurve) {
  741. var curveLength = selectedCurve.getTotalLength();
  742. let frameValue = (frame * curveLength) / 100;
  743. let currentP = selectedCurve.getPointAtLength(frameValue);
  744. let middle = this._heightScale / 2;
  745. let offset = (((currentP?.y * this._heightScale) - (this._heightScale ** 2) / 2) / middle) / this._heightScale;
  746. let unit = Math.sign(offset);
  747. currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  748. this.setState({ currentFrame: frame, currentValue: currentValue, currentPoint: currentP });
  749. }
  750. }
  751. updateFrameInKeyFrame(frame: number, index: number) {
  752. if (this.state && this.state.selected) {
  753. let animation = this.state.selected;
  754. let keys = [...animation.getKeys()];
  755. keys[index].frame = frame;
  756. animation.setKeys(keys);
  757. this.selectAnimation(animation);
  758. }
  759. }
  760. render() {
  761. return (
  762. <div id="animation-curve-editor">
  763. <Notification message={this.state.notification} open={this.state.notification !== "" ? true : false} close={() => this.clearNotification()} />
  764. <GraphActionsBar
  765. enabled={this.state.selected === null || this.state.selected === undefined ? false : true}
  766. title={this._entityName}
  767. close={this.props.close}
  768. currentValue={this.state.currentValue}
  769. currentFrame={this.state.currentFrame}
  770. handleFrameChange={(e) => this.handleFrameChange(e)}
  771. handleValueChange={(e) => this.handleValueChange(e)}
  772. addKeyframe={() => this.addKeyframeClick()}
  773. removeKeyframe={() => this.removeKeyframeClick()}
  774. brokenMode={this.state.isBrokenMode}
  775. brokeTangents={() => this.setBrokenMode()}
  776. lerpMode={this.state.lerpMode}
  777. setLerpMode={() => this.setLerpMode()}
  778. flatTangent={() => this.setFlatTangent()} />
  779. <div className="content">
  780. <div className="row">
  781. <EditorControls selectAnimation={(animation: Animation, axis?: string) => this.selectAnimation(animation, axis)}
  782. isTargetedAnimation={this._isTargetedAnimation}
  783. entity={this.props.entity}
  784. selected={this.state.selected}
  785. setNotificationMessage={(message: string) => { this.setState({notification: message})}}
  786. />
  787. <div ref={this._graphCanvas} className="graph-chart" onWheel={(e) => this.zoom(e)} >
  788. <Playhead frame={this.state.currentFrame} offset={this.state.playheadOffset} />
  789. {this.state.svgKeyframes && <SvgDraggableArea ref={this._svgCanvas}
  790. selectKeyframe={(id: string) => this.selectKeyframe(id)}
  791. viewBoxScale={this.state.frameAxisLength.length} scale={this.state.scale}
  792. keyframeSvgPoints={this.state.svgKeyframes}
  793. selectedControlPoint={(type: string, id: string) => this.selectedControlPoint(type, id)}
  794. updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) => this.renderPoints(updatedSvgKeyFrame, index)}>
  795. {/* Frame Labels */}
  796. { /* Vertical Grid */}
  797. {this.state.frameAxisLength.map((f, i) =>
  798. <svg key={i}>
  799. <text x={f.value} y="-2" dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.value}</text>
  800. <line x1={f.value} y1="0" x2={f.value} y2="100%"></line>
  801. </svg>
  802. )}
  803. {this.state.valueAxisLength.map((f, i) => {
  804. return <svg key={i}>
  805. <text x="-3" y={f.value} dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.label.toFixed(1)}</text>
  806. <line x1="0" y1={f.value} x2="100%" y2={f.value}></line>
  807. </svg>
  808. })}
  809. { /* Single Curve -Modify this for multiple selection and view */}
  810. <path ref={this._selectedCurve} pathLength={this.state.lastFrame} id="curve" d={this.state.currentPathData} style={{ stroke: 'red', fill: 'none', strokeWidth: '0.5' }}></path>
  811. {this._frames && this._frames.map(frame =>
  812. <svg x={frame.x} y={frame.y} style={{ overflow: 'visible' }}>
  813. <circle cx="0" cy="0" r="2" stroke="black" strokeWidth="1" fill="white" />
  814. </svg>
  815. )}
  816. </SvgDraggableArea>
  817. }
  818. </div>
  819. </div>
  820. <div className="row">
  821. <Timeline currentFrame={this.state.currentFrame} playPause={(direction: number) => this.playPause(direction)} isPlaying={this.state.isPlaying} dragKeyframe={(frame: number, index: number) => this.updateFrameInKeyFrame(frame, index)} onCurrentFrameChange={(frame: number) => this.changeCurrentFrame(frame)} keyframes={this.state.selected && this.state.selected.getKeys()} selected={this.state.selected && this.state.selected.getKeys()[0]}></Timeline>
  822. </div>
  823. </div>
  824. </div>
  825. );
  826. }
  827. }