animationCurveEditorComponent.tsx 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  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 { Size } from 'babylonjs/Maths/math.size';
  5. import { Color3, Color4 } from 'babylonjs/Maths/math.color';
  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 { ButtonLineComponent } from '../../../lines/buttonLineComponent';
  16. import { IAnimatable } from 'babylonjs/Animations/animatable.interface';
  17. import { TargetedAnimation } from "babylonjs/Animations/animationGroup";
  18. import { Nullable } from 'babylonjs/types';
  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. export class AnimationCurveEditorComponent extends React.Component<IAnimationCurveEditorComponentProps, {
  31. animationName: string,
  32. animationType: string,
  33. animationTargetProperty: string,
  34. isOpen: boolean,
  35. selected: Animation | null,
  36. currentPathData: string | undefined,
  37. svgKeyframes: IKeyframeSvgPoint[] | undefined,
  38. currentFrame: number,
  39. currentValue: number,
  40. frameAxisLength: ICanvasAxis[],
  41. valueAxisLength: ICanvasAxis[],
  42. isFlatTangentMode: boolean,
  43. isTangentMode: boolean,
  44. isBrokenMode: boolean,
  45. lerpMode: boolean,
  46. scale: number,
  47. playheadOffset: number,
  48. notification: string,
  49. currentPoint: SVGPoint | undefined,
  50. lastFrame: number,
  51. playheadPos: number,
  52. isPlaying: boolean
  53. }> {
  54. // Height scale *Review this functionaliy
  55. private _heightScale: number = 100;
  56. // Canvas Length *Review this functionality
  57. readonly _entityName: string;
  58. readonly _canvasLength: number = 20;
  59. private _svgKeyframes: IKeyframeSvgPoint[] = [];
  60. private _frames: Vector2[] = [];
  61. private _isPlaying: boolean = false;
  62. private _graphCanvas: React.RefObject<HTMLDivElement>;
  63. private _selectedCurve: React.RefObject<SVGPathElement>;
  64. private _svgCanvas: React.RefObject<SvgDraggableArea>;
  65. private _isTargetedAnimation: boolean;
  66. constructor(props: IAnimationCurveEditorComponentProps) {
  67. super(props);
  68. this._entityName = (this.props.entity as any).id;
  69. // Review is we really need this refs
  70. this._graphCanvas = React.createRef();
  71. this._selectedCurve = React.createRef();
  72. this._svgCanvas = React.createRef();
  73. console.log(this.props.entity instanceof TargetedAnimation)
  74. let initialSelection;
  75. let initialPathData;
  76. let initialLerpMode;
  77. if (this.props.entity instanceof TargetedAnimation) {
  78. this._isTargetedAnimation = true;
  79. initialSelection = this.props.entity.animation;
  80. initialLerpMode = initialSelection !== undefined ? this.analizeAnimation(initialSelection) : false;
  81. initialPathData = initialSelection !== undefined ? this.getPathData(initialSelection) : "";
  82. } else {
  83. this._isTargetedAnimation = false;
  84. let hasAnimations = this.props.entity.animations !== undefined || this.props.entity.animations !== null ? this.props.entity.animations : false;
  85. initialSelection = hasAnimations !== false ? hasAnimations && hasAnimations[0] : null;
  86. initialLerpMode = initialSelection !== undefined ? this.analizeAnimation(this.props.entity.animations && initialSelection) : false;
  87. initialPathData = initialSelection && this.getPathData(initialSelection);
  88. initialPathData = initialPathData === null || initialPathData === undefined ? "" : initialPathData;
  89. }
  90. // will update this until we have a top scroll/zoom feature
  91. let valueInd = [2, 1.8, 1.6, 1.4, 1.2, 1, 0.8, 0.6, 0.4, 0.2, 0];
  92. this.state = {
  93. selected: initialSelection,
  94. isOpen: true,
  95. currentPathData: initialPathData,
  96. svgKeyframes: this._svgKeyframes,
  97. animationTargetProperty: 'position.x',
  98. animationName: "",
  99. animationType: "Float",
  100. currentFrame: 0,
  101. currentValue: 1,
  102. isFlatTangentMode: false,
  103. isTangentMode: false,
  104. isBrokenMode: false,
  105. lerpMode: initialLerpMode,
  106. playheadOffset: this._graphCanvas.current ? (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10) : 0,
  107. frameAxisLength: (new Array(this._canvasLength)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } }),
  108. valueAxisLength: (new Array(10)).fill(0).map((s, i) => { return { value: i * 10, label: valueInd[i] } }),
  109. notification: "",
  110. lastFrame: 0,
  111. currentPoint: undefined,
  112. scale: 1,
  113. playheadPos: 0,
  114. isPlaying: this.isAnimationPlaying()
  115. }
  116. }
  117. componentDidMount() {
  118. setTimeout(() => this.resetPlayheadOffset(), 500);
  119. }
  120. /**
  121. * Notifications
  122. * To add notification we set the state and clear to make the notification bar hide.
  123. */
  124. clearNotification() {
  125. this.setState({ notification: "" });
  126. }
  127. /**
  128. * Zoom and Scroll
  129. * This section handles zoom and scroll
  130. * of the graph area.
  131. */
  132. zoom(e: React.WheelEvent<HTMLDivElement>) {
  133. e.nativeEvent.stopImmediatePropagation();
  134. console.log(e.deltaY);
  135. let scaleX = 1;
  136. if (Math.sign(e.deltaY) === -1) {
  137. scaleX = (this.state.scale - 0.01);
  138. } else {
  139. scaleX = (this.state.scale + 0.01);
  140. }
  141. this.setState({ scale: scaleX }, this.setAxesLength);
  142. }
  143. setAxesLength() {
  144. let length = Math.round(this._canvasLength * this.state.scale);// Check Undefined, or NaN
  145. let highestFrame = 100;
  146. if (this.state.selected !== null) {
  147. highestFrame = this.state.selected.getHighestFrame();
  148. }
  149. if (length < (highestFrame * 2) / 10) {
  150. length = (highestFrame * 2) / 10
  151. }
  152. let valueLines = Math.round((this.state.scale * this._heightScale) / 10);
  153. let newFrameLength = (new Array(length)).fill(0).map((s, i) => { return { value: i * 10, label: i * 10 } });
  154. let newValueLength = (new Array(valueLines)).fill(0).map((s, i) => { return { value: i * 10, label: this.getValueLabel(i * 10) } });
  155. this.setState({ frameAxisLength: newFrameLength, valueAxisLength: newValueLength });
  156. this.resetPlayheadOffset();
  157. }
  158. getValueLabel(i: number) {
  159. // Need to update this when Y axis grows
  160. let label = 0;
  161. if (i === 0) {
  162. label = 2;
  163. }
  164. if (i === 50) {
  165. label = 1;
  166. } else {
  167. label = ((100 - (i * 2)) * 0.01) + 1;
  168. }
  169. return label;
  170. }
  171. resetPlayheadOffset() {
  172. if (this._graphCanvas && this._graphCanvas.current) {
  173. this.setState({ playheadOffset: (this._graphCanvas.current.children[1].clientWidth) / (this._canvasLength * 10 * this.state.scale) });
  174. }
  175. }
  176. /**
  177. * Add New Animation
  178. * This section handles events from AnimationCreation.
  179. */
  180. handleNameChange(event: React.ChangeEvent<HTMLInputElement>) {
  181. event.preventDefault();
  182. this.setState({ animationName: event.target.value.trim() });
  183. }
  184. handleTypeChange(event: React.ChangeEvent<HTMLSelectElement>) {
  185. event.preventDefault();
  186. this.setState({ animationType: event.target.value });
  187. }
  188. handlePropertyChange(event: React.ChangeEvent<HTMLInputElement>) {
  189. event.preventDefault();
  190. this.setState({ animationTargetProperty: event.target.value });
  191. }
  192. setListItem(animation: Animation, i: number) {
  193. let element;
  194. switch (animation.dataType) {
  195. case Animation.ANIMATIONTYPE_FLOAT:
  196. element = <li className={this.state.selected && this.state.selected.name === animation.name ? 'active' : ''} key={i} onClick={() => this.selectAnimation(animation)}>
  197. <p>{animation.name}&nbsp;
  198. <span>{animation.targetProperty}</span></p>
  199. {!(this.props.entity instanceof TargetedAnimation) ? this.state.selected && this.state.selected.name === animation.name ? <ButtonLineComponent label={"Remove"} onClick={() => this.deleteAnimation()} /> : null : null}
  200. </li>
  201. break;
  202. case Animation.ANIMATIONTYPE_VECTOR2:
  203. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  204. <ul>
  205. <li key={`${i}_x`}>Property <strong>X</strong></li>
  206. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  207. </ul>
  208. </li>
  209. break;
  210. case Animation.ANIMATIONTYPE_VECTOR3:
  211. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  212. <ul>
  213. <li key={`${i}_x`}>Property <strong>X</strong></li>
  214. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  215. <li key={`${i}_z`}>Property <strong>Z</strong></li>
  216. </ul>
  217. </li>
  218. break;
  219. case Animation.ANIMATIONTYPE_QUATERNION:
  220. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  221. <ul>
  222. <li key={`${i}_x`}>Property <strong>X</strong></li>
  223. <li key={`${i}_y`}>Property <strong>Y</strong></li>
  224. <li key={`${i}_z`}>Property <strong>Z</strong></li>
  225. <li key={`${i}_w`}>Property <strong>W</strong></li>
  226. </ul>
  227. </li>
  228. break;
  229. case Animation.ANIMATIONTYPE_COLOR3:
  230. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  231. <ul>
  232. <li key={`${i}_r`}>Property <strong>R</strong></li>
  233. <li key={`${i}_g`}>Property <strong>G</strong></li>
  234. <li key={`${i}_b`}>Property <strong>B</strong></li>
  235. </ul>
  236. </li>
  237. break;
  238. case Animation.ANIMATIONTYPE_COLOR4:
  239. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  240. <ul>
  241. <li key={`${i}_r`}>Property <strong>R</strong></li>
  242. <li key={`${i}_g`}>Property <strong>G</strong></li>
  243. <li key={`${i}_b`}>Property <strong>B</strong></li>
  244. <li key={`${i}_a`}>Property <strong>A</strong></li>
  245. </ul>
  246. </li>
  247. break;
  248. case Animation.ANIMATIONTYPE_SIZE:
  249. element = <li className="property" key={i}><p>{animation.targetProperty}</p>
  250. <ul>
  251. <li key={`${i}_width`}>Property <strong>Width</strong></li>
  252. <li key={`${i}_height`}>Property <strong>Height</strong></li>
  253. </ul>
  254. </li>
  255. break;
  256. default: console.log("not recognized");
  257. element = null;
  258. break;
  259. }
  260. return element;
  261. }
  262. getAnimationTypeofChange(selected: string) {
  263. let dataType = 0;
  264. switch (selected) {
  265. case "Float":
  266. dataType = Animation.ANIMATIONTYPE_FLOAT;
  267. break;
  268. case "Quaternion":
  269. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  270. break;
  271. case "Vector3":
  272. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  273. break;
  274. case "Vector2":
  275. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  276. break;
  277. case "Size":
  278. dataType = Animation.ANIMATIONTYPE_SIZE;
  279. break;
  280. case "Color3":
  281. dataType = Animation.ANIMATIONTYPE_COLOR3;
  282. break;
  283. case "Color4":
  284. dataType = Animation.ANIMATIONTYPE_COLOR4;
  285. break;
  286. }
  287. return dataType;
  288. }
  289. deleteAnimation() {
  290. let currentSelected = this.state.selected;
  291. if (this.props.entity instanceof TargetedAnimation) {
  292. console.log("no animation remove allowed");
  293. } else {
  294. let animations = (this.props.entity as IAnimatable).animations;
  295. if (animations) {
  296. let updatedAnimations = animations.filter(anim => anim !== currentSelected);
  297. (this.props.entity as IAnimatable).animations = updatedAnimations as Nullable<Animation[]>;
  298. }
  299. }
  300. }
  301. addAnimation() {
  302. if (this.state.animationName != "" && this.state.animationTargetProperty != "") {
  303. let matchTypeTargetProperty = this.state.animationTargetProperty.split('.');
  304. let animationDataType = this.getAnimationTypeofChange(this.state.animationType);
  305. let matched = false;
  306. if (matchTypeTargetProperty.length === 1) {
  307. let match = (this.props.entity as any)[matchTypeTargetProperty[0]];
  308. if (match) {
  309. switch (match.constructor.name) {
  310. case "Vector2":
  311. animationDataType === Animation.ANIMATIONTYPE_VECTOR2 ? matched = true : matched = false;
  312. break;
  313. case "Vector3":
  314. animationDataType === Animation.ANIMATIONTYPE_VECTOR3 ? matched = true : matched = false;
  315. break;
  316. case "Quaternion":
  317. animationDataType === Animation.ANIMATIONTYPE_QUATERNION ? matched = true : matched = false;
  318. break;
  319. case "Color3":
  320. animationDataType === Animation.ANIMATIONTYPE_COLOR3 ? matched = true : matched = false;
  321. break;
  322. case "Color4":
  323. animationDataType === Animation.ANIMATIONTYPE_COLOR4 ? matched = true : matched = false;
  324. break;
  325. case "Size":
  326. animationDataType === Animation.ANIMATIONTYPE_SIZE ? matched = true : matched = false;
  327. break;
  328. default: console.log("not recognized");
  329. break;
  330. }
  331. } else {
  332. this.setState({ notification: `The selected entity doesn't have a ${matchTypeTargetProperty[0]} property` });
  333. }
  334. } else if (matchTypeTargetProperty.length > 1) {
  335. let match = (this.props.entity as any)[matchTypeTargetProperty[0]][matchTypeTargetProperty[1]];
  336. if (typeof match === "number") {
  337. animationDataType === Animation.ANIMATIONTYPE_FLOAT ? matched = true : matched = false;
  338. }
  339. }
  340. if (matched) {
  341. let startValue;
  342. let endValue;
  343. let outTangent;
  344. let inTangent;
  345. // Default start and end values for new animations
  346. switch (animationDataType) {
  347. case Animation.ANIMATIONTYPE_FLOAT:
  348. startValue = 1;
  349. endValue = 1;
  350. outTangent = 0;
  351. inTangent = 0;
  352. break;
  353. case Animation.ANIMATIONTYPE_VECTOR2:
  354. startValue = new Vector2(1, 1);
  355. endValue = new Vector2(1, 1);
  356. outTangent = Vector2.Zero();
  357. inTangent = Vector2.Zero();
  358. break;
  359. case Animation.ANIMATIONTYPE_VECTOR3:
  360. startValue = new Vector3(1, 1, 1);
  361. endValue = new Vector3(1, 1, 1);
  362. outTangent = Vector3.Zero();
  363. inTangent = Vector3.Zero();
  364. break;
  365. case Animation.ANIMATIONTYPE_QUATERNION:
  366. startValue = new Quaternion(1, 1, 1, 1);
  367. endValue = new Quaternion(1, 1, 1, 1);
  368. outTangent = Quaternion.Zero();
  369. inTangent = Quaternion.Zero();
  370. break;
  371. case Animation.ANIMATIONTYPE_COLOR3:
  372. startValue = new Color3(1, 1, 1);
  373. endValue = new Color3(1, 1, 1);
  374. outTangent = new Color3(0, 0, 0);
  375. inTangent = new Color3(0, 0, 0);
  376. break;
  377. case Animation.ANIMATIONTYPE_COLOR4:
  378. startValue = new Color4(1, 1, 1, 1);
  379. endValue = new Color4(1, 1, 1, 1);
  380. outTangent = new Color4(0, 0, 0, 0);
  381. inTangent = new Color4(0, 0, 0, 0);
  382. break;
  383. case Animation.ANIMATIONTYPE_SIZE:
  384. startValue = new Size(1, 1);
  385. endValue = new Size(1, 1);
  386. outTangent = Size.Zero();
  387. inTangent = Size.Zero();
  388. break;
  389. default: console.log("not recognized");
  390. break;
  391. }
  392. let alreadyAnimatedProperty = (this.props.entity as IAnimatable).animations?.find(anim =>
  393. anim.targetProperty === this.state.animationTargetProperty
  394. , this);
  395. let alreadyAnimationName = (this.props.entity as IAnimatable).animations?.find(anim =>
  396. anim.name === this.state.animationName
  397. , this);
  398. if (alreadyAnimatedProperty) {
  399. this.setState({ notification: `The property "${this.state.animationTargetProperty}" already has an animation` });
  400. } else if (alreadyAnimationName) {
  401. this.setState({ notification: `There is already an animation with the name: "${this.state.animationName}"` });
  402. } else {
  403. let animation = new Animation(this.state.animationName, this.state.animationTargetProperty, 30, animationDataType);
  404. // Start with two keyframes
  405. var keys = [];
  406. keys.push({
  407. frame: 0,
  408. value: startValue,
  409. outTangent: outTangent
  410. });
  411. keys.push({
  412. inTangent: inTangent,
  413. frame: 100,
  414. value: endValue
  415. });
  416. animation.setKeys(keys);
  417. (this.props.entity as IAnimatable).animations?.push(animation);
  418. }
  419. } else {
  420. this.setState({ notification: `The property "${this.state.animationTargetProperty}" is not a "${this.state.animationType}" type` });
  421. }
  422. } else {
  423. this.setState({ notification: "You need to provide a name and target property." });
  424. }
  425. }
  426. /**
  427. * Keyframe Manipulation
  428. * This section handles events from SvgDraggableArea.
  429. */
  430. selectKeyframe(id: string) {
  431. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  432. if (kf.id === id) {
  433. kf.selected = !kf.selected
  434. }
  435. return kf;
  436. });
  437. this.setState({ svgKeyframes: updatedKeyframes });
  438. }
  439. selectedControlPoint(type: string, id: string) {
  440. let updatedKeyframes = this.state.svgKeyframes?.map(kf => {
  441. if (kf.id === id) {
  442. this.setState({ isFlatTangentMode: false });
  443. if (type === "left") {
  444. kf.isLeftActive = !kf.isLeftActive;
  445. kf.isRightActive = false;
  446. }
  447. if (type === "right") {
  448. kf.isRightActive = !kf.isRightActive;
  449. kf.isLeftActive = false;
  450. }
  451. }
  452. return kf;
  453. });
  454. this.setState({ svgKeyframes: updatedKeyframes });
  455. }
  456. renderPoints(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) {
  457. let animation = this.state.selected as Animation;
  458. // Bug: After play/stop we get an extra keyframe at 0
  459. let keys = [...animation.getKeys()];
  460. let newFrame = 0;
  461. if (updatedSvgKeyFrame.keyframePoint.x !== 0) {
  462. if (updatedSvgKeyFrame.keyframePoint.x > 0 && updatedSvgKeyFrame.keyframePoint.x < 1) {
  463. newFrame = 1;
  464. } else {
  465. newFrame = Math.round(updatedSvgKeyFrame.keyframePoint.x);
  466. }
  467. }
  468. keys[index].frame = newFrame; // This value comes as percentage/frame/time
  469. keys[index].value = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2; // this value comes inverted svg from 0 = 100 to 100 = 0
  470. if (updatedSvgKeyFrame.isLeftActive) {
  471. if (updatedSvgKeyFrame.leftControlPoint !== null) {
  472. // Rotate
  473. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.leftControlPoint.y) / this._heightScale) * 2;
  474. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  475. keys[index].inTangent = keyframeValue - updatedValue;
  476. if (!this.state.isBrokenMode) {
  477. // Right control point if exists
  478. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  479. // Sets opposite value
  480. keys[index].outTangent = keys[index].inTangent * -1
  481. }
  482. }
  483. }
  484. }
  485. if (updatedSvgKeyFrame.isRightActive) {
  486. if (updatedSvgKeyFrame.rightControlPoint !== null) {
  487. // Rotate
  488. let updatedValue = ((this._heightScale - updatedSvgKeyFrame.rightControlPoint.y) / this._heightScale) * 2;
  489. let keyframeValue = ((this._heightScale - updatedSvgKeyFrame.keyframePoint.y) / this._heightScale) * 2;
  490. keys[index].outTangent = keyframeValue - updatedValue;
  491. if (!this.state.isBrokenMode) {
  492. if (updatedSvgKeyFrame.leftControlPoint !== null) { // Sets opposite value
  493. keys[index].inTangent = keys[index].outTangent * -1
  494. }
  495. }
  496. }
  497. }
  498. animation.setKeys(keys);
  499. this.selectAnimation(animation);
  500. }
  501. /**
  502. * Actions
  503. * This section handles events from GraphActionsBar.
  504. */
  505. handleFrameChange(event: React.ChangeEvent<HTMLInputElement>) {
  506. event.preventDefault();
  507. this.changeCurrentFrame(parseInt(event.target.value))
  508. }
  509. handleValueChange(event: React.ChangeEvent<HTMLInputElement>) {
  510. event.preventDefault();
  511. this.setState({ currentValue: parseFloat(event.target.value) }, () => {
  512. if (this.state.selected !== null) {
  513. let animation = this.state.selected;
  514. let keys = animation.getKeys();
  515. let isKeyframe = keys.find(k => k.frame === this.state.currentFrame);
  516. if (isKeyframe) {
  517. let updatedKeys = keys.map(k => {
  518. if (k.frame === this.state.currentFrame) {
  519. k.value = this.state.currentValue;
  520. }
  521. return k;
  522. });
  523. this.state.selected.setKeys(updatedKeys);
  524. this.selectAnimation(animation);
  525. }
  526. }
  527. });
  528. }
  529. setFlatTangent() {
  530. if (this.state.selected !== null) {
  531. let animation = this.state.selected;
  532. this.setState({ isFlatTangentMode: !this.state.isFlatTangentMode }, () => this.selectAnimation(animation));
  533. }
  534. }
  535. // Use this for Bezier curve mode
  536. setTangentMode() {
  537. if (this.state.selected !== null) {
  538. let animation = this.state.selected;
  539. this.setState({ isTangentMode: !this.state.isTangentMode }, () => this.selectAnimation(animation));
  540. }
  541. }
  542. setBrokenMode() {
  543. if (this.state.selected !== null) {
  544. let animation = this.state.selected;
  545. this.setState({ isBrokenMode: !this.state.isBrokenMode }, () => this.selectAnimation(animation));
  546. }
  547. }
  548. setLerpMode() {
  549. if (this.state.selected !== null) {
  550. let animation = this.state.selected;
  551. this.setState({ lerpMode: !this.state.lerpMode }, () => this.selectAnimation(animation));
  552. }
  553. }
  554. addKeyframeClick() {
  555. if (this.state.selected !== null) {
  556. let currentAnimation = this.state.selected;
  557. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  558. let keys = currentAnimation.getKeys();
  559. let x = this.state.currentFrame;
  560. let y = this.state.currentValue;
  561. keys.push({ frame: x, value: y, inTangent: 0, outTangent: 0 });
  562. keys.sort((a, b) => a.frame - b.frame);
  563. currentAnimation.setKeys(keys);
  564. this.selectAnimation(currentAnimation);
  565. }
  566. }
  567. }
  568. removeKeyframeClick() {
  569. if (this.state.selected !== null) {
  570. let currentAnimation = this.state.selected;
  571. if (currentAnimation.dataType === Animation.ANIMATIONTYPE_FLOAT) {
  572. let keys = currentAnimation.getKeys();
  573. let x = this.state.currentFrame;
  574. let filteredKeys = keys.filter(kf => kf.frame !== x);
  575. currentAnimation.setKeys(filteredKeys);
  576. this.selectAnimation(currentAnimation);
  577. }
  578. }
  579. }
  580. addKeyFrame(event: React.MouseEvent<SVGSVGElement>) {
  581. event.preventDefault();
  582. if (this.state.selected !== null) {
  583. var svg = event.target as SVGSVGElement;
  584. var pt = svg.createSVGPoint();
  585. pt.x = event.clientX;
  586. pt.y = event.clientY;
  587. var inverse = svg.getScreenCTM()?.inverse();
  588. var cursorpt = pt.matrixTransform(inverse);
  589. var currentAnimation = this.state.selected;
  590. var keys = currentAnimation.getKeys();
  591. var height = 100;
  592. var middle = (height / 2);
  593. var keyValue;
  594. if (cursorpt.y < middle) {
  595. keyValue = 1 + ((100 / cursorpt.y) * .1)
  596. }
  597. if (cursorpt.y > middle) {
  598. keyValue = 1 - ((100 / cursorpt.y) * .1)
  599. }
  600. keys.push({ frame: cursorpt.x, value: keyValue });
  601. currentAnimation.setKeys(keys);
  602. this.selectAnimation(currentAnimation);
  603. }
  604. }
  605. updateKeyframe(keyframe: Vector2, index: number) {
  606. let anim = this.state.selected as Animation;
  607. var keys: IAnimationKey[] = [];
  608. var svgKeyframes = this.state.svgKeyframes?.map((k, i) => {
  609. if (i === index) {
  610. k.keyframePoint.x = keyframe.x;
  611. k.keyframePoint.y = keyframe.y;
  612. }
  613. var height = 100;
  614. var middle = (height / 2);
  615. var keyValue;
  616. if (k.keyframePoint.y < middle) {
  617. keyValue = 1 + ((100 / k.keyframePoint.y) * .1)
  618. }
  619. if (k.keyframePoint.y > middle) {
  620. keyValue = 1 - ((100 / k.keyframePoint.y) * .1)
  621. }
  622. keys.push({ frame: k.keyframePoint.x, value: keyValue })
  623. return k;
  624. });
  625. anim.setKeys(keys);
  626. this.setState({ svgKeyframes: svgKeyframes });
  627. }
  628. /**
  629. * Curve Rendering Functions
  630. * This section handles how to render curves.
  631. */
  632. getAnimationProperties(animation: Animation) {
  633. let easingType, easingMode;
  634. let easingFunction: EasingFunction = animation.getEasingFunction() as EasingFunction;
  635. if (easingFunction === undefined) {
  636. easingType = undefined
  637. easingMode = undefined;
  638. } else {
  639. easingType = easingFunction.constructor.name;
  640. easingMode = easingFunction.getEasingMode();
  641. }
  642. return { easingType, easingMode }
  643. }
  644. linearInterpolation(keyframes: IAnimationKey[], data: string, middle: number): string {
  645. keyframes.forEach((key, i) => {
  646. var point = new Vector2(0, 0);
  647. point.x = key.frame;
  648. point.y = this._heightScale - (key.value * middle);
  649. this.setKeyframePointLinear(point, i);
  650. if (i !== 0) {
  651. data += ` L${point.x} ${point.y}`
  652. }
  653. });
  654. return data;
  655. }
  656. setKeyframePointLinear(point: Vector2, index: number) {
  657. let svgKeyframe = { keyframePoint: point, rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  658. this._svgKeyframes.push(svgKeyframe);
  659. }
  660. getPathData(animation: Animation | null) {
  661. if (animation === null){
  662. return "";
  663. }
  664. // Check if Tangent mode is active and broken mode is active. (Only one tangent moves)
  665. let keyframes = animation.getKeys();
  666. if (keyframes === undefined) {
  667. return "";
  668. }
  669. // Checks if Flat Tangent is active (tangents are set to zero)
  670. if (this.state && this.state.isFlatTangentMode) {
  671. keyframes = animation.getKeys().map(kf => {
  672. if (kf.inTangent !== undefined) {
  673. kf.inTangent = 0;
  674. }
  675. if (kf.outTangent !== undefined) {
  676. kf.outTangent = 0;
  677. }
  678. return kf;
  679. });
  680. } else {
  681. keyframes = animation.getKeys();
  682. }
  683. const startKey = keyframes[0];
  684. let middle = this._heightScale / 2;
  685. // START OF LINE/CURVE
  686. let data: string | undefined = `M${startKey.frame}, ${this._heightScale - (startKey.value * middle)}`;
  687. if (this.state && this.state.lerpMode) {
  688. data = this.linearInterpolation(keyframes, data, middle);
  689. } else {
  690. if (this.getAnimationData(animation).usesTangents) {
  691. data = this.curvePathWithTangents(keyframes, data, middle, animation.dataType);
  692. } else {
  693. const { easingMode, easingType } = this.getAnimationProperties(animation);
  694. if (easingType !== undefined && easingMode !== undefined) {
  695. let easingFunction = animation.getEasingFunction();
  696. data = this.curvePath(keyframes, data, middle, easingFunction as EasingFunction)
  697. } else {
  698. if (this.state !== undefined) {
  699. let emptyTangents = keyframes.map((kf, i) => {
  700. if (i === 0) {
  701. kf.outTangent = 0;
  702. } else if (i === keyframes.length - 1) {
  703. kf.inTangent = 0;
  704. } else {
  705. kf.inTangent = 0;
  706. kf.outTangent = 0;
  707. }
  708. return kf;
  709. });
  710. data = this.curvePathWithTangents(emptyTangents, data, middle, animation.dataType);
  711. } else {
  712. data = this.linearInterpolation(keyframes, data, middle);
  713. }
  714. }
  715. }
  716. }
  717. return data;
  718. }
  719. getAnimationData(animation: Animation) {
  720. // General Props
  721. let loopMode = animation.loopMode;
  722. let name = animation.name;
  723. let blendingSpeed = animation.blendingSpeed;
  724. let targetProperty = animation.targetProperty;
  725. let targetPropertyPath = animation.targetPropertyPath;
  726. let framesPerSecond = animation.framePerSecond;
  727. let highestFrame = animation.getHighestFrame();
  728. let serialized = animation.serialize();
  729. let usesTangents = animation.getKeys().find(kf => kf.hasOwnProperty('inTangent') || kf.hasOwnProperty('outTangent')) !== undefined ? true : false;
  730. return { loopMode, name, blendingSpeed, targetPropertyPath, targetProperty, framesPerSecond, highestFrame, serialized, usesTangents }
  731. }
  732. drawAllFrames(initialKey: IAnimationKey, endKey: IAnimationKey, easingFunction: EasingFunction) {
  733. let i = initialKey.frame;
  734. for (i; i < endKey.frame; i++) {
  735. (i * 100 / endKey.frame)
  736. let dy = easingFunction.easeInCore(i);
  737. let value = this._heightScale - (dy * (this._heightScale / 2));
  738. this._frames.push(new Vector2(i, value));
  739. }
  740. }
  741. curvePathFlat(keyframes: IAnimationKey[], data: string, middle: number, dataType: number) {
  742. keyframes.forEach((key, i) => {
  743. if (dataType === Animation.ANIMATIONTYPE_FLOAT) {
  744. var pointA = new Vector2(0, 0);
  745. if (i === 0) {
  746. pointA.set(key.frame, this._heightScale - (key.value * middle));
  747. this.setKeyframePoint([pointA], i, keyframes.length);
  748. } else {
  749. pointA.set(keyframes[i - 1].frame, this._heightScale - (keyframes[i - 1].value * middle));
  750. let defaultWeight = 10;
  751. let nextKeyframe = keyframes[i + 1];
  752. let prevKeyframe = keyframes[i - 1];
  753. if (nextKeyframe !== undefined) {
  754. let distance = keyframes[i + 1].frame - key.frame;
  755. defaultWeight = distance * .33;
  756. }
  757. if (prevKeyframe !== undefined) {
  758. let distance = key.frame - keyframes[i - 1].frame;
  759. defaultWeight = distance * .33;
  760. }
  761. let tangentA = new Vector2(pointA.x + defaultWeight, pointA.y);
  762. let pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  763. let tangentB = new Vector2(pointB.x - defaultWeight, pointB.y);
  764. this.setKeyframePoint([pointA, tangentA, tangentB, pointB], i, keyframes.length);
  765. data += ` C${tangentA.x} ${tangentA.y} ${tangentB.x} ${tangentB.y} ${pointB.x} ${pointB.y} `
  766. }
  767. }
  768. });
  769. return data;
  770. }
  771. curvePathWithTangents(keyframes: IAnimationKey[], data: string, middle: number, type: number) {
  772. keyframes.forEach((key, i) => {
  773. let svgKeyframe;
  774. let outTangent;
  775. let inTangent;
  776. let defaultWeight = 5;
  777. var inT = key.inTangent === undefined ? null : key.inTangent;
  778. var outT = key.outTangent === undefined ? null : key.outTangent;
  779. let y = this._heightScale - (key.value * middle);
  780. let nextKeyframe = keyframes[i + 1];
  781. let prevKeyframe = keyframes[i - 1];
  782. if (nextKeyframe !== undefined) {
  783. let distance = keyframes[i + 1].frame - key.frame;
  784. defaultWeight = distance * .33;
  785. }
  786. if (prevKeyframe !== undefined) {
  787. let distance = key.frame - keyframes[i - 1].frame;
  788. defaultWeight = distance * .33;
  789. }
  790. if (inT !== null) {
  791. let valueIn = (y * inT) + y;
  792. inTangent = new Vector2(key.frame - defaultWeight, valueIn)
  793. } else {
  794. inTangent = null;
  795. }
  796. if (outT !== null) {
  797. let valueOut = (y * outT) + y;
  798. outTangent = new Vector2(key.frame + defaultWeight, valueOut);
  799. } else {
  800. outTangent = null;
  801. }
  802. if (i === 0) {
  803. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: null, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  804. if (outTangent !== null) {
  805. data += ` C${outTangent.x} ${outTangent.y} `;
  806. }
  807. } else {
  808. svgKeyframe = { keyframePoint: new Vector2(key.frame, this._heightScale - (key.value * middle)), rightControlPoint: outTangent, leftControlPoint: inTangent, id: i.toString(), selected: false, isLeftActive: false, isRightActive: false }
  809. if (outTangent !== null && inTangent !== null) {
  810. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} C${outTangent.x} ${outTangent.y} `
  811. } else if (inTangent !== null) {
  812. data += ` ${inTangent.x} ${inTangent.y} ${svgKeyframe.keyframePoint.x} ${svgKeyframe.keyframePoint.y} `
  813. }
  814. }
  815. if (this.state) {
  816. let prev = this.state.svgKeyframes?.find(kf => kf.id === i.toString());
  817. if (prev) {
  818. svgKeyframe.isLeftActive = prev?.isLeftActive;
  819. svgKeyframe.isRightActive = prev?.isRightActive;
  820. svgKeyframe.selected = prev?.selected
  821. }
  822. }
  823. this._svgKeyframes.push(svgKeyframe);
  824. }, this);
  825. return data;
  826. }
  827. curvePath(keyframes: IAnimationKey[], data: string, middle: number, easingFunction: EasingFunction) {
  828. // This will get 1/4 and 3/4 of points in eased curve
  829. const u = .25;
  830. const v = .75;
  831. keyframes.forEach((key, i) => {
  832. // Gets previous initial point of curve segment
  833. var pointA = new Vector2(0, 0);
  834. if (i === 0) {
  835. pointA.x = key.frame;
  836. pointA.y = this._heightScale - (key.value * middle);
  837. this.setKeyframePoint([pointA], i, keyframes.length);
  838. } else {
  839. pointA.x = keyframes[i - 1].frame;
  840. pointA.y = this._heightScale - (keyframes[i - 1].value * middle)
  841. // Gets the end point of this curve segment
  842. var pointB = new Vector2(key.frame, this._heightScale - (key.value * middle));
  843. // Get easing value of percentage to get the bezier control points below
  844. 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)
  845. let dv = easingFunction.easeInCore(v); // Option 2: Create a easeInCore function and adapt it with the new control points values... needs more revision.
  846. // Direction of curve up/down
  847. let yInt25 = 0;
  848. if (pointB.y > pointA.y) { // if pointB.y > pointA.y = goes down
  849. yInt25 = ((pointB.y - pointA.y) * du) + pointA.y
  850. } else if (pointB.y < pointA.y) { // if pointB.y < pointA.y = goes up
  851. yInt25 = pointA.y - ((pointA.y - pointB.y) * du);
  852. }
  853. let yInt75 = 0;
  854. if (pointB.y > pointA.y) {
  855. yInt75 = ((pointB.y - pointA.y) * dv) + pointA.y
  856. } else if (pointB.y < pointA.y) {
  857. yInt75 = pointA.y - ((pointA.y - pointB.y) * dv)
  858. }
  859. // Intermediate points in curve
  860. let intermediatePoint25 = new Vector2(((pointB.x - pointA.x) * u) + pointA.x, yInt25);
  861. let intermediatePoint75 = new Vector2(((pointB.x - pointA.x) * v) + pointA.x, yInt75);
  862. // Gets the four control points of bezier curve
  863. let controlPoints = this.interpolateControlPoints(pointA, intermediatePoint25, u, intermediatePoint75, v, pointB);
  864. if (controlPoints === undefined) {
  865. console.log("error getting bezier control points");
  866. } else {
  867. this.setKeyframePoint(controlPoints, i, keyframes.length);
  868. data += ` C${controlPoints[1].x} ${controlPoints[1].y} ${controlPoints[2].x} ${controlPoints[2].y} ${controlPoints[3].x} ${controlPoints[3].y}`
  869. }
  870. }
  871. });
  872. return data;
  873. }
  874. setKeyframePoint(controlPoints: Vector2[], index: number, keyframesCount: number) {
  875. let svgKeyframe;
  876. if (index === 0) {
  877. svgKeyframe = { keyframePoint: controlPoints[0], rightControlPoint: null, leftControlPoint: null, id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  878. } else {
  879. this._svgKeyframes[index - 1].rightControlPoint = controlPoints[1];
  880. svgKeyframe = { keyframePoint: controlPoints[3], rightControlPoint: null, leftControlPoint: controlPoints[2], id: index.toString(), selected: false, isLeftActive: false, isRightActive: false }
  881. }
  882. this._svgKeyframes.push(svgKeyframe);
  883. }
  884. interpolateControlPoints(p0: Vector2, p1: Vector2, u: number, p2: Vector2, v: number, p3: Vector2): Vector2[] | undefined {
  885. let a = 0.0;
  886. let b = 0.0;
  887. let c = 0.0;
  888. let d = 0.0;
  889. let det = 0.0;
  890. let q1: Vector2 = new Vector2();
  891. let q2: Vector2 = new Vector2();
  892. let controlA: Vector2 = p0;
  893. let controlB: Vector2 = new Vector2();
  894. let controlC: Vector2 = new Vector2();
  895. let controlD: Vector2 = p3;
  896. if ((u <= 0.0) || (u >= 1.0) || (v <= 0.0) || (v >= 1.0) || (u >= v)) {
  897. return undefined;
  898. }
  899. a = 3 * (1 - u) * (1 - u) * u; b = 3 * (1 - u) * u * u;
  900. c = 3 * (1 - v) * (1 - v) * v; d = 3 * (1 - v) * v * v;
  901. det = a * d - b * c;
  902. if (det == 0.0) return undefined;
  903. q1.x = p1.x - ((1 - u) * (1 - u) * (1 - u) * p0.x + u * u * u * p3.x);
  904. q1.y = p1.y - ((1 - u) * (1 - u) * (1 - u) * p0.y + u * u * u * p3.y);
  905. q2.x = p2.x - ((1 - v) * (1 - v) * (1 - v) * p0.x + v * v * v * p3.x);
  906. q2.y = p2.y - ((1 - v) * (1 - v) * (1 - v) * p0.y + v * v * v * p3.y);
  907. controlB.x = (d * q1.x - b * q2.x) / det;
  908. controlB.y = (d * q1.y - b * q2.y) / det;
  909. controlC.x = ((-c) * q1.x + a * q2.x) / det;
  910. controlC.y = ((-c) * q1.y + a * q2.y) / det;
  911. return [controlA, controlB, controlC, controlD];
  912. }
  913. /**
  914. * Core functions
  915. * This section handles main Curve Editor Functions.
  916. */
  917. selectAnimation(animation: Animation) {
  918. this.playStopAnimation();
  919. this._svgKeyframes = [];
  920. const pathData = this.getPathData(animation);
  921. let lastFrame = animation.getHighestFrame();
  922. if (pathData === "") {
  923. console.log("no keyframes in this animation");
  924. }
  925. this.setState({ selected: animation, currentPathData: pathData, svgKeyframes: this._svgKeyframes, lastFrame: lastFrame });
  926. }
  927. isAnimationPlaying() {
  928. let target = this.props.entity;
  929. if (this.props.entity instanceof TargetedAnimation) {
  930. target = this.props.entity.target;
  931. }
  932. return this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  933. }
  934. playPause(direction: number) {
  935. if (this.state.selected) {
  936. let target = this.props.entity;
  937. if (this.props.entity instanceof TargetedAnimation) {
  938. target = this.props.entity.target;
  939. }
  940. if (this.state.isPlaying) {
  941. this.props.scene.stopAnimation(target);
  942. this.setState({ isPlaying: false })
  943. this._isPlaying = false;
  944. this.forceUpdate();
  945. } else {
  946. let keys = this.state.selected.getKeys();
  947. let firstFrame = keys[0].frame;
  948. let LastFrame = keys[keys.length - 1].frame;
  949. if (direction === 1){
  950. this.props.scene.beginAnimation(target, firstFrame, LastFrame, true);
  951. }
  952. if (direction === -1){
  953. this.props.scene.beginAnimation(target, LastFrame, firstFrame, true);
  954. }
  955. this._isPlaying = true;
  956. this.setState({ isPlaying: true });
  957. this.forceUpdate();
  958. }
  959. }
  960. }
  961. playStopAnimation() {
  962. let target = this.props.entity;
  963. if (this.props.entity instanceof TargetedAnimation) {
  964. target = this.props.entity.target;
  965. }
  966. this._isPlaying = this.props.scene.getAllAnimatablesByTarget(target).length > 0;
  967. if (this._isPlaying) {
  968. this.props.playOrPause && this.props.playOrPause();
  969. return true;
  970. } else {
  971. this._isPlaying = false;
  972. return false;
  973. }
  974. }
  975. analizeAnimation(animation: Animation | null) {
  976. if (animation !== null) {
  977. const { easingMode, easingType } = this.getAnimationProperties(animation);
  978. let hasDefinedTangents = this.getAnimationData(animation).usesTangents;
  979. if (easingType === undefined && easingMode === undefined && !hasDefinedTangents) {
  980. return true;
  981. } else {
  982. return false;
  983. }
  984. } else {
  985. return false;
  986. }
  987. }
  988. /**
  989. * Timeline
  990. * This section controls the timeline.
  991. */
  992. changeCurrentFrame(frame: number) {
  993. let currentValue;
  994. let selectedCurve = this._selectedCurve.current;
  995. if (selectedCurve) {
  996. var curveLength = selectedCurve.getTotalLength();
  997. let frameValue = (frame * curveLength) / 100;
  998. let currentP = selectedCurve.getPointAtLength(frameValue);
  999. let middle = this._heightScale / 2;
  1000. let offset = (((currentP?.y * this._heightScale) - (this._heightScale ** 2) / 2) / middle) / this._heightScale;
  1001. let unit = Math.sign(offset);
  1002. currentValue = unit === -1 ? Math.abs(offset + unit) : unit - offset;
  1003. this.setState({ currentFrame: frame, currentValue: currentValue, currentPoint: currentP });
  1004. }
  1005. }
  1006. updateFrameInKeyFrame(frame: number, index: number) {
  1007. if (this.state && this.state.selected) {
  1008. let animation = this.state.selected;
  1009. let keys = [...animation.getKeys()];
  1010. keys[index].frame = frame;
  1011. animation.setKeys(keys);
  1012. this.selectAnimation(animation);
  1013. }
  1014. }
  1015. render() {
  1016. return (
  1017. <div id="animation-curve-editor">
  1018. <Notification message={this.state.notification} open={this.state.notification !== "" ? true : false} close={() => this.clearNotification()} />
  1019. <GraphActionsBar
  1020. enabled={this.state.selected === null || this.state.selected === undefined ? false : true}
  1021. title={this._entityName}
  1022. close={this.props.close}
  1023. currentValue={this.state.currentValue}
  1024. currentFrame={this.state.currentFrame}
  1025. handleFrameChange={(e) => this.handleFrameChange(e)}
  1026. handleValueChange={(e) => this.handleValueChange(e)}
  1027. addKeyframe={() => this.addKeyframeClick()}
  1028. removeKeyframe={() => this.removeKeyframeClick()}
  1029. brokenMode={this.state.isBrokenMode}
  1030. brokeTangents={() => this.setBrokenMode()}
  1031. lerpMode={this.state.lerpMode}
  1032. setLerpMode={() => this.setLerpMode()}
  1033. flatTangent={() => this.setFlatTangent()} />
  1034. <div className="content">
  1035. <div className="row">
  1036. <div className="animation-list">
  1037. <div style={{ display: this._isTargetedAnimation ? "none" : "block" }}>
  1038. <div className="label-input">
  1039. <label>Animation Name</label>
  1040. <input type="text" value={this.state.animationName} onChange={(e) => this.handleNameChange(e)}></input>
  1041. </div>
  1042. <div className="label-input">
  1043. <label>Type</label>
  1044. <select onChange={(e) => this.handleTypeChange(e)} value={this.state.animationType}>
  1045. <option value="Float">Float</option>
  1046. <option value="Vector3">Vector3</option>
  1047. <option value="Vector2">Vector2</option>
  1048. <option value="Quaternion">Quaternion</option>
  1049. <option value="Color3">Color3</option>
  1050. <option value="Color4">Color4</option>
  1051. <option value="Size">Size</option>
  1052. </select>
  1053. </div>
  1054. <div className="label-input">
  1055. <label>Target Property</label>
  1056. <input type="text" value={this.state.animationTargetProperty} onChange={(e) => this.handlePropertyChange(e)}></input>
  1057. </div>
  1058. <ButtonLineComponent label={"Add Animation"} onClick={() => this.addAnimation()} />
  1059. </div>
  1060. <div className="object-tree">
  1061. <ul>
  1062. {
  1063. this.props.entity instanceof TargetedAnimation ? this.setListItem(this.props.entity.animation, 0) :
  1064. this.props.entity.animations && this.props.entity.animations.map((animation, i) => {
  1065. return this.setListItem(animation, i);
  1066. })}
  1067. </ul>
  1068. </div>
  1069. </div>
  1070. <div ref={this._graphCanvas} className="graph-chart" onWheel={(e) => this.zoom(e)} >
  1071. <Playhead frame={this.state.currentFrame} offset={this.state.playheadOffset} />
  1072. {this.state.svgKeyframes && <SvgDraggableArea ref={this._svgCanvas}
  1073. selectKeyframe={(id: string) => this.selectKeyframe(id)}
  1074. viewBoxScale={this.state.frameAxisLength.length} scale={this.state.scale}
  1075. keyframeSvgPoints={this.state.svgKeyframes}
  1076. selectedControlPoint={(type: string, id: string) => this.selectedControlPoint(type, id)}
  1077. updatePosition={(updatedSvgKeyFrame: IKeyframeSvgPoint, index: number) => this.renderPoints(updatedSvgKeyFrame, index)}>
  1078. {/* Frame Labels */}
  1079. { /* Vertical Grid */}
  1080. {this.state.frameAxisLength.map((f, i) =>
  1081. <svg key={i}>
  1082. <text x={f.value} y="-2" dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.value}</text>
  1083. <line x1={f.value} y1="0" x2={f.value} y2="100%"></line>
  1084. </svg>
  1085. )}
  1086. {this.state.valueAxisLength.map((f, i) => {
  1087. return <svg key={i}>
  1088. <text x="-3" y={f.value} dx="-1em" style={{ font: 'italic 0.2em sans-serif', fontSize: `${0.2 * this.state.scale}em` }}>{f.label.toFixed(1)}</text>
  1089. <line x1="0" y1={f.value} x2="100%" y2={f.value}></line>
  1090. </svg>
  1091. })}
  1092. { /* Single Curve -Modify this for multiple selection and view */}
  1093. <path ref={this._selectedCurve} pathLength={this.state.lastFrame} id="curve" d={this.state.currentPathData} style={{ stroke: 'red', fill: 'none', strokeWidth: '0.5' }}></path>
  1094. {this._frames && this._frames.map(frame =>
  1095. <svg x={frame.x} y={frame.y} style={{ overflow: 'visible' }}>
  1096. <circle cx="0" cy="0" r="2" stroke="black" strokeWidth="1" fill="white" />
  1097. </svg>
  1098. )}
  1099. </SvgDraggableArea>
  1100. }
  1101. </div>
  1102. </div>
  1103. <div className="row">
  1104. <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>
  1105. </div>
  1106. </div>
  1107. </div>
  1108. );
  1109. }
  1110. }