GUICurveEditor.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2018 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using bs;
  6. namespace bs.Editor
  7. {
  8. /** @addtogroup AnimationEditor
  9. * @{
  10. */
  11. /// <summary>
  12. /// Displays a set of animation curves and events. Allows manipulation of both by adding, removing and modifying
  13. /// curve keyframes, and animation events.
  14. /// </summary>
  15. internal class GUICurveEditor
  16. {
  17. /// <summary>
  18. /// Information about currently selected set of keyframes for a specific curve.
  19. /// </summary>
  20. class SelectedKeyframes
  21. {
  22. public int curveIdx;
  23. public List<int> keyIndices = new List<int>();
  24. }
  25. /// <summary>
  26. /// Information about a keyframe that is currently being dragged.
  27. /// </summary>
  28. struct DraggedKeyframe
  29. {
  30. public DraggedKeyframe(int index, KeyFrame original)
  31. {
  32. this.index = index;
  33. this.original = original;
  34. }
  35. public int index;
  36. public KeyFrame original;
  37. }
  38. /// <summary>
  39. /// Information about all keyframes of a specific curve that are currently being dragged.
  40. /// </summary>
  41. class DraggedKeyframes
  42. {
  43. public int curveIdx;
  44. public List<DraggedKeyframe> keys = new List<DraggedKeyframe>();
  45. }
  46. /// <summary>
  47. /// Data about an animation event.
  48. /// </summary>
  49. class EventInfo
  50. {
  51. public AnimationEvent animEvent;
  52. public bool selected;
  53. }
  54. private const int TIMELINE_HEIGHT = 20;
  55. private const int VERT_PADDING = 2;
  56. private const int EVENTS_HEIGHT = 15;
  57. private const int SIDEBAR_WIDTH = 30;
  58. private const int DRAG_START_DISTANCE = 3;
  59. private const float DRAG_SCALE = 3.0f;
  60. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  61. private GUILayout gui;
  62. private GUILayout mainPanel;
  63. private GUIPanel drawingPanel;
  64. private GUIPanel eventsPanel;
  65. private GUITexture timelineBackground;
  66. private GUITexture eventsBackground;
  67. private GUIGraphTime guiTimeline;
  68. private GUIAnimEvents guiEvents;
  69. private GUICurves guiCurveDrawing;
  70. private GUIGraphValues guiSidebar;
  71. private int scrollBarWidth;
  72. private int scrollBarHeight;
  73. private GUIResizeableScrollBarH horzScrollBar;
  74. private GUIResizeableScrollBarV vertScrollBar;
  75. private ContextMenu blankContextMenu;
  76. private ContextMenu keyframeContextMenu;
  77. private ContextMenu blankEventContextMenu;
  78. private ContextMenu eventContextMenu;
  79. private Vector2I contextClickPosition;
  80. private EdCurveDrawInfo[] curveInfos = new EdCurveDrawInfo[0];
  81. private bool disableCurveEdit = false;
  82. private float xRange = 60.0f;
  83. private float yRange = 10.0f;
  84. private Vector2 offset;
  85. private int width;
  86. private int height;
  87. private int markedFrameIdx;
  88. private List<SelectedKeyframes> selectedKeyframes = new List<SelectedKeyframes>();
  89. private bool showEvents = true;
  90. private List<EventInfo> events = new List<EventInfo>();
  91. private SceneObject eventsSO;
  92. private bool isPointerHeld;
  93. private bool isMousePressedOverKey;
  94. private bool isMousePressedOverTangent;
  95. private bool isDragInProgress;
  96. private bool isModifiedDuringDrag;
  97. private List<DraggedKeyframes> draggedKeyframes = new List<DraggedKeyframes>();
  98. private TangentRef draggedTangent;
  99. private Vector2I dragStart;
  100. /// <summary>
  101. /// Triggers whenever user selects a new frame. Reports the index of the selected frame.
  102. /// </summary>
  103. public Action<int> OnFrameSelected;
  104. /// <summary>
  105. /// Triggered whenever a new animation event is added.
  106. /// </summary>
  107. public Action OnEventAdded;
  108. /// <summary>
  109. /// Triggered whenever values in an animation event change.
  110. /// </summary>
  111. public Action OnEventModified;
  112. /// <summary>
  113. /// Triggered whenever an animation event is deleted.
  114. /// </summary>
  115. public Action OnEventDeleted;
  116. /// <summary>
  117. /// Triggered whenever keyframe in a curve is modified (added, removed or edited).
  118. /// </summary>
  119. public Action OnCurveModified;
  120. /// <summary>
  121. /// Triggered when the user clicks anywhere on the curve editor area.
  122. /// </summary>
  123. public Action OnClicked;
  124. /// <summary>
  125. /// The displayed range of the curve, where:
  126. /// .x - Range of the horizontal area. Displayed area ranges from [0, x].
  127. /// .y - Range of the vertical area. Displayed area ranges from [-y, y].
  128. /// </summary>
  129. public Vector2 Range
  130. {
  131. get { return new Vector2(xRange, yRange); }
  132. set
  133. {
  134. xRange = value.x;
  135. yRange = value.y;
  136. guiTimeline.SetRange(xRange);
  137. guiCurveDrawing.SetRange(xRange, yRange * 2.0f);
  138. guiSidebar.SetRange(offset.y - yRange, offset.y + yRange);
  139. if(showEvents)
  140. guiEvents.SetRange(xRange);
  141. Redraw();
  142. }
  143. }
  144. /// <summary>
  145. /// Determines how much to offset the displayed curve values.
  146. /// </summary>
  147. public Vector2 Offset
  148. {
  149. get { return offset; }
  150. set
  151. {
  152. offset = value;
  153. guiTimeline.SetOffset(offset.x);
  154. guiCurveDrawing.SetOffset(offset);
  155. guiSidebar.SetRange(offset.y - yRange, offset.y + yRange);
  156. if(showEvents)
  157. guiEvents.SetOffset(offset.x);
  158. Redraw();
  159. }
  160. }
  161. /// <summary>
  162. /// Returns the width of the curve editor, in pixels.
  163. /// </summary>
  164. public int Width
  165. {
  166. get { return width; }
  167. }
  168. /// <summary>
  169. /// Returns the height of the curve editor, in pixels.
  170. /// </summary>
  171. public int Height
  172. {
  173. get { return height; }
  174. }
  175. /// <summary>
  176. /// Set to true if curves are not allowed to be edited.
  177. /// </summary>
  178. public bool DisableCurveEdit
  179. {
  180. set { disableCurveEdit = value; }
  181. }
  182. /// <summary>
  183. /// Animation events displayed on the curve editor.
  184. /// </summary>
  185. public AnimationEvent[] Events
  186. {
  187. get
  188. {
  189. AnimationEvent[] animEvents = new AnimationEvent[events.Count];
  190. // Note: Hidden dependency. Returned events must point to the same event class this object is using, so
  191. // that any modifications made in this class will be visible in the returned values.
  192. for (int i = 0; i < events.Count; i++)
  193. animEvents[i] = events[i].animEvent;
  194. return animEvents;
  195. }
  196. set
  197. {
  198. events.Clear();
  199. for (int i = 0; i < value.Length; i++)
  200. {
  201. EventInfo eventInfo = new EventInfo();
  202. eventInfo.animEvent = value[i];
  203. events.Add(eventInfo);
  204. }
  205. UpdateEventsGUI();
  206. }
  207. }
  208. /// <summary>
  209. /// Creates a new curve editor GUI elements.
  210. /// </summary>
  211. /// <param name="gui">GUI layout into which to place the GUI element.</param>
  212. /// <param name="width">Width in pixels.</param>
  213. /// <param name="height">Height in pixels.</param>
  214. /// <param name="showEvents">If true show events on the graph and allow their editing.</param>
  215. /// <param name="drawOptions">Options that control which elements to display when drawing curves.</param>
  216. public GUICurveEditor(GUILayout gui, int width, int height, bool showEvents,
  217. CurveDrawOptions drawOptions = CurveDrawOptions.DrawMarkers | CurveDrawOptions.DrawKeyframes)
  218. {
  219. this.gui = gui;
  220. this.showEvents = showEvents;
  221. blankContextMenu = new ContextMenu();
  222. blankContextMenu.AddItem("Add keyframe", AddKeyframeAtPosition);
  223. blankEventContextMenu = new ContextMenu();
  224. blankEventContextMenu.AddItem("Add event", AddEventAtPosition);
  225. keyframeContextMenu = new ContextMenu();
  226. keyframeContextMenu.AddItem("Delete", DeleteSelectedKeyframes);
  227. keyframeContextMenu.AddItem("Edit", EditSelectedKeyframe);
  228. keyframeContextMenu.AddItem("Tangents/Auto", () => { ChangeSelectionTangentMode(TangentMode.Auto); });
  229. keyframeContextMenu.AddItem("Tangents/Free", () => { ChangeSelectionTangentMode(TangentMode.Free); });
  230. keyframeContextMenu.AddItem("Tangents/In/Auto", () => { ChangeSelectionTangentMode(TangentMode.InAuto); });
  231. keyframeContextMenu.AddItem("Tangents/In/Free", () => { ChangeSelectionTangentMode(TangentMode.InFree); });
  232. keyframeContextMenu.AddItem("Tangents/In/Linear", () => { ChangeSelectionTangentMode(TangentMode.InLinear); });
  233. keyframeContextMenu.AddItem("Tangents/In/Step", () => { ChangeSelectionTangentMode(TangentMode.InStep); });
  234. keyframeContextMenu.AddItem("Tangents/Out/Auto", () => { ChangeSelectionTangentMode(TangentMode.OutAuto); });
  235. keyframeContextMenu.AddItem("Tangents/Out/Free", () => { ChangeSelectionTangentMode(TangentMode.OutFree); });
  236. keyframeContextMenu.AddItem("Tangents/Out/Linear", () => { ChangeSelectionTangentMode(TangentMode.OutLinear); });
  237. keyframeContextMenu.AddItem("Tangents/Out/Step", () => { ChangeSelectionTangentMode(TangentMode.OutStep); });
  238. eventContextMenu = new ContextMenu();
  239. eventContextMenu.AddItem("Delete", DeleteSelectedEvents);
  240. eventContextMenu.AddItem("Edit", EditSelectedEvent);
  241. horzScrollBar = new GUIResizeableScrollBarH();
  242. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  243. vertScrollBar = new GUIResizeableScrollBarV();
  244. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  245. GUILayout mainLayout = gui.AddLayoutY();
  246. GUILayout curveLayoutHorz = mainLayout.AddLayoutX();
  247. GUILayout horzScrollBarLayout = mainLayout.AddLayoutX();
  248. horzScrollBarLayout.AddElement(horzScrollBar);
  249. horzScrollBarLayout.AddFlexibleSpace();
  250. mainPanel = curveLayoutHorz.AddPanel();
  251. curveLayoutHorz.AddElement(vertScrollBar);
  252. curveLayoutHorz.AddFlexibleSpace();
  253. scrollBarHeight = horzScrollBar.Bounds.height;
  254. scrollBarWidth = vertScrollBar.Bounds.width;
  255. this.width = Math.Max(0, width - scrollBarWidth);
  256. this.height = Math.Max(0, height - scrollBarHeight);
  257. GUIPanel timelinePanel = mainPanel.AddPanel();
  258. guiTimeline = new GUIGraphTime(timelinePanel, this.width, TIMELINE_HEIGHT);
  259. GUIPanel timelineBgPanel = mainPanel.AddPanel(1);
  260. timelineBackground = new GUITexture(null, EditorStyles.Header);
  261. timelineBackground.Bounds = new Rect2I(0, 0, this.width, TIMELINE_HEIGHT + VERT_PADDING);
  262. timelineBgPanel.AddElement(timelineBackground);
  263. int eventsHeaderHeight = 0;
  264. if (showEvents)
  265. {
  266. eventsPanel = mainPanel.AddPanel();
  267. eventsPanel.SetPosition(0, TIMELINE_HEIGHT + VERT_PADDING);
  268. guiEvents = new GUIAnimEvents(eventsPanel, this.width, EVENTS_HEIGHT);
  269. GUIPanel eventsBgPanel = eventsPanel.AddPanel(1);
  270. eventsBackground = new GUITexture(null, EditorStyles.Header);
  271. eventsBackground.Bounds = new Rect2I(0, 0, this.width, EVENTS_HEIGHT + VERT_PADDING);
  272. eventsBgPanel.AddElement(eventsBackground);
  273. eventsHeaderHeight = EVENTS_HEIGHT;
  274. }
  275. drawingPanel = mainPanel.AddPanel();
  276. drawingPanel.SetPosition(0, TIMELINE_HEIGHT + eventsHeaderHeight + VERT_PADDING);
  277. guiCurveDrawing = new GUICurves(drawOptions);
  278. guiCurveDrawing.SetWidth(this.width);
  279. guiCurveDrawing.SetHeight(this.height - TIMELINE_HEIGHT - eventsHeaderHeight - VERT_PADDING * 2);
  280. guiCurveDrawing.SetRange(60.0f, 20.0f);
  281. guiCurveDrawing.Curves = GetPlainCurveDrawInfos();
  282. drawingPanel.AddElement(guiCurveDrawing);
  283. GUIPanel sidebarPanel = mainPanel.AddPanel(-10);
  284. sidebarPanel.SetPosition(0, TIMELINE_HEIGHT + eventsHeaderHeight + VERT_PADDING);
  285. guiSidebar = new GUIGraphValues(sidebarPanel, SIDEBAR_WIDTH, this.height - TIMELINE_HEIGHT -
  286. eventsHeaderHeight - VERT_PADDING * 2);
  287. guiSidebar.SetRange(-10.0f, 10.0f);
  288. horzScrollBar.SetWidth(this.width);
  289. vertScrollBar.SetHeight(this.height);
  290. UpdateScrollBarSize();
  291. }
  292. /// <summary>
  293. /// Change the set of curves to display.
  294. /// </summary>
  295. /// <param name="curveInfos">New set of curves to draw on the GUI element.</param>
  296. public void SetCurves(EdCurveDrawInfo[] curveInfos)
  297. {
  298. this.curveInfos = curveInfos;
  299. guiCurveDrawing.Curves = GetPlainCurveDrawInfos();
  300. Redraw();
  301. }
  302. /// <summary>
  303. /// Change the physical size of the GUI element.
  304. /// </summary>
  305. /// <param name="width">Width of the element in pixels.</param>
  306. /// <param name="height">Height of the element in pixels.</param>
  307. public void SetSize(int width, int height)
  308. {
  309. this.width = Math.Max(0, width - scrollBarWidth);
  310. this.height = Math.Max(0, height - scrollBarHeight);
  311. int eventsHeaderHeight = 0;
  312. if (showEvents)
  313. {
  314. eventsHeaderHeight = EVENTS_HEIGHT;
  315. guiEvents.SetSize(this.width, EVENTS_HEIGHT);
  316. eventsBackground.Bounds = new Rect2I(0, 0, this.width, EVENTS_HEIGHT + VERT_PADDING);
  317. }
  318. guiTimeline.SetSize(this.width, TIMELINE_HEIGHT);
  319. guiCurveDrawing.SetWidth(this.width);
  320. guiCurveDrawing.SetHeight(this.height - TIMELINE_HEIGHT - eventsHeaderHeight);
  321. guiSidebar.SetSize(SIDEBAR_WIDTH, this.height - TIMELINE_HEIGHT - eventsHeaderHeight);
  322. timelineBackground.Bounds = new Rect2I(0, 0, this.width, TIMELINE_HEIGHT + VERT_PADDING);
  323. horzScrollBar.SetWidth(this.width);
  324. vertScrollBar.SetHeight(this.height);
  325. UpdateScrollBarSize();
  326. UpdateScrollBarPosition();
  327. }
  328. /// <summary>
  329. /// Number of frames per second, used for frame selection and marking.
  330. /// </summary>
  331. /// <param name="fps">Number of prames per second.</param>
  332. public void SetFPS(int fps)
  333. {
  334. guiTimeline.SetFPS(fps);
  335. guiCurveDrawing.FPS = fps;
  336. if(showEvents)
  337. guiEvents.SetFPS(fps);
  338. Redraw();
  339. }
  340. /// <summary>
  341. /// Sets a scene object that will be used for enumerating components/methods used for adding events.
  342. /// </summary>
  343. /// <param name="so">Scene object containing the animation component.</param>
  344. public void SetEventSceneObject(SceneObject so)
  345. {
  346. eventsSO = so;
  347. }
  348. /// <summary>
  349. /// Returns time for a frame with the specified index. Depends on set range and FPS.
  350. /// </summary>
  351. /// <param name="frameIdx">Index of the frame (not a key-frame) to get the time for.</param>
  352. /// <returns>Time of the frame with the provided index. </returns>
  353. public float GetTimeForFrame(int frameIdx)
  354. {
  355. return guiCurveDrawing.GetTimeForFrame(frameIdx);
  356. }
  357. /// <summary>
  358. /// Sets the frame at which to display the frame marker.
  359. /// </summary>
  360. /// <param name="frameIdx">Index of the frame to display the marker on, or -1 to clear the marker.</param>
  361. public void SetMarkedFrame(int frameIdx)
  362. {
  363. markedFrameIdx = frameIdx;
  364. guiTimeline.SetMarkedFrame(frameIdx);
  365. guiCurveDrawing.MarkedFrame = frameIdx;
  366. if(showEvents)
  367. guiEvents.SetMarkedFrame(frameIdx);
  368. Redraw();
  369. }
  370. /// <summary>
  371. /// Adds a new keyframe at the currently selected frame.
  372. /// </summary>
  373. public void AddKeyFrameAtMarker()
  374. {
  375. ClearSelection();
  376. if (!disableCurveEdit)
  377. {
  378. foreach (var curveInfo in curveInfos)
  379. {
  380. float t = guiCurveDrawing.GetTimeForFrame(markedFrameIdx);
  381. float value = curveInfo.curve.Evaluate(t);
  382. curveInfo.curve.AddOrUpdateKeyframe(t, value);
  383. curveInfo.curve.Apply();
  384. }
  385. }
  386. else
  387. ShowReadOnlyMessage();
  388. OnCurveModified?.Invoke();
  389. RefreshCurveDrawing();
  390. UpdateEventsGUI();
  391. }
  392. /// <summary>
  393. /// Adds a new event at the currently selected event.
  394. /// </summary>
  395. public void AddEventAtMarker()
  396. {
  397. ClearSelection();
  398. if (!showEvents)
  399. return;
  400. float eventTime = guiEvents.GetTimeForFrame(markedFrameIdx);
  401. EventInfo eventInfo = new EventInfo();
  402. eventInfo.animEvent = new AnimationEvent("", eventTime);
  403. events.Add(eventInfo);
  404. OnEventAdded?.Invoke();
  405. UpdateEventsGUI();
  406. StartEventEdit(events.Count - 1);
  407. }
  408. /// <summary>
  409. /// Rebuilds GUI displaying the animation events list.
  410. /// </summary>
  411. private void UpdateEventsGUI()
  412. {
  413. if (!showEvents)
  414. return;
  415. AnimationEvent[] animEvents = new AnimationEvent[events.Count];
  416. bool[] selected = new bool[events.Count];
  417. for (int i = 0; i < events.Count; i++)
  418. {
  419. animEvents[i] = events[i].animEvent;
  420. selected[i] = events[i].selected;
  421. }
  422. guiEvents.SetEvents(animEvents, selected);
  423. guiEvents.Rebuild();
  424. }
  425. /// <summary>
  426. /// Rebuilds the entire curve editor GUI.
  427. /// </summary>
  428. public void Redraw()
  429. {
  430. guiTimeline.Rebuild();
  431. guiSidebar.Rebuild();
  432. if(showEvents)
  433. guiEvents.Rebuild();
  434. }
  435. /// <summary>
  436. /// Updates the curve drawing. Should be called after animation curves change.
  437. /// </summary>
  438. private void RefreshCurveDrawing()
  439. {
  440. guiCurveDrawing.Curves = GetPlainCurveDrawInfos();
  441. }
  442. /// <summary>
  443. /// Changes the tangent mode for all currently selected keyframes.
  444. /// </summary>
  445. /// <param name="mode">Tangent mode to set. If only in or out tangent mode is provided, the mode for the opposite
  446. /// tangent will be kept as is.</param>
  447. private void ChangeSelectionTangentMode(TangentMode mode)
  448. {
  449. if (disableCurveEdit)
  450. {
  451. ShowReadOnlyMessage();
  452. return;
  453. }
  454. foreach (var selectedEntry in selectedKeyframes)
  455. {
  456. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  457. foreach (var keyframeIdx in selectedEntry.keyIndices)
  458. {
  459. if (mode == TangentMode.Auto || mode == TangentMode.Free)
  460. {
  461. curve.SetTangentMode(keyframeIdx, mode);
  462. // Refresh tangent display
  463. guiCurveDrawing.SelectKeyframe(new KeyframeRef(selectedEntry.curveIdx, keyframeIdx), mode, true);
  464. }
  465. else
  466. {
  467. TangentMode newMode = curve.TangentModes[keyframeIdx];
  468. if (mode.HasFlag((TangentMode) TangentType.In))
  469. {
  470. // Replace only the in tangent mode, keeping the out tangent as is
  471. TangentMode inFlags = (TangentMode.InAuto | TangentMode.InFree | TangentMode.InLinear |
  472. TangentMode.InStep);
  473. newMode &= ~inFlags;
  474. newMode |= (mode & inFlags);
  475. }
  476. else
  477. {
  478. // Replace only the out tangent mode, keeping the in tangent as is
  479. TangentMode outFlags = (TangentMode.OutAuto | TangentMode.OutFree | TangentMode.OutLinear |
  480. TangentMode.OutStep);
  481. newMode &= ~outFlags;
  482. newMode |= (mode & outFlags);
  483. }
  484. curve.SetTangentMode(keyframeIdx, newMode);
  485. // Refresh tangent display
  486. guiCurveDrawing.SelectKeyframe(new KeyframeRef(selectedEntry.curveIdx, keyframeIdx), newMode, true);
  487. }
  488. }
  489. curve.Apply();
  490. }
  491. OnCurveModified?.Invoke();
  492. RefreshCurveDrawing();
  493. }
  494. /// <summary>
  495. /// Adds a new keyframe at the specified time on the provided curve.
  496. /// </summary>
  497. /// <param name="curveIdx">Index of the curve to add the keyframe to.</param>
  498. /// <param name="time">Time at which to add the keyframe.</param>
  499. private void AddKeyframe(int curveIdx, float time)
  500. {
  501. ClearSelection();
  502. if (!disableCurveEdit)
  503. {
  504. if (curveIdx < curveInfos.Length)
  505. {
  506. EdAnimationCurve curve = curveInfos[curveIdx].curve;
  507. float value = curve.Evaluate(time, false);
  508. curve.AddOrUpdateKeyframe(time, value);
  509. curve.Apply();
  510. }
  511. }
  512. else
  513. ShowReadOnlyMessage();
  514. OnCurveModified?.Invoke();
  515. RefreshCurveDrawing();
  516. UpdateEventsGUI();
  517. }
  518. /// <summary>
  519. /// Adds a new keyframe at the position the context menu was opened at.
  520. /// </summary>
  521. private void AddKeyframeAtPosition()
  522. {
  523. Vector2 curveCoord;
  524. if (guiCurveDrawing.PixelToCurveSpace(contextClickPosition, out curveCoord))
  525. {
  526. ClearSelection();
  527. if (!disableCurveEdit)
  528. {
  529. foreach (var curveInfo in curveInfos)
  530. {
  531. float t = curveCoord.x;
  532. float value = curveCoord.y;
  533. curveInfo.curve.AddOrUpdateKeyframe(t, value);
  534. curveInfo.curve.Apply();
  535. }
  536. }
  537. else
  538. ShowReadOnlyMessage();
  539. OnCurveModified?.Invoke();
  540. RefreshCurveDrawing();
  541. UpdateEventsGUI();
  542. }
  543. }
  544. /// <summary>
  545. /// Adds a new event at the position the context menu was opened at.
  546. /// </summary>
  547. private void AddEventAtPosition()
  548. {
  549. if (!showEvents)
  550. return;
  551. int frame = guiEvents.GetFrame(contextClickPosition);
  552. if (frame != -1)
  553. {
  554. ClearSelection();
  555. float time = guiEvents.GetTime(contextClickPosition.x);
  556. EventInfo eventInfo = new EventInfo();
  557. eventInfo.animEvent = new AnimationEvent("", time);
  558. events.Add(eventInfo);
  559. OnEventAdded?.Invoke();
  560. UpdateEventsGUI();
  561. StartEventEdit(events.Count - 1);
  562. }
  563. }
  564. /// <summary>
  565. /// Removes all currently selected keyframes from the curves.
  566. /// </summary>
  567. private void DeleteSelectedKeyframes()
  568. {
  569. if (!disableCurveEdit)
  570. {
  571. foreach (var selectedEntry in selectedKeyframes)
  572. {
  573. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  574. // Sort keys from highest to lowest so the indices don't change
  575. selectedEntry.keyIndices.Sort((x, y) =>
  576. {
  577. return y.CompareTo(x);
  578. });
  579. foreach (var keyframeIdx in selectedEntry.keyIndices)
  580. curve.RemoveKeyframe(keyframeIdx);
  581. curve.Apply();
  582. }
  583. }
  584. else
  585. ShowReadOnlyMessage();
  586. ClearSelection();
  587. OnCurveModified?.Invoke();
  588. RefreshCurveDrawing();
  589. UpdateEventsGUI();
  590. }
  591. /// <summary>
  592. /// Deletes all currently selected events.
  593. /// </summary>
  594. private void DeleteSelectedEvents()
  595. {
  596. List<EventInfo> newEvents = new List<EventInfo>();
  597. foreach (var entry in events)
  598. {
  599. if(!entry.selected)
  600. newEvents.Add(entry);
  601. }
  602. events = newEvents;
  603. OnEventDeleted?.Invoke();
  604. ClearSelection();
  605. UpdateEventsGUI();
  606. }
  607. /// <summary>
  608. /// Unselects any selected keyframes and events.
  609. /// </summary>
  610. private void ClearSelection()
  611. {
  612. guiCurveDrawing.ClearSelectedKeyframes();
  613. selectedKeyframes.Clear();
  614. foreach (var entry in events)
  615. entry.selected = false;
  616. }
  617. /// <summary>
  618. /// Adds the provided keyframe to the selection list (doesn't clear existing ones).
  619. /// </summary>
  620. /// <param name="keyframeRef">Keyframe to select.</param>
  621. private void SelectKeyframe(KeyframeRef keyframeRef)
  622. {
  623. TangentMode tangentMode = TangentMode.Auto;
  624. if (keyframeRef.curveIdx >= 0 && keyframeRef.curveIdx < curveInfos.Length)
  625. {
  626. EdAnimationCurve curve = curveInfos[keyframeRef.curveIdx].curve;
  627. if (keyframeRef.keyIdx >= 0 && keyframeRef.keyIdx < curve.TangentModes.Length)
  628. tangentMode = curve.TangentModes[keyframeRef.keyIdx];
  629. }
  630. guiCurveDrawing.SelectKeyframe(keyframeRef, tangentMode, true);
  631. if (!IsSelected(keyframeRef))
  632. {
  633. int curveIdx = selectedKeyframes.FindIndex(x =>
  634. {
  635. return x.curveIdx == keyframeRef.curveIdx;
  636. });
  637. if (curveIdx == -1)
  638. {
  639. curveIdx = selectedKeyframes.Count;
  640. SelectedKeyframes newKeyframes = new SelectedKeyframes();
  641. newKeyframes.curveIdx = keyframeRef.curveIdx;
  642. selectedKeyframes.Add(newKeyframes);
  643. }
  644. selectedKeyframes[curveIdx].keyIndices.Add(keyframeRef.keyIdx);
  645. }
  646. }
  647. /// <summary>
  648. /// Checks is the provided keyframe currently selected.
  649. /// </summary>
  650. /// <param name="keyframeRef">Keyframe to check.</param>
  651. /// <returns>True if selected, false otherwise.</returns>
  652. private bool IsSelected(KeyframeRef keyframeRef)
  653. {
  654. int curveIdx = selectedKeyframes.FindIndex(x =>
  655. {
  656. return x.curveIdx == keyframeRef.curveIdx;
  657. });
  658. if (curveIdx == -1)
  659. return false;
  660. int keyIdx = selectedKeyframes[curveIdx].keyIndices.FindIndex(x =>
  661. {
  662. return x == keyframeRef.keyIdx;
  663. });
  664. return keyIdx != -1;
  665. }
  666. /// <summary>
  667. /// Opens the edit window for the currently selected keyframe.
  668. /// </summary>
  669. private void EditSelectedKeyframe()
  670. {
  671. if (disableCurveEdit)
  672. {
  673. ShowReadOnlyMessage();
  674. return;
  675. }
  676. if (selectedKeyframes.Count == 0)
  677. return;
  678. EdAnimationCurve curve = curveInfos[selectedKeyframes[0].curveIdx].curve;
  679. KeyFrame[] keyFrames = curve.KeyFrames;
  680. int keyIndex = selectedKeyframes[0].keyIndices[0];
  681. KeyFrame keyFrame = keyFrames[keyIndex];
  682. Vector2I position = guiCurveDrawing.CurveToPixelSpace(new Vector2(keyFrame.time, keyFrame.value));
  683. Rect2I drawingBounds = drawingPanel.Bounds;
  684. position.x = MathEx.Clamp(position.x, 0, drawingBounds.width);
  685. position.y = MathEx.Clamp(position.y, 0, drawingBounds.height);
  686. KeyframeEditWindow editWindow = DropDownWindow.Open<KeyframeEditWindow>(drawingPanel, position);
  687. editWindow.Initialize(keyFrame, x =>
  688. {
  689. curve.UpdateKeyframe(keyIndex, x.time, x.value);
  690. curve.Apply();
  691. RefreshCurveDrawing();
  692. },
  693. x =>
  694. {
  695. if (x)
  696. OnCurveModified?.Invoke();
  697. });
  698. }
  699. /// <summary>
  700. /// Opens the edit window for the currently selected event.
  701. /// </summary>
  702. private void EditSelectedEvent()
  703. {
  704. if (!showEvents)
  705. return;
  706. for (int i = 0; i < events.Count; i++)
  707. {
  708. if (events[i].selected)
  709. {
  710. StartEventEdit(i);
  711. break;
  712. }
  713. }
  714. }
  715. /// <summary>
  716. /// Opens the event edit window for the specified event.
  717. /// </summary>
  718. /// <param name="eventIdx">Event index to open the edit window for.</param>
  719. private void StartEventEdit(int eventIdx)
  720. {
  721. if (!showEvents || eventsSO == null)
  722. return;
  723. AnimationEvent animEvent = events[eventIdx].animEvent;
  724. Vector2I position = new Vector2I();
  725. position.x = guiEvents.GetOffset(animEvent.time);
  726. position.y = EVENTS_HEIGHT/2;
  727. Component[] components = eventsSO.GetComponents();
  728. string[] componentNames = new string[components.Length];
  729. for (int i = 0; i < components.Length; i++)
  730. componentNames[i] = components[i].GetType().Name;
  731. EventEditWindow editWindow = DropDownWindow.Open<EventEditWindow>(eventsPanel, position);
  732. editWindow.Initialize(animEvent, componentNames, () =>
  733. {
  734. UpdateEventsGUI();
  735. },
  736. x =>
  737. {
  738. if(x)
  739. OnEventModified?.Invoke();
  740. });
  741. }
  742. /// <summary>
  743. /// Shows a dialog box that notifies the user that the animation clip is read only.
  744. /// </summary>
  745. private void ShowReadOnlyMessage()
  746. {
  747. LocEdString title = new LocEdString("Warning");
  748. LocEdString message =
  749. new LocEdString("You cannot edit keyframes on animation clips that" +
  750. " are imported from an external file.");
  751. DialogBox.Open(title, message, DialogBox.Type.OK);
  752. }
  753. #region Input
  754. /// <summary>
  755. /// Handles input. Should be called by the owning window whenever a pointer is pressed.
  756. /// </summary>
  757. /// <param name="ev">Object containing pointer press event information.</param>
  758. internal void OnPointerPressed(PointerEvent ev)
  759. {
  760. if (ev.IsUsed)
  761. return;
  762. Rect2I elementBounds = mainPanel.ScreenBounds;
  763. Vector2I pointerPos = ev.ScreenPos - new Vector2I(elementBounds.x, elementBounds.y);
  764. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  765. if (!isOverEditor)
  766. return;
  767. else
  768. OnClicked?.Invoke();
  769. Rect2I drawingBounds = drawingPanel.Bounds;
  770. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  771. Rect2I eventBounds = new Rect2I();
  772. if(showEvents)
  773. eventBounds = eventsPanel.Bounds;
  774. Vector2I eventPos = pointerPos - new Vector2I(eventBounds.x, eventBounds.y);
  775. if (ev.Button == PointerButton.Left)
  776. {
  777. Vector2 curveCoord;
  778. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  779. {
  780. KeyframeRef keyframeRef;
  781. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  782. {
  783. TangentRef tangentRef;
  784. if (guiCurveDrawing.FindTangent(drawingPos, out tangentRef))
  785. {
  786. isMousePressedOverTangent = true;
  787. dragStart = drawingPos;
  788. draggedTangent = tangentRef;
  789. }
  790. else
  791. ClearSelection();
  792. }
  793. else
  794. {
  795. if (!IsSelected(keyframeRef))
  796. {
  797. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  798. ClearSelection();
  799. SelectKeyframe(keyframeRef);
  800. }
  801. isMousePressedOverKey = true;
  802. dragStart = drawingPos;
  803. }
  804. UpdateEventsGUI();
  805. }
  806. else
  807. {
  808. int frameIdx = guiTimeline.GetFrame(pointerPos);
  809. if (frameIdx != -1)
  810. SetMarkedFrame(frameIdx);
  811. else
  812. {
  813. int eventIdx;
  814. if (showEvents && guiEvents.FindEvent(eventPos, out eventIdx))
  815. {
  816. if (!Input.IsButtonHeld(ButtonCode.LeftShift) && !Input.IsButtonHeld(ButtonCode.RightShift))
  817. ClearSelection();
  818. events[eventIdx].selected = true;
  819. UpdateEventsGUI();
  820. }
  821. else
  822. {
  823. ClearSelection();
  824. UpdateEventsGUI();
  825. }
  826. }
  827. OnFrameSelected?.Invoke(frameIdx);
  828. }
  829. isPointerHeld = true;
  830. }
  831. else if (ev.Button == PointerButton.Right)
  832. {
  833. Vector2 curveCoord;
  834. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord, true))
  835. {
  836. contextClickPosition = drawingPos;
  837. KeyframeRef keyframeRef;
  838. if (!guiCurveDrawing.FindKeyFrame(drawingPos, out keyframeRef))
  839. {
  840. ClearSelection();
  841. blankContextMenu.Open(pointerPos, mainPanel);
  842. UpdateEventsGUI();
  843. }
  844. else
  845. {
  846. // If clicked outside of current selection, just select the one keyframe
  847. if (!IsSelected(keyframeRef))
  848. {
  849. ClearSelection();
  850. SelectKeyframe(keyframeRef);
  851. UpdateEventsGUI();
  852. }
  853. keyframeContextMenu.Open(pointerPos, mainPanel);
  854. }
  855. }
  856. else if (showEvents && guiEvents.GetFrame(eventPos) != -1) // Clicked over events bar
  857. {
  858. contextClickPosition = eventPos;
  859. int eventIdx;
  860. if (!guiEvents.FindEvent(eventPos, out eventIdx))
  861. {
  862. ClearSelection();
  863. blankEventContextMenu.Open(pointerPos, mainPanel);
  864. UpdateEventsGUI();
  865. }
  866. else
  867. {
  868. // If clicked outside of current selection, just select the one event
  869. if (!events[eventIdx].selected)
  870. {
  871. ClearSelection();
  872. events[eventIdx].selected = true;
  873. UpdateEventsGUI();
  874. }
  875. eventContextMenu.Open(pointerPos, mainPanel);
  876. }
  877. }
  878. }
  879. else if (ev.button == PointerButton.Middle)
  880. {
  881. Vector2 curvePos;
  882. if (WindowToCurveSpace(pointerPos, out curvePos))
  883. {
  884. dragStartPos = pointerPos;
  885. isMiddlePointerHeld = true;
  886. }
  887. }
  888. }
  889. /// <summary>
  890. /// Handles input. Should be called by the owning window whenever a pointer is double-clicked.
  891. /// </summary>
  892. /// <param name="ev">Object containing pointer press event information.</param>
  893. internal void OnPointerDoubleClicked(PointerEvent ev)
  894. {
  895. if (ev.IsUsed)
  896. return;
  897. Rect2I elementBounds = mainPanel.ScreenBounds;
  898. Vector2I pointerPos = ev.ScreenPos - new Vector2I(elementBounds.x, elementBounds.y);
  899. bool isOverEditor = pointerPos.x >= 0 && pointerPos.x < width && pointerPos.y >= 0 && pointerPos.y < height;
  900. if (!isOverEditor)
  901. return;
  902. Rect2I drawingBounds = drawingPanel.Bounds;
  903. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  904. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out var curveCoord, true))
  905. {
  906. int curveIdx = (int)guiCurveDrawing.FindCurve(drawingPos);
  907. if (curveIdx == -1)
  908. return;
  909. AddKeyframe(curveIdx, curveCoord.x);
  910. }
  911. }
  912. /// <summary>
  913. /// Handles input. Should be called by the owning window whenever a pointer is moved.
  914. /// </summary>
  915. /// <param name="ev">Object containing pointer move event information.</param>
  916. internal void OnPointerMoved(PointerEvent ev)
  917. {
  918. if (ev.Button != PointerButton.Left)
  919. return;
  920. if (isPointerHeld)
  921. {
  922. Rect2I elementBounds = mainPanel.ScreenBounds;
  923. Vector2I pointerPos = ev.ScreenPos - new Vector2I(elementBounds.x, elementBounds.y);
  924. if (isMousePressedOverKey || isMousePressedOverTangent)
  925. {
  926. Rect2I drawingBounds = drawingPanel.Bounds;
  927. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  928. if (!isDragInProgress)
  929. {
  930. int distance = Vector2I.Distance(drawingPos, dragStart);
  931. if (distance >= DRAG_START_DISTANCE)
  932. {
  933. if (isMousePressedOverKey && !disableCurveEdit)
  934. {
  935. draggedKeyframes.Clear();
  936. foreach (var selectedEntry in selectedKeyframes)
  937. {
  938. EdAnimationCurve curve = curveInfos[selectedEntry.curveIdx].curve;
  939. KeyFrame[] keyFrames = curve.KeyFrames;
  940. DraggedKeyframes newEntry = new DraggedKeyframes();
  941. newEntry.curveIdx = selectedEntry.curveIdx;
  942. draggedKeyframes.Add(newEntry);
  943. foreach (var keyframeIdx in selectedEntry.keyIndices)
  944. newEntry.keys.Add(new DraggedKeyframe(keyframeIdx, keyFrames[keyframeIdx]));
  945. }
  946. }
  947. isDragInProgress = true;
  948. }
  949. }
  950. if (isDragInProgress)
  951. {
  952. if (isMousePressedOverKey && !disableCurveEdit)
  953. {
  954. Vector2 diff = Vector2.Zero;
  955. Vector2 dragStartCurve;
  956. if (guiCurveDrawing.PixelToCurveSpace(dragStart, out dragStartCurve, true))
  957. {
  958. Vector2 currentPosCurve;
  959. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  960. diff = currentPosCurve - dragStartCurve;
  961. }
  962. foreach (var draggedEntry in draggedKeyframes)
  963. {
  964. EdAnimationCurve curve = curveInfos[draggedEntry.curveIdx].curve;
  965. for (int i = 0; i < draggedEntry.keys.Count; i++)
  966. {
  967. DraggedKeyframe draggedKey = draggedEntry.keys[i];
  968. float newTime = Math.Max(0.0f, draggedKey.original.time + diff.x);
  969. float newValue = draggedKey.original.value + diff.y;
  970. int newIndex = curve.UpdateKeyframe(draggedKey.index, newTime, newValue);
  971. // It's possible key changed position due to time change, but since we're moving all
  972. // keys at once they cannot change position relative to one another, otherwise we would
  973. // need to update indices for other keys as well.
  974. draggedKey.index = newIndex;
  975. draggedEntry.keys[i] = draggedKey;
  976. }
  977. curve.Apply();
  978. }
  979. // Rebuild selected keys from dragged keys (after potential sorting)
  980. ClearSelection();
  981. foreach (var draggedEntry in draggedKeyframes)
  982. {
  983. foreach (var keyframe in draggedEntry.keys)
  984. SelectKeyframe(new KeyframeRef(draggedEntry.curveIdx, keyframe.index));
  985. }
  986. isModifiedDuringDrag = true;
  987. RefreshCurveDrawing();
  988. UpdateEventsGUI();
  989. }
  990. else if (isMousePressedOverTangent && !disableCurveEdit)
  991. {
  992. EdAnimationCurve curve = curveInfos[draggedTangent.keyframeRef.curveIdx].curve;
  993. KeyFrame keyframe = curve.KeyFrames[draggedTangent.keyframeRef.keyIdx];
  994. Vector2 keyframeCurveCoords = new Vector2(keyframe.time, keyframe.value);
  995. Vector2 currentPosCurve;
  996. if (guiCurveDrawing.PixelToCurveSpace(drawingPos, out currentPosCurve, true))
  997. {
  998. Vector2 normal = currentPosCurve - keyframeCurveCoords;
  999. normal = normal.Normalized;
  1000. float tangent = EdAnimationCurve.NormalToTangent(normal);
  1001. if (draggedTangent.type == TangentType.In)
  1002. {
  1003. if (normal.x > 0.0f)
  1004. tangent = float.PositiveInfinity;
  1005. else
  1006. tangent = -tangent;
  1007. keyframe.inTangent = tangent;
  1008. if(curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1009. keyframe.outTangent = tangent;
  1010. }
  1011. else
  1012. {
  1013. if (normal.x < 0.0f)
  1014. tangent = float.PositiveInfinity;
  1015. keyframe.outTangent = tangent;
  1016. if (curve.TangentModes[draggedTangent.keyframeRef.keyIdx] == TangentMode.Free)
  1017. keyframe.inTangent = tangent;
  1018. }
  1019. curve.KeyFrames[draggedTangent.keyframeRef.keyIdx] = keyframe;
  1020. curve.Apply();
  1021. isModifiedDuringDrag = true;
  1022. RefreshCurveDrawing();
  1023. }
  1024. }
  1025. }
  1026. }
  1027. else // Move frame marker
  1028. {
  1029. int frameIdx = guiTimeline.GetFrame(pointerPos);
  1030. if (frameIdx != -1)
  1031. SetMarkedFrame(frameIdx);
  1032. OnFrameSelected?.Invoke(frameIdx);
  1033. }
  1034. }
  1035. if (isMiddlePointerHeld)
  1036. {
  1037. Rect2I elementBounds = mainPanel.ScreenBounds;
  1038. Vector2I pointerPos = ev.ScreenPos - new Vector2I(elementBounds.x, elementBounds.y);
  1039. int distance = Vector2I.Distance(dragStartPos, pointerPos);
  1040. if (distance >= DRAG_START_DISTANCE)
  1041. {
  1042. isZoomDragInProgress = true;
  1043. Cursor.Hide();
  1044. Rect2I clipRect;
  1045. clipRect.x = ev.ScreenPos.x - 2;
  1046. clipRect.y = ev.ScreenPos.y - 2;
  1047. clipRect.width = 4;
  1048. clipRect.height = 4;
  1049. Cursor.ClipToRect(clipRect);
  1050. }
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// Handles input. Should be called by the owning window whenever a pointer is released.
  1055. /// </summary>
  1056. /// <param name="ev">Object containing pointer release event information.</param>
  1057. internal void OnPointerReleased(PointerEvent ev)
  1058. {
  1059. if (isZoomDragInProgress)
  1060. {
  1061. Cursor.Show();
  1062. Cursor.ClipDisable();
  1063. }
  1064. if (isModifiedDuringDrag)
  1065. OnCurveModified?.Invoke();
  1066. isMiddlePointerHeld = false;
  1067. isZoomDragInProgress = false;
  1068. isPointerHeld = false;
  1069. isDragInProgress = false;
  1070. isMousePressedOverKey = false;
  1071. isMousePressedOverTangent = false;
  1072. isModifiedDuringDrag = false;
  1073. }
  1074. /// <summary>
  1075. /// Handles input. Should be called by the owning window whenever a button is released.
  1076. /// </summary>
  1077. /// <param name="ev">Object containing button release event information.</param>
  1078. internal void OnButtonUp(ButtonEvent ev)
  1079. {
  1080. if(ev.Button == ButtonCode.Delete)
  1081. DeleteSelectedKeyframes();
  1082. }
  1083. #endregion
  1084. #region Scroll, drag, zoom
  1085. private Vector2I dragStartPos;
  1086. private bool isMiddlePointerHeld;
  1087. private bool isZoomDragInProgress;
  1088. private float zoomAmount;
  1089. /// <summary>
  1090. /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
  1091. /// Should be called every frame.
  1092. /// </summary>
  1093. internal void HandleDragAndZoomInput()
  1094. {
  1095. // Handle middle mouse dragging
  1096. if (isZoomDragInProgress)
  1097. {
  1098. float lengthPerPixel = Range.x / Width;
  1099. float heightPerPixel = Range.y / Height;
  1100. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  1101. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  1102. Vector2 offset = Offset;
  1103. offset.x = Math.Max(0.0f, offset.x + dragX);
  1104. offset.y -= dragY;
  1105. Offset = offset;
  1106. UpdateScrollBarSize();
  1107. UpdateScrollBarPosition();
  1108. }
  1109. // Handle zoom in/out
  1110. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  1111. if (scroll != 0.0f)
  1112. {
  1113. Rect2I elementBounds = mainPanel.ScreenBounds;
  1114. Vector2I pointerPos = Input.PointerPosition - new Vector2I(elementBounds.x, elementBounds.y);
  1115. Vector2 curvePos;
  1116. if (WindowToCurveSpace(pointerPos, out curvePos))
  1117. {
  1118. float zoom = scroll * ZOOM_SCALE;
  1119. Zoom(curvePos, zoom);
  1120. }
  1121. }
  1122. }
  1123. /// <summary>
  1124. /// Moves or resizes the vertical scroll bar under the curve editor.
  1125. /// </summary>
  1126. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1127. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1128. private void SetVertScrollbarProperties(float position, float size)
  1129. {
  1130. Vector2 visibleRange = Range;
  1131. Vector2 totalRange = GetTotalRange();
  1132. visibleRange.y = totalRange.y*size;
  1133. Range = visibleRange;
  1134. float scrollableRange = totalRange.y - visibleRange.y;
  1135. Vector2 offset = Offset;
  1136. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  1137. Offset = offset;
  1138. }
  1139. /// <summary>
  1140. /// Moves or resizes the horizontal scroll bar under the curve editor.
  1141. /// </summary>
  1142. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1143. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  1144. private void SetHorzScrollbarProperties(float position, float size)
  1145. {
  1146. Vector2 visibleRange = Range;
  1147. Vector2 totalRange = GetTotalRange();
  1148. visibleRange.x = totalRange.x * size;
  1149. Range = visibleRange;
  1150. float scrollableRange = totalRange.x - visibleRange.x;
  1151. Vector2 offset = Offset;
  1152. offset.x = scrollableRange * position;
  1153. Offset = offset;
  1154. }
  1155. /// <summary>
  1156. /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
  1157. /// </summary>
  1158. private void UpdateScrollBarSize()
  1159. {
  1160. Vector2 visibleRange = Range;
  1161. Vector2 totalRange = GetTotalRange();
  1162. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  1163. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  1164. }
  1165. /// <summary>
  1166. /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
  1167. /// </summary>
  1168. private void UpdateScrollBarPosition()
  1169. {
  1170. Vector2 visibleRange = Range;
  1171. Vector2 totalRange = GetTotalRange();
  1172. Vector2 scrollableRange = totalRange - visibleRange;
  1173. Vector2 offset = Offset;
  1174. if (scrollableRange.x > 0.0f)
  1175. horzScrollBar.Position = offset.x / scrollableRange.x;
  1176. else
  1177. horzScrollBar.Position = 0.0f;
  1178. if (scrollableRange.y > 0.0f)
  1179. {
  1180. float pos = offset.y/scrollableRange.y;
  1181. float sign = MathEx.Sign(pos);
  1182. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  1183. pos = (1.0f - pos) /2.0f;
  1184. vertScrollBar.Position = pos;
  1185. }
  1186. else
  1187. vertScrollBar.Position = 0.0f;
  1188. }
  1189. /// <summary>
  1190. /// Calculates the width/height of the curve area depending on the current zoom level.
  1191. /// </summary>
  1192. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1193. private Vector2 GetZoomedRange()
  1194. {
  1195. float zoomLevel = MathEx.Pow(2, zoomAmount);
  1196. GetOptimalRangeAndOffset(out _, out var optimalRange);
  1197. return optimalRange / zoomLevel;
  1198. }
  1199. /// <summary>
  1200. /// Returns the total width/height of the contents of the curve area.
  1201. /// </summary>
  1202. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1203. private Vector2 GetTotalRange()
  1204. {
  1205. // Return optimal range (that covers the visible curve)
  1206. GetOptimalRangeAndOffset(out _, out var range);
  1207. // Increase range in case user zoomed out
  1208. Vector2 zoomedRange = GetZoomedRange();
  1209. return Vector2.Max(range, zoomedRange);
  1210. }
  1211. /// <summary>
  1212. /// Zooms in or out at the provided position in the curve display.
  1213. /// </summary>
  1214. /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
  1215. /// (value, time)</param>
  1216. /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
  1217. private void Zoom(Vector2 curvePos, float amount)
  1218. {
  1219. // Increase or decrease the visible range depending on zoom level
  1220. Vector2 oldZoomedRange = GetZoomedRange();
  1221. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  1222. Vector2 zoomedRange = GetZoomedRange();
  1223. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  1224. Vector2 currentRange = Range;
  1225. Vector2 newRange = currentRange + zoomedDiff;
  1226. newRange.x = Math.Max(0, newRange.x);
  1227. Range = newRange;
  1228. // When zooming, make sure to focus on the point provided, so adjust the offset
  1229. Vector2 rangeScale = newRange;
  1230. rangeScale.x /= currentRange.x;
  1231. rangeScale.y /= currentRange.y;
  1232. UpdateScrollBarSize();
  1233. UpdateScrollBarPosition();
  1234. }
  1235. /// <summary>
  1236. /// Updates the offset and range of the curve display to fully fit the currently selected set of curves.
  1237. /// </summary>
  1238. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  1239. /// be kept as is.</param>
  1240. internal void CenterAndResize(bool resetTime)
  1241. {
  1242. GetOptimalRangeAndOffset(out var offset, out var range);
  1243. if (!resetTime)
  1244. {
  1245. offset.x = Offset.x;
  1246. range.x = Range.x;
  1247. }
  1248. Range = range;
  1249. Offset = offset;
  1250. UpdateScrollBarPosition();
  1251. UpdateScrollBarSize();
  1252. }
  1253. /// <summary>
  1254. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1255. /// </summary>
  1256. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1257. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1258. private void OnHorzScrollOrResize(float position, float size)
  1259. {
  1260. SetHorzScrollbarProperties(position, size);
  1261. }
  1262. /// <summary>
  1263. /// Triggered when the user moves or resizes the vertical scrollbar.
  1264. /// </summary>
  1265. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1266. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1267. private void OnVertScrollOrResize(float position, float size)
  1268. {
  1269. SetVertScrollbarProperties(position, size);
  1270. }
  1271. #endregion
  1272. #region Helpers
  1273. /// <summary>
  1274. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1275. /// </summary>
  1276. /// <param name="offset">Offset used for centering the curves.</param>
  1277. /// <param name="range">Range representing the width/height in curve space (time, value). </param>
  1278. private void GetOptimalRangeAndOffset(out Vector2 offset, out Vector2 range)
  1279. {
  1280. AnimationCurve[] curves = new AnimationCurve[curveInfos.Length];
  1281. for(int i = 0; i < curveInfos.Length; i++)
  1282. curves[i] = curveInfos[i].curve.Normal;
  1283. float xMin, xMax;
  1284. float yMin, yMax;
  1285. AnimationUtility.CalculateRange(curves, out xMin, out xMax, out yMin, out yMax);
  1286. float xRange = xMax - xMin;
  1287. float yRange = (yMax - yMin) * 0.5f;
  1288. float yOffset = yMin + yRange;
  1289. // Add padding to y range
  1290. yRange *= 1.05f;
  1291. // Don't allow zero range
  1292. if (xRange == 0.0f)
  1293. xRange = 60.0f;
  1294. if (yRange == 0.0f)
  1295. yRange = 10.0f;
  1296. offset = new Vector2(xMin, yOffset);
  1297. range = new Vector2(xRange, yRange);
  1298. }
  1299. /// <summary>
  1300. /// Returns a set of current curve draw infos with non-editor curves.
  1301. /// </summary>
  1302. /// <returns>Curve draw infos.</returns>
  1303. private CurveDrawInfo[] GetPlainCurveDrawInfos()
  1304. {
  1305. CurveDrawInfo[] output = new CurveDrawInfo[curveInfos.Length];
  1306. for(int i = 0; i < curveInfos.Length; i++)
  1307. output[i] = new CurveDrawInfo(curveInfos[i].curve.Normal, curveInfos[i].color);
  1308. return output;
  1309. }
  1310. /// <summary>
  1311. /// Converts coordinate in curve space (time, value) into pixel coordinates relative to the curve drawing area
  1312. /// origin.
  1313. /// </summary>
  1314. /// <param name="curveCoords">Time and value of the location to convert.</param>
  1315. /// <returns>Coordinates relative to curve drawing area's origin, in pixels.</returns>
  1316. public Vector2I CurveToPixelSpace(Vector2 curveCoords)
  1317. {
  1318. return guiCurveDrawing.CurveToPixelSpace(curveCoords);
  1319. }
  1320. /// <summary>
  1321. /// Converts coordinates in window space (relative to the parent window origin) into coordinates in curve space.
  1322. /// </summary>
  1323. /// <param name="pointerPos">Coordinates relative to this GUI element, in pixels.</param>
  1324. /// <param name="curveCoord">Curve coordinates within the range as specified by <see cref="Range"/>. Only
  1325. /// valid when function returns true.</param>
  1326. /// <returns>True if the coordinates are within the curve area, false otherwise.</returns>
  1327. public bool WindowToCurveSpace(Vector2I pointerPos, out Vector2 curveCoord)
  1328. {
  1329. Rect2I drawingBounds = drawingPanel.Bounds;
  1330. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  1331. return guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord);
  1332. }
  1333. #endregion
  1334. }
  1335. /// <summary>
  1336. /// Information necessary to drawing an editor curve.
  1337. /// </summary>
  1338. public struct EdCurveDrawInfo
  1339. {
  1340. public EdCurveDrawInfo(EdAnimationCurve curve, Color color)
  1341. {
  1342. this.curve = curve;
  1343. this.color = color;
  1344. }
  1345. public EdAnimationCurve curve;
  1346. public Color color;
  1347. }
  1348. /// <summary>
  1349. /// Drop down window that displays input boxes used for editing a keyframe.
  1350. /// </summary>
  1351. [DefaultSize(120, 80)]
  1352. internal class KeyframeEditWindow : DropDownWindow
  1353. {
  1354. private Action<bool> closeCallback;
  1355. private bool changesMade;
  1356. /// <summary>
  1357. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1358. /// use.
  1359. /// </summary>
  1360. /// <param name="keyFrame">Keyframe whose properties to edit.</param>
  1361. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1362. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1363. internal void Initialize(KeyFrame keyFrame, Action<KeyFrame> updateCallback, Action<bool> closeCallback)
  1364. {
  1365. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1366. timeField.Value = keyFrame.time;
  1367. timeField.OnChanged += x => { keyFrame.time = x; changesMade = true; updateCallback(keyFrame); };
  1368. GUIFloatField valueField = new GUIFloatField(new LocEdString("Value"), 40, "");
  1369. valueField.Value = keyFrame.value;
  1370. valueField.OnChanged += x => { keyFrame.value = x; changesMade = true; updateCallback(keyFrame); };
  1371. GUILayoutY vertLayout = GUI.AddLayoutY();
  1372. vertLayout.AddFlexibleSpace();
  1373. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1374. horzLayout.AddFlexibleSpace();
  1375. GUILayout contentLayout = horzLayout.AddLayoutY();
  1376. GUILayout timeLayout = contentLayout.AddLayoutX();
  1377. timeLayout.AddSpace(5);
  1378. timeLayout.AddElement(timeField);
  1379. timeLayout.AddFlexibleSpace();
  1380. GUILayout componentLayout = contentLayout.AddLayoutX();
  1381. componentLayout.AddSpace(5);
  1382. componentLayout.AddElement(valueField);
  1383. componentLayout.AddFlexibleSpace();
  1384. horzLayout.AddFlexibleSpace();
  1385. vertLayout.AddFlexibleSpace();
  1386. this.closeCallback = closeCallback;
  1387. }
  1388. private void OnDestroy()
  1389. {
  1390. closeCallback?.Invoke(changesMade);
  1391. }
  1392. }
  1393. /// <summary>
  1394. /// Drop down window that displays input boxes used for editing an event.
  1395. /// </summary>
  1396. [DefaultSize(200, 80)]
  1397. internal class EventEditWindow : DropDownWindow
  1398. {
  1399. private Action<bool> closeCallback;
  1400. private bool changesMade;
  1401. /// <summary>
  1402. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1403. /// use.
  1404. /// </summary>
  1405. /// <param name="animEvent">Event whose properties to edit.</param>
  1406. /// <param name="componentNames">List of component names that the user can select from.</param>
  1407. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1408. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1409. internal void Initialize(AnimationEvent animEvent, string[] componentNames, Action updateCallback,
  1410. Action<bool> closeCallback)
  1411. {
  1412. int selectedIndex = -1;
  1413. string methodName = "";
  1414. if (!string.IsNullOrEmpty(animEvent.name))
  1415. {
  1416. string[] nameEntries = animEvent.name.Split('/');
  1417. if (nameEntries.Length > 1)
  1418. {
  1419. string typeName = nameEntries[0];
  1420. for (int i = 0; i < componentNames.Length; i++)
  1421. {
  1422. if (componentNames[i] == typeName)
  1423. {
  1424. selectedIndex = i;
  1425. break;
  1426. }
  1427. }
  1428. methodName = nameEntries[nameEntries.Length - 1];
  1429. }
  1430. }
  1431. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1432. timeField.Value = animEvent.time;
  1433. timeField.OnChanged += x => { animEvent.time = x; changesMade = true; updateCallback(); };
  1434. GUIListBoxField componentField = new GUIListBoxField(componentNames, new LocEdString("Component"), 40);
  1435. if (selectedIndex != -1)
  1436. componentField.Index = selectedIndex;
  1437. componentField.OnSelectionChanged += x =>
  1438. {
  1439. string compName = "";
  1440. if (x != -1)
  1441. compName = componentNames[x] + "/";
  1442. animEvent.name = compName + x;
  1443. changesMade = true;
  1444. updateCallback();
  1445. };
  1446. GUITextField methodField = new GUITextField(new LocEdString("Method"), 40, false, "", GUIOption.FixedWidth(190));
  1447. methodField.Value = methodName;
  1448. methodField.OnChanged += x =>
  1449. {
  1450. string compName = "";
  1451. if(componentField.Index != -1)
  1452. compName = componentNames[componentField.Index] + "/";
  1453. animEvent.name = compName + x;
  1454. changesMade = true;
  1455. updateCallback();
  1456. };
  1457. GUILayoutY vertLayout = GUI.AddLayoutY();
  1458. vertLayout.AddFlexibleSpace();
  1459. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1460. horzLayout.AddFlexibleSpace();
  1461. GUILayout contentLayout = horzLayout.AddLayoutY();
  1462. GUILayout timeLayout = contentLayout.AddLayoutX();
  1463. timeLayout.AddSpace(5);
  1464. timeLayout.AddElement(timeField);
  1465. timeLayout.AddFlexibleSpace();
  1466. GUILayout componentLayout = contentLayout.AddLayoutX();
  1467. componentLayout.AddSpace(5);
  1468. componentLayout.AddElement(componentField);
  1469. componentLayout.AddFlexibleSpace();
  1470. GUILayout methodLayout = contentLayout.AddLayoutX();
  1471. methodLayout.AddSpace(5);
  1472. methodLayout.AddElement(methodField);
  1473. methodLayout.AddFlexibleSpace();
  1474. horzLayout.AddFlexibleSpace();
  1475. vertLayout.AddFlexibleSpace();
  1476. this.closeCallback = closeCallback;
  1477. }
  1478. private void OnDestroy()
  1479. {
  1480. closeCallback?.Invoke(changesMade);
  1481. }
  1482. }
  1483. /** @} */
  1484. }