animationCurveEditorComponent.tsx 45 KB

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