animationCurveEditorComponent.tsx 58 KB

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