animationCurveEditorComponent.tsx 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. import * as React from 'react';
  2. import { Animation } from 'babylonjs/Animations/animation';
  3. import { Vector2, Vector3, Quaternion } from 'babylonjs/Maths/math.vector';
  4. import { Color3, Color4 } from 'babylonjs/Maths/math.color';
  5. import { Size } from 'babylonjs/Maths/math.size';
  6. import { EasingFunction } from 'babylonjs/Animations/easing';
  7. import { IAnimationKey } from 'babylonjs/Animations/animationKey';
  8. import { IKeyframeSvgPoint } from './keyframeSvgPoint';
  9. import { SvgDraggableArea } from './svgDraggableArea';
  10. import { Timeline } from './timeline';
  11. import { Notification } from './notification';
  12. import { GraphActionsBar } from './graphActionsBar';
  13. import { Scene } from 'babylonjs/scene';
  14. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  15. import { Animatable } from 'babylonjs/Animations/animatable';
  16. import { TargetedAnimation } from 'babylonjs/Animations/animationGroup';
  17. import { EditorControls } from './editorControls';
  18. import { SelectedCoordinate } from './animationListTree';
  19. import { LockObject } from '../lockObject';
  20. import { GlobalState } from '../../../../globalState';
  21. import { Nullable } from 'babylonjs/types';
  22. import { Observer } from 'babylonjs/Misc/observable';
  23. import { ScaleLabel } from './scale-label';
  24. require('./curveEditor.scss');
  25. interface IAnimationCurveEditorComponentProps {
  26. close: (event: any) => void;
  27. playOrPause?: () => void;
  28. scene: Scene;
  29. entity: IAnimatable | TargetedAnimation;
  30. lockObject: LockObject;
  31. globalState: GlobalState;
  32. }
  33. interface ICanvasAxis {
  34. value: number;
  35. label: number;
  36. }
  37. export enum CurveScale {
  38. float,
  39. radians,
  40. degrees,
  41. integers,
  42. default,
  43. }
  44. export interface IActionableKeyFrame {
  45. frame?: number | string;
  46. value?: any;
  47. }
  48. interface ICurveData {
  49. pathData: string;
  50. pathLength: number;
  51. domCurve: React.RefObject<SVGPathElement>;
  52. color: string;
  53. id: string;
  54. }
  55. export class AnimationCurveEditorComponent extends React.Component<
  56. IAnimationCurveEditorComponentProps,
  57. {
  58. isOpen: boolean;
  59. selected: Animation | null;
  60. svgKeyframes: IKeyframeSvgPoint[] | undefined;
  61. currentFrame: number;
  62. currentValue: number;
  63. frameAxisLength: ICanvasAxis[];
  64. valueAxisLength: ICanvasAxis[];
  65. isFlatTangentMode: boolean;
  66. isTangentMode: boolean;
  67. isBrokenMode: boolean;
  68. lerpMode: boolean;
  69. scale: number;
  70. playheadOffset: number;
  71. notification: string;
  72. currentPoint: SVGPoint | undefined;
  73. playheadPos: number;
  74. isPlaying: boolean;
  75. selectedPathData: ICurveData[] | undefined;
  76. selectedCoordinate: number;
  77. animationLimit: number;
  78. fps: number;
  79. isLooping: boolean;
  80. panningY: number;
  81. panningX: number;
  82. repositionCanvas: boolean;
  83. actionableKeyframe: IActionableKeyFrame;
  84. valueScale: CurveScale;
  85. }
  86. > {
  87. private _snippetUrl = 'https://snippet.babylonjs.com';
  88. // Height scale *Review this functionaliy
  89. private _heightScale: number = 100;
  90. // Canvas Length *Review this functionality
  91. readonly _entityName: string;
  92. readonly _canvasLength: number = 20;
  93. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  94. private _isPlaying: boolean = false;
  95. private _graphCanvas: React.RefObject<HTMLDivElement>;
  96. //private _selectedCurve: React.RefObject<SVGPathElement>;
  97. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  98. private _isTargetedAnimation: boolean;
  99. private _pixelFrameUnit: number;
  100. private _onBeforeRenderObserver: Nullable<Observer<Scene>>;
  101. private _mainAnimatable: Nullable<Animatable>;
  102. constructor(props: IAnimationCurveEditorComponentProps) {
  103. super(props);
  104. this._entityName = (this.props.entity as any).id;
  105. this._graphCanvas = React.createRef();
  106. this._svgCanvas = React.createRef();
  107. this._pixelFrameUnit = 10;
  108. let initialSelection;
  109. let initialPathData;
  110. let initialLerpMode;
  111. if (this.props.entity instanceof TargetedAnimation) {
  112. this._isTargetedAnimation = true;
  113. initialSelection = this.props.entity.animation;
  114. initialLerpMode = initialSelection !== undefined ? this.analizeAnimationForLerp(initialSelection) : false;
  115. initialPathData = initialSelection !== undefined ? this.getPathData(initialSelection) : undefined;
  116. } else {
  117. this._isTargetedAnimation = false;
  118. let hasAnimations = this.props.entity.animations !== undefined || this.props.entity.animations !== null ? this.props.entity.animations : false;
  119. initialSelection = hasAnimations !== false ? hasAnimations && hasAnimations[0] : null;
  120. initialLerpMode = initialSelection !== undefined ? this.analizeAnimationForLerp(this.props.entity.animations && initialSelection) : false;
  121. initialPathData = initialSelection && this.getPathData(initialSelection);
  122. initialPathData = initialPathData === null || initialPathData === undefined ? undefined : initialPathData;
  123. }
  124. this._canvasLength = 240;
  125. this.stopAnimation();
  126. // will update this until we have a top scroll/zoom feature
  127. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  128. this.state = {
  129. selected: initialSelection,
  130. isOpen: true,
  131. svgKeyframes: this._svgKeyframes,
  132. currentFrame: 0,
  133. currentValue: 1,
  134. isFlatTangentMode: false,
  135. isTangentMode: false,
  136. isBrokenMode: false,
  137. lerpMode: initialLerpMode,
  138. playheadOffset: this._graphCanvas.current ? this._graphCanvas.current.children[0].clientWidth / (this._canvasLength * 10) : 0,
  139. frameAxisLength: this.setFrameAxis(this._canvasLength),
  140. valueAxisLength: new Array(10).fill(0).map((s, i) => {
  141. return { value: i * 10, label: valueInd[i] };
  142. }),
  143. notification: '',
  144. currentPoint: undefined,
  145. scale: 1,
  146. playheadPos: 0,
  147. isPlaying: false,
  148. selectedPathData: initialPathData,
  149. selectedCoordinate: 0,
  150. animationLimit: this._canvasLength / 2,
  151. fps: 60,
  152. isLooping: true,
  153. panningY: 0,
  154. panningX: 0,
  155. repositionCanvas: false,
  156. actionableKeyframe: { frame: undefined, value: undefined },
  157. valueScale: CurveScale.degrees,
  158. };
  159. }
  160. componentDidMount() {
  161. this.state.selected && this.selectAnimation(this.state.selected);
  162. }
  163. /**
  164. * Notifications
  165. * To add notification we set the state and clear to make the notification bar hide.
  166. */
  167. clearNotification() {
  168. this.setState({ notification: '' });
  169. }
  170. /**
  171. * Zoom and Scroll
  172. * This section handles zoom and scroll
  173. * of the graph area.
  174. */
  175. zoom(e: React.WheelEvent<HTMLDivElement>) {
  176. e.nativeEvent.stopImmediatePropagation();
  177. let scaleX = 1;
  178. if (Math.sign(e.deltaY) === -1) {
  179. scaleX = this.state.scale; //- 0.01; //+ 0.01;
  180. }
  181. this.setState({ scale: scaleX });
  182. }
  183. setFrameAxis(currentLength: number) {
  184. let halfNegative = new Array(currentLength / 2).fill(0).map((s, i) => {
  185. return { value: -i * 10, label: -i };
  186. });
  187. let halfPositive = new Array(currentLength / 2).fill(0).map((s, i) => {
  188. return { value: i * 10, label: i };
  189. });
  190. return [...halfNegative, ...halfPositive];
  191. }
  192. setValueLines(type: CurveScale) {
  193. let scaleValues = { scale: 10, factor: 0 };
  194. switch (type) {
  195. case CurveScale.default:
  196. scaleValues.factor = 2;
  197. this._heightScale = 100;
  198. break;
  199. case CurveScale.float:
  200. scaleValues.factor = 2.5;
  201. this._heightScale = 120;
  202. break;
  203. case CurveScale.degrees:
  204. scaleValues.factor = 50;
  205. this._heightScale = 200;
  206. break;
  207. case CurveScale.integers:
  208. scaleValues.factor = 320;
  209. break;
  210. case CurveScale.radians:
  211. scaleValues.factor = 0.8;
  212. break;
  213. }
  214. const initialValues = new Array(scaleValues.scale).fill(0).map((_, i) => {
  215. return {
  216. value: i * scaleValues.scale,
  217. label: (scaleValues.factor * ((scaleValues.scale - i) / scaleValues.scale)).toFixed(2),
  218. };
  219. });
  220. initialValues.shift();
  221. const valueHeight = Math.abs(Math.round(this.state.panningY / scaleValues.scale));
  222. const sign = Math.sign(this.state.panningY);
  223. const pannedValues = new Array(valueHeight).fill(0).map((s, i) => {
  224. return sign === -1
  225. ? {
  226. value: -i * scaleValues.scale,
  227. label: (i + scaleValues.scale) / (scaleValues.scale / scaleValues.factor),
  228. }
  229. : {
  230. value: (i + scaleValues.scale) * scaleValues.scale,
  231. label: (i * -1) / (scaleValues.scale / scaleValues.factor),
  232. };
  233. });
  234. return [...initialValues, ...pannedValues];
  235. }
  236. setAxesLength() {
  237. let length = this.state.animationLimit * 2;
  238. let newlength = Math.round(this._canvasLength * this.state.scale);
  239. if (!isNaN(newlength) || newlength !== undefined) {
  240. length = newlength;
  241. }
  242. let highestFrame = 100;
  243. if (this.state.selected !== null && this.state.selected !== undefined) {
  244. highestFrame = this.state.selected.getHighestFrame();
  245. }
  246. if (length < (highestFrame * 2) / 10) {
  247. length = Math.round((highestFrame * 2) / 10);
  248. }
  249. let valueLines = Math.round((this.state.scale * this._heightScale) / 10);
  250. let newFrameLength = new Array(length).fill(0).map((s, i) => {
  251. return { value: i * 10, label: i };
  252. });
  253. let newValueLength = new Array(valueLines).fill(0).map((s, i) => {
  254. return { value: i * 10, label: this.getValueLabel(i * 10) };
  255. });
  256. this.setState({
  257. frameAxisLength: newFrameLength,
  258. valueAxisLength: newValueLength,
  259. });
  260. this.resetPlayheadOffset();
  261. }
  262. getValueLabel(i: number) {
  263. // Need to update this when Y axis grows
  264. let label = 0;
  265. if (i === 0) {
  266. label = 2;
  267. }
  268. if (i === 50) {
  269. label = 1;
  270. } else {
  271. label = (100 - i * 2) * 0.01 + 1;
  272. }
  273. return label;
  274. }
  275. resetPlayheadOffset() {
  276. if (this._graphCanvas && this._graphCanvas.current) {
  277. this.setState({
  278. playheadOffset: this._graphCanvas.current.children[0].clientWidth / (this._canvasLength * 10 * this.state.scale),
  279. });
  280. }
  281. }
  282. encodeCurveId(animationName: string, coordinate: number) {
  283. return animationName + '_' + coordinate;
  284. }
  285. decodeCurveId(id: string) {
  286. const order = parseInt(id.split('_')[3]);
  287. const coordinate = parseInt(id.split('_')[2]);
  288. return { order, coordinate };
  289. }
  290. getKeyframeValueFromAnimation(id: string) {
  291. const animation = this.state.selected as Animation;
  292. const { order, coordinate } = this.decodeCurveId(id);
  293. const keys = [...animation.getKeys()];
  294. const key = keys.find((_, i) => i === order);
  295. if (key) {
  296. const valueAsArray = this.getValueAsArray(animation.dataType, key.value);
  297. return { frame: key?.frame, value: valueAsArray[coordinate] };
  298. } else {
  299. return undefined;
  300. }
  301. }
  302. /**
  303. * Keyframe Manipulation
  304. * This section handles events from SvgDraggableArea.
  305. */
  306. selectKeyframe(id: string, multiselect: boolean) {
  307. const frameValue = this.getKeyframeValueFromAnimation(id);
  308. const selectedKeyFrame = this.state.svgKeyframes?.find((kf) => kf.id === id)?.selected;
  309. if (!multiselect) {
  310. this.deselectKeyframes();
  311. }
  312. const updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  313. if (kf.id === id) {
  314. kf.selected = !selectedKeyFrame;
  315. }
  316. return kf;
  317. });
  318. this.setState({
  319. svgKeyframes: updatedKeyframes,
  320. actionableKeyframe: frameValue ?? this.state.actionableKeyframe,
  321. });
  322. }
  323. resetActionableKeyframe() {
  324. this.setState({
  325. actionableKeyframe: { frame: undefined, value: undefined },
  326. });
  327. }
  328. selectedControlPoint(type: string, id: string) {
  329. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  330. if (kf.id === id) {
  331. this.setState({ isFlatTangentMode: false });
  332. if (type === 'left') {
  333. kf.isLeftActive = !kf.isLeftActive;
  334. kf.isRightActive = false;
  335. }
  336. if (type === 'right') {
  337. kf.isRightActive = !kf.isRightActive;
  338. kf.isLeftActive = false;
  339. }
  340. }
  341. return kf;
  342. });
  343. this.setState({ svgKeyframes: updatedKeyframes });
  344. }
  345. deselectKeyframes() {
  346. let updatedKeyframes = this.state.svgKeyframes?.map((kf) => {
  347. kf.isLeftActive = false;
  348. kf.isRightActive = false;
  349. kf.selected = false;
  350. return kf;
  351. });
  352. this.setState({
  353. svgKeyframes: updatedKeyframes,
  354. actionableKeyframe: { frame: undefined, value: undefined },
  355. });
  356. }
  357. updateValuePerCoordinate(dataType: number, value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion, newValue: number, coordinate?: number) {
  358. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  359. value = newValue;
  360. }
  361. if (dataType === Animation.ANIMATIONTYPE_VECTOR2) {
  362. switch (coordinate) {
  363. case SelectedCoordinate.x:
  364. (value as Vector2).x = newValue;
  365. break;
  366. case SelectedCoordinate.y:
  367. (value as Vector2).y = newValue;
  368. break;
  369. }
  370. }
  371. if (dataType === Animation.ANIMATIONTYPE_VECTOR3) {
  372. switch (coordinate) {
  373. case SelectedCoordinate.x:
  374. (value as Vector3).x = newValue;
  375. break;
  376. case SelectedCoordinate.y:
  377. (value as Vector3).y = newValue;
  378. break;
  379. case SelectedCoordinate.z:
  380. (value as Vector3).z = newValue;
  381. break;
  382. }
  383. }
  384. if (dataType === Animation.ANIMATIONTYPE_QUATERNION) {
  385. switch (coordinate) {
  386. case SelectedCoordinate.x:
  387. (value as Quaternion).x = newValue;
  388. break;
  389. case SelectedCoordinate.y:
  390. (value as Quaternion).y = newValue;
  391. break;
  392. case SelectedCoordinate.z:
  393. (value as Quaternion).z = newValue;
  394. break;
  395. case SelectedCoordinate.w:
  396. (value as Quaternion).w = newValue;
  397. break;
  398. }
  399. }
  400. if (dataType === Animation.ANIMATIONTYPE_COLOR3) {
  401. switch (coordinate) {
  402. case SelectedCoordinate.r:
  403. (value as Color3).r = newValue;
  404. break;
  405. case SelectedCoordinate.g:
  406. (value as Color3).g = newValue;
  407. break;
  408. case SelectedCoordinate.b:
  409. (value as Color3).b = newValue;
  410. break;
  411. }
  412. }
  413. if (dataType === Animation.ANIMATIONTYPE_COLOR4) {
  414. switch (coordinate) {
  415. case SelectedCoordinate.r:
  416. (value as Color4).r = newValue;
  417. break;
  418. case SelectedCoordinate.g:
  419. (value as Color4).g = newValue;
  420. break;
  421. case SelectedCoordinate.b:
  422. (value as Color4).b = newValue;
  423. break;
  424. case SelectedCoordinate.a:
  425. (value as Color4).a = newValue;
  426. break;
  427. }
  428. }
  429. if (dataType === Animation.ANIMATIONTYPE_SIZE) {
  430. switch (coordinate) {
  431. case SelectedCoordinate.width:
  432. (value as Size).width = newValue;
  433. break;
  434. case SelectedCoordinate.g:
  435. (value as Size).height = newValue;
  436. break;
  437. }
  438. }
  439. return value;
  440. }
  441. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, id: string) {
  442. let animation = this.state.selected as Animation;
  443. const { order: index, coordinate } = this.decodeCurveId(id);
  444. let keys = [...animation.getKeys()];
  445. let newFrame = 0;
  446. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  447. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  448. newFrame = 1;
  449. } else {
  450. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x / this._pixelFrameUnit);
  451. }
  452. }
  453. if (newFrame > keys[index].frame) {
  454. const nextKf = keys[index + 1];
  455. if (nextKf) {
  456. if (nextKf.frame <= newFrame) {
  457. keys[index].frame = keys[index].frame;
  458. } else {
  459. keys[index].frame = newFrame;
  460. }
  461. }
  462. }
  463. if (newFrame < keys[index].frame) {
  464. const prevKf = keys[index - 1];
  465. if (prevKf) {
  466. if (prevKf.frame >= newFrame) {
  467. keys[index].frame = keys[index].frame;
  468. } else {
  469. keys[index].frame = newFrame;
  470. }
  471. }
  472. }
  473. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2; // this value comes inverted svg from 0 = 100 to 100 = 0
  474. const updatedValueInCoordinate = this.updateValuePerCoordinate(animation.dataType, keys[index].value, updatedValue, coordinate);
  475. keys[index].value = updatedValueInCoordinate;
  476. this.updateLeftControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  477. this.updateRightControlPoint(updatedSvgKeyFrame, keys[index], animation.dataType, coordinate);
  478. animation.setKeys(keys);
  479. this.setState({
  480. actionableKeyframe: { frame: newFrame, value: updatedValueInCoordinate },
  481. });
  482. this.selectAnimation(animation, coordinate);
  483. }
  484. updateLeftControlPoint(updatedSvgKeyFrame: IKeyframeSvgPoint, key: IAnimationKey, dataType: number, coordinate: number) {
  485. if (updatedSvgKeyFrame.isLeftActive) {
  486. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  487. // Rotate
  488. let newValue = ((this._heightScale - updatedSvgKeyFrame.leftControlPoint.y) / this._heightScale) * 2;
  489. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  490. let updatedValue = keyframeValue - newValue;
  491. key.inTangent = this.updateValuePerCoordinate(dataType, key.inTangent, updatedValue, coordinate);
  492. if (!this.state.isBrokenMode) {
  493. // Right control point if exists
  494. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  495. // Sets opposite value
  496. key.outTangent = key.inTangent * -1;
  497. }
  498. }
  499. }
  500. }
  501. }
  502. updateRightControlPoint(updatedSvgKeyFrame: IKeyframeSvgPoint, key: IAnimationKey, dataType: number, coordinate: number) {
  503. if (updatedSvgKeyFrame.isRightActive) {
  504. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  505. // Rotate
  506. let newValue = ((this._heightScale - updatedSvgKeyFrame.rightControlPoint.y) / this._heightScale) * 2;
  507. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  508. let updatedValue = keyframeValue - newValue;
  509. key.outTangent = this.updateValuePerCoordinate(dataType, key.outTangent, updatedValue, coordinate);
  510. if (!this.state.isBrokenMode) {
  511. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  512. // Sets opposite value
  513. key.inTangent = key.outTangent * -1;
  514. }
  515. }
  516. }
  517. }
  518. }
  519. handleFrameChange(event: React.ChangeEvent<HTMLInputElement>) {
  520. event.preventDefault();
  521. let frame;
  522. if (event.target.value === '') {
  523. frame = '';
  524. } else {
  525. frame = parseInt(event.target.value);
  526. }
  527. this.setState({
  528. actionableKeyframe: {
  529. frame: frame,
  530. value: this.state.actionableKeyframe.value,
  531. },
  532. });
  533. }
  534. handleValueChange(event: React.ChangeEvent<HTMLInputElement>) {
  535. event.preventDefault();
  536. let value;
  537. if (event.target.value !== undefined) {
  538. if (event.target.value !== '') {
  539. value = parseFloat(event.target.value);
  540. } else {
  541. value = '';
  542. }
  543. this.setState({
  544. actionableKeyframe: {
  545. frame: this.state.actionableKeyframe.frame,
  546. value: value,
  547. },
  548. });
  549. }
  550. }
  551. setKeyframeValue() {
  552. if (this.state.actionableKeyframe.frame !== '' && this.state.actionableKeyframe.frame !== undefined && this.state.actionableKeyframe.value !== '' && this.state.actionableKeyframe.value !== undefined) {
  553. if (this.state.selected !== null) {
  554. let currentSelected = this.state.svgKeyframes?.find((kf) => kf.selected);
  555. if (currentSelected) {
  556. let { order, coordinate } = this.decodeCurveId(currentSelected.id);
  557. let animation = this.state.selected;
  558. let keys = animation.getKeys();
  559. let isKeyframe = keys.find((_, i) => i === order);
  560. if (isKeyframe) {
  561. let updatedKeys = keys.map((k, i) => {
  562. if (i === order) {
  563. k.frame = this.state.actionableKeyframe.frame as number;
  564. const currentValue = this.getValueAsArray(animation.dataType, k.value);
  565. currentValue[coordinate] = this.state.actionableKeyframe.value;
  566. k.value = currentValue.length === 1 ? currentValue[0] : currentValue;
  567. }
  568. return k;
  569. });
  570. this.state.selected.setKeys(updatedKeys);
  571. this.selectAnimation(animation);
  572. }
  573. }
  574. }
  575. }
  576. }
  577. setFlatTangent() {
  578. if (this.state.selected !== null) {
  579. let animation = this.state.selected;
  580. this.setState({ isFlatTangentMode: true }, () => this.selectAnimation(animation));
  581. }
  582. }
  583. // Use this for Bezier curve mode
  584. setTangentMode() {
  585. if (this.state.selected !== null) {
  586. let animation = this.state.selected;
  587. this.setState({ isTangentMode: !this.state.isTangentMode }, () => this.selectAnimation(animation));
  588. }
  589. }
  590. setBrokenMode() {
  591. if (this.state.selected !== null) {
  592. let animation = this.state.selected;
  593. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () => this.selectAnimation(animation));
  594. }
  595. }
  596. setLerpMode() {
  597. if (this.state.selected !== null) {
  598. let animation = this.state.selected;
  599. this.setState({ lerpMode: !this.state.lerpMode }, () => this.selectAnimation(animation));
  600. }
  601. }
  602. addKeyframeClick() {
  603. if (this.state.selected !== null) {
  604. let currentAnimation = this.state.selected;
  605. let keys = currentAnimation.getKeys();
  606. let x = this.state.currentFrame;
  607. let y = this.state.actionableKeyframe.value ?? 1;
  608. // check if value exists...
  609. let arrayValue: any = [];
  610. let emptyValue = this.returnZero(currentAnimation.dataType);
  611. let existValue = keys.find((k) => k.frame === x);
  612. if (existValue !== undefined) {
  613. arrayValue = this.getValueAsArray(currentAnimation.dataType, existValue.value);
  614. } else {
  615. // Set empty if doesn't exist
  616. if (emptyValue) {
  617. arrayValue = this.getValueAsArray(currentAnimation.dataType, emptyValue);
  618. }
  619. }
  620. arrayValue[this.state.selectedCoordinate] = y;
  621. let actualValue = this.setValueAsType(currentAnimation.dataType, arrayValue);
  622. keys.push({
  623. frame: x,
  624. value: actualValue,
  625. inTangent: emptyValue,
  626. outTangent: emptyValue,
  627. });
  628. keys.sort((a, b) => a.frame - b.frame);
  629. currentAnimation.setKeys(keys);
  630. this.selectAnimation(currentAnimation, this.state.selectedCoordinate);
  631. }
  632. }
  633. removeKeyframeClick() {
  634. if (this.state.selected !== null) {
  635. let currentAnimation = this.state.selected;
  636. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  637. let keys = currentAnimation.getKeys();
  638. let x = this.state.currentFrame;
  639. let filteredKeys = keys.filter((kf) => kf.frame !== x);
  640. currentAnimation.setKeys(filteredKeys);
  641. this.selectAnimation(currentAnimation);
  642. }
  643. }
  644. }
  645. removeKeyframes(points: IKeyframeSvgPoint[]) {
  646. if (this.state.selected !== null) {
  647. let currentAnimation = this.state.selected;
  648. const indexesToRemove = points.map((p) => {
  649. return {
  650. index: parseInt(p.id.split('_')[3]),
  651. coordinate: parseInt(p.id.split('_')[2]),
  652. };
  653. });
  654. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  655. let keys = currentAnimation.getKeys();
  656. let filteredKeys = keys.filter((_, i) => {
  657. return !indexesToRemove.find((x) => x.index === i);
  658. });
  659. currentAnimation.setKeys(filteredKeys);
  660. this.deselectKeyframes();
  661. this.selectAnimation(currentAnimation);
  662. }
  663. }
  664. }
  665. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  666. event.preventDefault();
  667. if (this.state.selected !== null) {
  668. var svg = event.target as SVGSVGElement;
  669. var pt = svg.createSVGPoint();
  670. pt.x = event.clientX;
  671. pt.y = event.clientY;
  672. var inverse = svg.getScreenCTM()?.inverse();
  673. var cursorpt = pt.matrixTransform(inverse);
  674. var currentAnimation = this.state.selected;
  675. var keys = currentAnimation.getKeys();
  676. var height = 100;
  677. var middle = height / 2;
  678. var keyValue;
  679. if (cursorpt.y < middle) {
  680. keyValue = 1 + (100 / cursorpt.y) * 0.1;
  681. }
  682. if (cursorpt.y > middle) {
  683. keyValue = 1 - (100 / cursorpt.y) * 0.1;
  684. }
  685. keys.push({ frame: cursorpt.x, value: keyValue });
  686. currentAnimation.setKeys(keys);
  687. this.selectAnimation(currentAnimation);
  688. }
  689. }
  690. /**
  691. * Curve Rendering Functions
  692. * This section handles how to render curves.
  693. */
  694. linearInterpolation(keyframes: IAnimationKey[], data: string, middle: number): string {
  695. keyframes.forEach((key, i) => {
  696. // identify type of value and split...
  697. var point = new Vector2(0, 0);
  698. point.x = key.frame * this._pixelFrameUnit;
  699. point.y = this._heightScale - key.value * middle;
  700. this.setKeyframePointLinear(point, i);
  701. if (i !== 0) {
  702. data += ` L${point.x} ${point.y}`;
  703. }
  704. });
  705. return data;
  706. }
  707. setKeyframePointLinear(point: Vector2, index: number) {
  708. // here set the ID to a unique id
  709. let svgKeyframe = {
  710. keyframePoint: point,
  711. rightControlPoint: null,
  712. leftControlPoint: null,
  713. id: index.toString(),
  714. selected: false,
  715. isLeftActive: false,
  716. isRightActive: false,
  717. };
  718. this._svgKeyframes.push(svgKeyframe);
  719. }
  720. flatTangents(keyframes: IAnimationKey[], dataType: number) {
  721. // Checks if Flat Tangent is active (tangents are set to zero)
  722. let flattened;
  723. if (this.state && this.state.isFlatTangentMode) {
  724. flattened = keyframes.map((kf) => {
  725. if (kf.inTangent !== undefined) {
  726. kf.inTangent = this.returnZero(dataType);
  727. }
  728. if (kf.outTangent !== undefined) {
  729. kf.outTangent = this.returnZero(dataType);
  730. }
  731. return kf;
  732. });
  733. } else {
  734. flattened = keyframes;
  735. }
  736. this.setState({ isFlatTangentMode: false });
  737. return flattened;
  738. }
  739. returnZero(dataType: number) {
  740. switch (dataType) {
  741. case Animation.ANIMATIONTYPE_FLOAT:
  742. return 0;
  743. case Animation.ANIMATIONTYPE_VECTOR3:
  744. return Vector3.Zero();
  745. case Animation.ANIMATIONTYPE_VECTOR2:
  746. return Vector2.Zero();
  747. case Animation.ANIMATIONTYPE_QUATERNION:
  748. return Quaternion.Zero();
  749. case Animation.ANIMATIONTYPE_COLOR3:
  750. return new Color3(0, 0, 0);
  751. case Animation.ANIMATIONTYPE_COLOR4:
  752. return new Color4(0, 0, 0, 0);
  753. case Animation.ANIMATIONTYPE_SIZE:
  754. return new Size(0, 0);
  755. default:
  756. return 0;
  757. }
  758. }
  759. getValueAsArray(valueType: number, value: number | Vector2 | Vector3 | Color3 | Color4 | Size | Quaternion) {
  760. switch (valueType) {
  761. case Animation.ANIMATIONTYPE_FLOAT:
  762. return [value as number];
  763. case Animation.ANIMATIONTYPE_VECTOR3:
  764. return (value as Vector3).asArray();
  765. case Animation.ANIMATIONTYPE_VECTOR2:
  766. return (value as Vector2).asArray();
  767. case Animation.ANIMATIONTYPE_QUATERNION:
  768. return (value as Quaternion).asArray();
  769. case Animation.ANIMATIONTYPE_COLOR3:
  770. return (value as Color3).asArray();
  771. case Animation.ANIMATIONTYPE_COLOR4:
  772. return (value as Color4).asArray();
  773. case Animation.ANIMATIONTYPE_SIZE:
  774. return [(value as Size).width, (value as Size).height];
  775. default:
  776. return [];
  777. }
  778. }
  779. setValueAsType(valueType: number, arrayValue: number[]) {
  780. switch (valueType) {
  781. case Animation.ANIMATIONTYPE_FLOAT:
  782. return arrayValue[0];
  783. case Animation.ANIMATIONTYPE_VECTOR3:
  784. return new Vector3(arrayValue[0], arrayValue[1], arrayValue[2]);
  785. case Animation.ANIMATIONTYPE_VECTOR2:
  786. return new Vector2(arrayValue[0], arrayValue[1]);
  787. case Animation.ANIMATIONTYPE_QUATERNION:
  788. return new Quaternion(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  789. case Animation.ANIMATIONTYPE_COLOR3:
  790. return new Color3(arrayValue[0], arrayValue[1], arrayValue[2]);
  791. case Animation.ANIMATIONTYPE_COLOR4:
  792. return new Color4(arrayValue[0], arrayValue[1], arrayValue[2], arrayValue[3]);
  793. case Animation.ANIMATIONTYPE_SIZE:
  794. return new Size(arrayValue[0], arrayValue[1]);
  795. default:
  796. return arrayValue[0];
  797. }
  798. }
  799. getPathData(animation: Animation | null) {
  800. if (animation === null) {
  801. return undefined;
  802. }
  803. var keyframes = animation.getKeys();
  804. if (keyframes === undefined) {
  805. return undefined;
  806. } else {
  807. const { easingMode, easingType, usesTangents, valueType, highestFrame, name, targetProperty } = this.getAnimationData(animation);
  808. keyframes = this.flatTangents(keyframes, valueType);
  809. const startKey = keyframes[0];
  810. let middle = this._heightScale / 2;
  811. let collection: ICurveData[] = [];
  812. const colors = ['red', 'green', 'blue', 'white', '#7a4ece'];
  813. const startValue = this.getValueAsArray(valueType, startKey.value);
  814. for (var d = 0; d < startValue.length; d++) {
  815. const id = `${name}_${targetProperty}_${d}`;
  816. const curveColor = valueType === Animation.ANIMATIONTYPE_FLOAT ? colors[4] : colors[d];
  817. // START OF LINE/CURVE
  818. let data: string | undefined = `M${startKey.frame * this._pixelFrameUnit}, ${this._heightScale - startValue[d] * middle}`; //
  819. if (this.state) {
  820. if (usesTangents) {
  821. data = this.curvePathWithTangents(keyframes, data, middle, valueType, d, id);
  822. } else {
  823. if (easingType !== undefined && easingMode !== undefined) {
  824. let easingFunction = animation.getEasingFunction();
  825. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction);
  826. } else {
  827. if (this.state !== undefined) {
  828. let emptyTangents = keyframes.map((kf, i) => {
  829. if (i === 0) {
  830. kf.outTangent = this.returnZero(valueType);
  831. } else if (i === keyframes.length - 1) {
  832. kf.inTangent = this.returnZero(valueType);
  833. } else {
  834. kf.inTangent = this.returnZero(valueType);
  835. kf.outTangent = this.returnZero(valueType);
  836. }
  837. return kf;
  838. });
  839. data = this.curvePathWithTangents(emptyTangents, data, middle, valueType, d, id);
  840. }
  841. }
  842. }
  843. }
  844. collection.push({
  845. pathData: data,
  846. pathLength: highestFrame,
  847. domCurve: React.createRef(),
  848. color: curveColor,
  849. id: id,
  850. });
  851. }
  852. return collection;
  853. }
  854. }
  855. getAnimationData(animation: Animation) {
  856. // General Props
  857. let loopMode = animation.loopMode;
  858. let name = animation.name;
  859. let blendingSpeed = animation.blendingSpeed;
  860. let targetProperty = animation.targetProperty;
  861. let targetPropertyPath = animation.targetPropertyPath;
  862. let framesPerSecond = animation.framePerSecond;
  863. let highestFrame = animation.getHighestFrame();
  864. //let serialized = animation.serialize();
  865. let usesTangents = animation.getKeys().find((kf) => kf.hasOwnProperty('inTangent') || kf.hasOwnProperty('outTangent')) !== undefined ? true : false;
  866. let valueType = animation.dataType;
  867. // easing properties
  868. let easingType, easingMode;
  869. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  870. if (easingFunction === undefined) {
  871. easingType = undefined;
  872. easingMode = undefined;
  873. } else {
  874. easingType = easingFunction.constructor.name;
  875. easingMode = easingFunction.getEasingMode();
  876. }
  877. return {
  878. loopMode,
  879. name,
  880. blendingSpeed,
  881. targetPropertyPath,
  882. targetProperty,
  883. framesPerSecond,
  884. highestFrame,
  885. usesTangents,
  886. easingType,
  887. easingMode,
  888. valueType,
  889. };
  890. }
  891. curvePathWithTangents(keyframes: IAnimationKey[], data: string, middle: number, type: number, coordinate: number, animationName: string) {
  892. keyframes.forEach((key, i) => {
  893. // Create a unique id for curve
  894. const curveId = this.encodeCurveId(animationName, i);
  895. // identify type of value and split...
  896. const keyframe_valueAsArray = this.getValueAsArray(type, key.value)[coordinate];
  897. let svgKeyframe;
  898. let outTangent;
  899. let inTangent;
  900. let defaultWeight = 5;
  901. let defaultTangent: number | null = null;
  902. if (i !== 0 || i !== keyframes.length - 1) {
  903. defaultTangent = 0;
  904. }
  905. var inT = key.inTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.inTangent)[coordinate];
  906. var outT = key.outTangent === undefined ? defaultTangent : this.getValueAsArray(type, key.outTangent)[coordinate];
  907. let y = this._heightScale - keyframe_valueAsArray * middle;
  908. if (inT !== null) {
  909. let valueIn = y * inT + y;
  910. inTangent = new Vector2(key.frame * this._pixelFrameUnit - defaultWeight, valueIn);
  911. } else {
  912. inTangent = null;
  913. }
  914. if (outT !== null) {
  915. let valueOut = y * outT + y;
  916. outTangent = new Vector2(key.frame * this._pixelFrameUnit + defaultWeight, valueOut);
  917. } else {
  918. outTangent = null;
  919. }
  920. if (i === 0) {
  921. svgKeyframe = {
  922. keyframePoint: new Vector2(key.frame * this._pixelFrameUnit, this._heightScale - keyframe_valueAsArray * middle),
  923. rightControlPoint: outTangent,
  924. leftControlPoint: null,
  925. id: curveId,
  926. selected: false,
  927. isLeftActive: false,
  928. isRightActive: false,
  929. };
  930. if (outTangent !== null) {
  931. data += ` C${outTangent.x} ${outTangent.y} `;
  932. }
  933. } else {
  934. svgKeyframe = {
  935. keyframePoint: new Vector2(key.frame * this._pixelFrameUnit, this._heightScale - keyframe_valueAsArray * middle),
  936. rightControlPoint: outTangent,
  937. leftControlPoint: inTangent,
  938. id: curveId,
  939. selected: false,
  940. isLeftActive: false,
  941. isRightActive: false,
  942. };
  943. if (outTangent !== null && inTangent !== null) {
  944. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y} `;
  945. } else if (inTangent !== null) {
  946. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `;
  947. }
  948. }
  949. if (this.state) {
  950. let prev = this.state.svgKeyframes?.find((kf) => kf.id === curveId);
  951. if (prev) {
  952. svgKeyframe.isLeftActive = prev?.isLeftActive;
  953. svgKeyframe.isRightActive = prev?.isRightActive;
  954. svgKeyframe.selected = prev?.selected;
  955. }
  956. }
  957. this._svgKeyframes.push(svgKeyframe);
  958. }, this);
  959. return data;
  960. }
  961. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  962. // This will get 1/4 and 3/4 of points in eased curve
  963. const u = 0.25;
  964. const v = 0.75;
  965. keyframes.forEach((key, i) => {
  966. // identify type of value and split...
  967. // Gets previous initial point of curve segment
  968. var pointA = new Vector2(0, 0);
  969. if (i === 0) {
  970. pointA.x = key.frame;
  971. pointA.y = this._heightScale - key.value * middle;
  972. this.setKeyframePoint([pointA], i, keyframes.length);
  973. } else {
  974. pointA.x = keyframes[i - 1].frame;
  975. pointA.y = this._heightScale - keyframes[i - 1].value * middle;
  976. // Gets the end point of this curve segment
  977. var pointB = new Vector2(key.frame, this._heightScale - key.value * middle);
  978. // Get easing value of percentage to get the bezier control points below
  979. 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)
  980. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  981. // Direction of curve up/down
  982. let yInt25 = 0;
  983. if (pointB.y > pointA.y) {
  984. // if pointB.y > pointA.y = goes down
  985. yInt25 = (pointB.y - pointA.y) * du + pointA.y;
  986. } else if (pointB.y < pointA.y) {
  987. // if pointB.y < pointA.y = goes up
  988. yInt25 = pointA.y - (pointA.y - pointB.y) * du;
  989. }
  990. let yInt75 = 0;
  991. if (pointB.y > pointA.y) {
  992. yInt75 = (pointB.y - pointA.y) * dv + pointA.y;
  993. } else if (pointB.y < pointA.y) {
  994. yInt75 = pointA.y - (pointA.y - pointB.y) * dv;
  995. }
  996. // Intermediate points in curve
  997. let intermediatePoint25 = new Vector2((pointB.x - pointA.x) * u + pointA.x, yInt25);
  998. let intermediatePoint75 = new Vector2((pointB.x - pointA.x) * v + pointA.x, yInt75);
  999. // Gets the four control points of bezier curve
  1000. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  1001. if (controlPoints !== undefined) {
  1002. this.setKeyframePoint(controlPoints, i, keyframes.length);
  1003. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`;
  1004. }
  1005. }
  1006. });
  1007. return data;
  1008. }
  1009. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  1010. let svgKeyframe;
  1011. if (index === 0) {
  1012. svgKeyframe = {
  1013. keyframePoint: controlPoints[0],
  1014. rightControlPoint: null,
  1015. leftControlPoint: null,
  1016. id: index.toString(),
  1017. selected: false,
  1018. isLeftActive: false,
  1019. isRightActive: false,
  1020. };
  1021. } else {
  1022. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  1023. svgKeyframe = {
  1024. keyframePoint: controlPoints[3],
  1025. rightControlPoint: null,
  1026. leftControlPoint: controlPoints[2],
  1027. id: index.toString(),
  1028. selected: false,
  1029. isLeftActive: false,
  1030. isRightActive: false,
  1031. };
  1032. }
  1033. this._svgKeyframes.push(svgKeyframe);
  1034. }
  1035. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v: number, p3: Vector2): Vector2[] | undefined {
  1036. let a = 0.0;
  1037. let b = 0.0;
  1038. let c = 0.0;
  1039. let d = 0.0;
  1040. let det = 0.0;
  1041. let q1: Vector2 = new Vector2();
  1042. let q2: Vector2 = new Vector2();
  1043. let controlA: Vector2 = p0;
  1044. let controlB: Vector2 = new Vector2();
  1045. let controlC: Vector2 = new Vector2();
  1046. let controlD: Vector2 = p3;
  1047. if (u <= 0.0 || u >= 1.0 || v <= 0.0 || v >= 1.0 || u >= v) {
  1048. return undefined;
  1049. }
  1050. a = 3 * (1 - u) * (1 - u) * u;
  1051. b = 3 * (1 - u) * u * u;
  1052. c = 3 * (1 - v) * (1 - v) * v;
  1053. d = 3 * (1 - v) * v * v;
  1054. det = a * d - b * c;
  1055. if (det == 0.0) return undefined;
  1056. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  1057. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  1058. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  1059. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  1060. controlB.x = (d * q1.x - b * q2.x) / det;
  1061. controlB.y = (d * q1.y - b * q2.y) / det;
  1062. controlC.x = (-c * q1.x + a * q2.x) / det;
  1063. controlC.y = (-c * q1.y + a * q2.y) / det;
  1064. return [controlA, controlB, controlC, controlD];
  1065. }
  1066. deselectAnimation() {
  1067. this.setState({
  1068. selected: null,
  1069. svgKeyframes: [],
  1070. selectedPathData: [],
  1071. selectedCoordinate: 0,
  1072. });
  1073. }
  1074. /**
  1075. * Core functions
  1076. * This section handles main Curve Editor Functions.
  1077. */
  1078. selectAnimation(animation: Animation, coordinate?: SelectedCoordinate) {
  1079. this._svgKeyframes = [];
  1080. let updatedPath;
  1081. let filteredSvgKeys;
  1082. let selectedCurve = 0;
  1083. if (coordinate === undefined) {
  1084. this.stopAnimation();
  1085. updatedPath = this.getPathData(animation);
  1086. } else {
  1087. let curves = this.getPathData(animation);
  1088. updatedPath = [];
  1089. filteredSvgKeys = this._svgKeyframes?.filter((curve) => {
  1090. let id = parseInt(curve.id.split('_')[2]);
  1091. if (id === coordinate) {
  1092. return true;
  1093. } else {
  1094. return false;
  1095. }
  1096. });
  1097. curves?.map((curve) => {
  1098. let id = parseInt(curve.id.split('_')[2]);
  1099. if (id === coordinate) {
  1100. updatedPath.push(curve);
  1101. }
  1102. });
  1103. selectedCurve = coordinate;
  1104. }
  1105. // check for empty svgKeyframes, lastframe, selected
  1106. this.setState({
  1107. selected: animation,
  1108. svgKeyframes: coordinate !== undefined ? filteredSvgKeys : this._svgKeyframes,
  1109. selectedPathData: updatedPath,
  1110. selectedCoordinate: selectedCurve,
  1111. fps: animation.framePerSecond,
  1112. });
  1113. }
  1114. isAnimationPlaying() {
  1115. let target = this.props.entity;
  1116. if (this.props.entity instanceof TargetedAnimation) {
  1117. target = this.props.entity.target;
  1118. }
  1119. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1120. }
  1121. stopAnimation() {
  1122. let target = this.props.entity;
  1123. if (this.props.entity instanceof TargetedAnimation) {
  1124. target = this.props.entity.target;
  1125. }
  1126. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  1127. if (this._isPlaying) {
  1128. this.props.playOrPause && this.props.playOrPause();
  1129. }
  1130. }
  1131. setIsLooping() {
  1132. this.setState({ isLooping: !this.state.isLooping, isPlaying: false }, () => this.stopAnimation());
  1133. }
  1134. setFramesPerSecond(fps: number) {
  1135. this.setState({ fps: fps, isPlaying: false }, () => this.stopAnimation());
  1136. }
  1137. analizeAnimationForLerp(animation: Animation | null) {
  1138. if (animation !== null) {
  1139. const { easingMode, easingType, usesTangents } = this.getAnimationData(animation);
  1140. if (easingType === undefined && easingMode === undefined && !usesTangents) {
  1141. return true;
  1142. } else {
  1143. return false;
  1144. }
  1145. } else {
  1146. return false;
  1147. }
  1148. }
  1149. /**
  1150. * Timeline
  1151. * This section controls the timeline.
  1152. */
  1153. changeCurrentFrame(frame: number) {
  1154. let currentValue;
  1155. this.stopAnimation();
  1156. if (this.state.selectedPathData) {
  1157. let selectedCurve = this.state.selectedPathData[this.state.selectedCoordinate].domCurve.current;
  1158. if (selectedCurve) {
  1159. var curveLength = selectedCurve.getTotalLength();
  1160. let frameValue = (frame * curveLength) / 100;
  1161. let currentP = selectedCurve.getPointAtLength(frameValue);
  1162. let middle = this._heightScale / 2;
  1163. let offset = (currentP?.y * this._heightScale - this._heightScale ** 2 / 2) / middle / this._heightScale;
  1164. let unit = Math.sign(offset);
  1165. currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  1166. this.setState({
  1167. currentFrame: frame,
  1168. currentValue: currentValue,
  1169. currentPoint: currentP,
  1170. isPlaying: false,
  1171. });
  1172. }
  1173. }
  1174. }
  1175. setCanvasPosition(frame: number) {
  1176. this.setState({ panningX: (frame - 10) * 10, repositionCanvas: true });
  1177. }
  1178. setCurrentFrame(direction: number) {
  1179. this.setState({
  1180. currentFrame: this.state.currentFrame + direction,
  1181. });
  1182. }
  1183. changeAnimationLimit(limit: number) {
  1184. this.setState({
  1185. animationLimit: limit,
  1186. });
  1187. }
  1188. updateFrameInKeyFrame(frame: number, index: number) {
  1189. if (this.state && this.state.selected) {
  1190. let animation = this.state.selected;
  1191. let keys = [...animation.getKeys()];
  1192. keys[index].frame = frame;
  1193. animation.setKeys(keys);
  1194. this.selectAnimation(animation);
  1195. }
  1196. }
  1197. playPause(direction: number) {
  1198. this.registerObs();
  1199. if (this.state.selected) {
  1200. let target = this.props.entity;
  1201. if (this.props.entity instanceof TargetedAnimation) {
  1202. target = this.props.entity.target;
  1203. }
  1204. if (this.state.isPlaying && direction === 0) {
  1205. this.props.scene.stopAnimation(target);
  1206. this.setState({ isPlaying: false });
  1207. this._isPlaying = false;
  1208. this.forceUpdate();
  1209. } else {
  1210. if (this.state.isPlaying) {
  1211. this.props.scene.stopAnimation(target);
  1212. }
  1213. let keys = this.state.selected.getKeys();
  1214. let firstFrame = keys[0].frame;
  1215. let LastFrame = this.state.selected.getHighestFrame();
  1216. if (direction === 1) {
  1217. this._mainAnimatable = this.props.scene.beginAnimation(target, firstFrame, LastFrame, this.state.isLooping, this.state.fps);
  1218. console.log(this._mainAnimatable);
  1219. console.log(`${target}, ${firstFrame}, ${LastFrame}, ${this.state.isLooping}, ${this.state.fps}`);
  1220. }
  1221. if (direction === -1) {
  1222. this._mainAnimatable = this.props.scene.beginAnimation(target, LastFrame, firstFrame, this.state.isLooping, this.state.fps);
  1223. }
  1224. this._isPlaying = true;
  1225. this.setState({ isPlaying: true });
  1226. this.forceUpdate();
  1227. }
  1228. }
  1229. }
  1230. moveFrameTo(e: React.MouseEvent<SVGRectElement, MouseEvent>) {
  1231. this.stopAnimation();
  1232. var svg = e.currentTarget as SVGRectElement;
  1233. var CTM = svg.getScreenCTM();
  1234. let position;
  1235. if (CTM) {
  1236. position = new Vector2((e.clientX - CTM.e) / CTM.a, (e.clientY - CTM.f) / CTM.d);
  1237. let selectedFrame = Math.round(position.x / this._pixelFrameUnit);
  1238. this.setState({ currentFrame: selectedFrame, isPlaying: false });
  1239. }
  1240. }
  1241. registerObs() {
  1242. this._onBeforeRenderObserver = this.props.scene.onBeforeRenderObservable.add(() => {
  1243. if (!this._isPlaying || !this._mainAnimatable) {
  1244. return;
  1245. }
  1246. this.setState({
  1247. currentFrame: Math.round(this._mainAnimatable.masterFrame),
  1248. });
  1249. });
  1250. }
  1251. componentWillUnmount() {
  1252. if (this._onBeforeRenderObserver) {
  1253. this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  1254. this._onBeforeRenderObserver = null;
  1255. }
  1256. }
  1257. isCurrentFrame(frame: number) {
  1258. return this.state.currentFrame === frame;
  1259. }
  1260. render() {
  1261. return (
  1262. <div id="animation-curve-editor">
  1263. <Notification message={this.state.notification} open={this.state.notification !== '' ? true : false} close={() => this.clearNotification()} />
  1264. <GraphActionsBar
  1265. setKeyframeValue={() => this.setKeyframeValue()}
  1266. enabled={this.state.selected === null || this.state.selected === undefined ? false : true}
  1267. title={this._entityName}
  1268. close={this.props.close}
  1269. actionableKeyframe={this.state.actionableKeyframe}
  1270. handleFrameChange={(e) => this.handleFrameChange(e)}
  1271. handleValueChange={(e) => this.handleValueChange(e)}
  1272. addKeyframe={() => this.addKeyframeClick()}
  1273. removeKeyframe={() => this.removeKeyframeClick()}
  1274. brokenMode={this.state.isBrokenMode}
  1275. brokeTangents={() => this.setBrokenMode()}
  1276. lerpMode={this.state.lerpMode}
  1277. setLerpMode={() => this.setLerpMode()}
  1278. flatTangent={() => this.setFlatTangent()}
  1279. />
  1280. <div className="content">
  1281. <div className="row">
  1282. <EditorControls
  1283. deselectAnimation={() => this.deselectAnimation()}
  1284. selectAnimation={(animation: Animation, axis?: SelectedCoordinate) => this.selectAnimation(animation, axis)}
  1285. isTargetedAnimation={this._isTargetedAnimation}
  1286. entity={this.props.entity}
  1287. selected={this.state.selected}
  1288. lockObject={this.props.lockObject}
  1289. setNotificationMessage={(message: string) => {
  1290. this.setState({ notification: message });
  1291. }}
  1292. globalState={this.props.globalState}
  1293. snippetServer={this._snippetUrl}
  1294. fps={this.state.fps}
  1295. setFps={(fps: number) => this.setFramesPerSecond(fps)}
  1296. setIsLooping={() => this.setIsLooping()}
  1297. />
  1298. <div ref={this._graphCanvas} className="graph-chart" onWheel={(e) => this.zoom(e)}>
  1299. <ScaleLabel current={this.state.valueScale} />
  1300. {this.state.svgKeyframes && (
  1301. <SvgDraggableArea
  1302. ref={this._svgCanvas}
  1303. selectKeyframe={(id: string, multiselect: boolean) => this.selectKeyframe(id, multiselect)}
  1304. viewBoxScale={this.state.frameAxisLength.length}
  1305. scale={this.state.scale}
  1306. keyframeSvgPoints={this.state.svgKeyframes}
  1307. removeSelectedKeyframes={(points: IKeyframeSvgPoint[]) => this.removeKeyframes(points)}
  1308. selectedControlPoint={(type: string, id: string) => this.selectedControlPoint(type, id)}
  1309. deselectKeyframes={() => this.deselectKeyframes()}
  1310. updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint, id: string) => this.renderPoints(updatedSvgKeyFrame, id)}
  1311. panningY={(panningY: number) => {
  1312. this.setState({ panningY: panningY });
  1313. }}
  1314. panningX={(panningX: number) => {
  1315. this.setState({ panningX: panningX });
  1316. }}
  1317. setCurrentFrame={(direction: number) => this.setCurrentFrame(direction)}
  1318. positionCanvas={this.state.panningX}
  1319. repositionCanvas={this.state.repositionCanvas}
  1320. canvasPositionEnded={() => this.setState({ repositionCanvas: false })}
  1321. resetActionableKeyframe={() => this.resetActionableKeyframe()}
  1322. >
  1323. {/* Multiple Curves */}
  1324. {this.state.selectedPathData?.map((curve, i) => (
  1325. <path
  1326. key={i}
  1327. ref={curve.domCurve}
  1328. pathLength={curve.pathLength}
  1329. id="curve"
  1330. d={curve.pathData}
  1331. style={{
  1332. stroke: curve.color,
  1333. fill: 'none',
  1334. strokeWidth: '0.5',
  1335. }}
  1336. ></path>
  1337. ))}
  1338. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1339. return (
  1340. <text
  1341. key={`value_inline_${i}`}
  1342. x={this.state.panningX - 5}
  1343. y={line.value}
  1344. dx="2"
  1345. textAnchor="middle"
  1346. dy="-1"
  1347. style={{
  1348. fontSize: `${0.18 * this.state.scale}em`,
  1349. fontWeight: 'bold',
  1350. textAlign: 'center',
  1351. }}
  1352. >
  1353. {line.label}
  1354. </text>
  1355. );
  1356. })}
  1357. {this.setValueLines(this.state.valueScale).map((line, i) => {
  1358. return <line key={i} x1={-((this.state.frameAxisLength.length * 10) / 2)} y1={line.value} x2={this.state.frameAxisLength.length * 10} y2={line.value}></line>;
  1359. })}
  1360. <rect onClick={(e) => this.moveFrameTo(e)} x={-((this.state.frameAxisLength.length * 10) / 2)} y={90 + this.state.panningY + '%'} width={this.state.frameAxisLength.length * 10} height="10%" fill="#222" style={{ cursor: 'pointer' }}></rect>
  1361. {this.state.frameAxisLength.map((f, i) => (
  1362. <svg key={i} x="0" y={96 + this.state.panningY + '%'} className="frame-contain">
  1363. <text x={f.value} y="0" dx="2px" style={{ fontSize: `${0.17 * this.state.scale}em` }}>
  1364. {f.label}
  1365. </text>
  1366. <line x1={f.value} y1="0" x2={f.value} y2="5%"></line>
  1367. {f.value % this.state.fps === 0 && f.value !== 0 ? <line x1={f.value} y1="-100%" x2={f.value} y2="5%"></line> : null}
  1368. {this.isCurrentFrame(f.label) ? (
  1369. <svg>
  1370. <line
  1371. x1={f.value}
  1372. y1="0"
  1373. x2={f.value}
  1374. y2="-100%"
  1375. style={{
  1376. stroke: 'white',
  1377. strokeWidth: 0.4,
  1378. }}
  1379. />
  1380. <svg x={f.value} y="-1">
  1381. <circle className="svg-playhead" cx="0" cy="0" r="2%" fill="white" />
  1382. <text
  1383. x="0"
  1384. y="1%"
  1385. textAnchor="middle"
  1386. style={{
  1387. fontSize: `${0.17 * this.state.scale}em`,
  1388. pointerEvents: 'none',
  1389. fontWeight: 600,
  1390. }}
  1391. >
  1392. {f.label}
  1393. </text>
  1394. </svg>
  1395. </svg>
  1396. ) : null}
  1397. </svg>
  1398. ))}
  1399. </SvgDraggableArea>
  1400. )}
  1401. </div>
  1402. </div>
  1403. <div className="row-bottom">
  1404. <Timeline
  1405. currentFrame={this.state.currentFrame}
  1406. playPause={(direction: number) => this.playPause(direction)}
  1407. isPlaying={this.state.isPlaying}
  1408. dragKeyframe={(frame: number, index: number) => this.updateFrameInKeyFrame(frame, index)}
  1409. onCurrentFrameChange={(frame: number) => this.changeCurrentFrame(frame)}
  1410. onAnimationLimitChange={(limit: number) => this.changeAnimationLimit(limit)}
  1411. animationLimit={this.state.animationLimit}
  1412. keyframes={this.state.selected && this.state.selected.getKeys()}
  1413. selected={this.state.selected && this.state.selected.getKeys()[0]}
  1414. fps={this.state.fps}
  1415. repositionCanvas={(frame: number) => this.setCanvasPosition(frame)}
  1416. ></Timeline>
  1417. </div>
  1418. </div>
  1419. </div>
  1420. );
  1421. }
  1422. }