animationCurveEditorComponent.tsx 53 KB

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