GUICurveEditor.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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. Range = newRange;
  1227. // When zooming, make sure to focus on the point provided, so adjust the offset
  1228. Vector2 rangeScale = newRange;
  1229. rangeScale.x /= currentRange.x;
  1230. rangeScale.y /= currentRange.y;
  1231. Vector2 relativeCurvePos = curvePos - Offset;
  1232. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  1233. Vector2 diff = newCurvePos - relativeCurvePos;
  1234. Offset -= diff;
  1235. UpdateScrollBarSize();
  1236. UpdateScrollBarPosition();
  1237. }
  1238. /// <summary>
  1239. /// Updates the offset and range of the curve display to fully fit the currently selected set of curves.
  1240. /// </summary>
  1241. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  1242. /// be kept as is.</param>
  1243. internal void CenterAndResize(bool resetTime)
  1244. {
  1245. GetOptimalRangeAndOffset(out var offset, out var range);
  1246. if (!resetTime)
  1247. {
  1248. offset.x = Offset.x;
  1249. range.x = Range.x;
  1250. }
  1251. Range = range;
  1252. Offset = offset;
  1253. UpdateScrollBarPosition();
  1254. UpdateScrollBarSize();
  1255. }
  1256. /// <summary>
  1257. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1258. /// </summary>
  1259. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1260. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1261. private void OnHorzScrollOrResize(float position, float size)
  1262. {
  1263. SetHorzScrollbarProperties(position, size);
  1264. }
  1265. /// <summary>
  1266. /// Triggered when the user moves or resizes the vertical scrollbar.
  1267. /// </summary>
  1268. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1269. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1270. private void OnVertScrollOrResize(float position, float size)
  1271. {
  1272. SetVertScrollbarProperties(position, size);
  1273. }
  1274. #endregion
  1275. #region Helpers
  1276. /// <summary>
  1277. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1278. /// </summary>
  1279. /// <param name="offset">Offset used for centering the curves.</param>
  1280. /// <param name="range">Range representing the width/height in curve space (time, value). </param>
  1281. private void GetOptimalRangeAndOffset(out Vector2 offset, out Vector2 range)
  1282. {
  1283. AnimationCurve[] curves = new AnimationCurve[curveInfos.Length];
  1284. for(int i = 0; i < curveInfos.Length; i++)
  1285. curves[i] = curveInfos[i].curve.Normal;
  1286. float xMin, xMax;
  1287. float yMin, yMax;
  1288. AnimationUtility.CalculateRange(curves, out xMin, out xMax, out yMin, out yMax);
  1289. float xRange = xMax - xMin;
  1290. float yRange = (yMax - yMin) * 0.5f;
  1291. float yOffset = yMin + yRange;
  1292. // Add padding to y range
  1293. yRange *= 1.05f;
  1294. // Don't allow zero range
  1295. if (xRange == 0.0f)
  1296. xRange = 60.0f;
  1297. if (yRange == 0.0f)
  1298. yRange = 10.0f;
  1299. offset = new Vector2(xMin, yOffset);
  1300. range = new Vector2(xRange, yRange);
  1301. }
  1302. /// <summary>
  1303. /// Returns a set of current curve draw infos with non-editor curves.
  1304. /// </summary>
  1305. /// <returns>Curve draw infos.</returns>
  1306. private CurveDrawInfo[] GetPlainCurveDrawInfos()
  1307. {
  1308. CurveDrawInfo[] output = new CurveDrawInfo[curveInfos.Length];
  1309. for(int i = 0; i < curveInfos.Length; i++)
  1310. output[i] = new CurveDrawInfo(curveInfos[i].curve.Normal, curveInfos[i].color);
  1311. return output;
  1312. }
  1313. /// <summary>
  1314. /// Converts coordinate in curve space (time, value) into pixel coordinates relative to the curve drawing area
  1315. /// origin.
  1316. /// </summary>
  1317. /// <param name="curveCoords">Time and value of the location to convert.</param>
  1318. /// <returns>Coordinates relative to curve drawing area's origin, in pixels.</returns>
  1319. public Vector2I CurveToPixelSpace(Vector2 curveCoords)
  1320. {
  1321. return guiCurveDrawing.CurveToPixelSpace(curveCoords);
  1322. }
  1323. /// <summary>
  1324. /// Converts coordinates in window space (relative to the parent window origin) into coordinates in curve space.
  1325. /// </summary>
  1326. /// <param name="pointerPos">Coordinates relative to this GUI element, in pixels.</param>
  1327. /// <param name="curveCoord">Curve coordinates within the range as specified by <see cref="Range"/>. Only
  1328. /// valid when function returns true.</param>
  1329. /// <returns>True if the coordinates are within the curve area, false otherwise.</returns>
  1330. public bool WindowToCurveSpace(Vector2I pointerPos, out Vector2 curveCoord)
  1331. {
  1332. Rect2I drawingBounds = drawingPanel.Bounds;
  1333. Vector2I drawingPos = pointerPos - new Vector2I(drawingBounds.x, drawingBounds.y);
  1334. return guiCurveDrawing.PixelToCurveSpace(drawingPos, out curveCoord);
  1335. }
  1336. #endregion
  1337. }
  1338. /// <summary>
  1339. /// Information necessary to drawing an editor curve.
  1340. /// </summary>
  1341. public struct EdCurveDrawInfo
  1342. {
  1343. public EdCurveDrawInfo(EdAnimationCurve curve, Color color)
  1344. {
  1345. this.curve = curve;
  1346. this.color = color;
  1347. }
  1348. public EdAnimationCurve curve;
  1349. public Color color;
  1350. }
  1351. /// <summary>
  1352. /// Drop down window that displays input boxes used for editing a keyframe.
  1353. /// </summary>
  1354. [DefaultSize(120, 80)]
  1355. internal class KeyframeEditWindow : DropDownWindow
  1356. {
  1357. private Action<bool> closeCallback;
  1358. private bool changesMade;
  1359. /// <summary>
  1360. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1361. /// use.
  1362. /// </summary>
  1363. /// <param name="keyFrame">Keyframe whose properties to edit.</param>
  1364. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1365. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1366. internal void Initialize(KeyFrame keyFrame, Action<KeyFrame> updateCallback, Action<bool> closeCallback)
  1367. {
  1368. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1369. timeField.Value = keyFrame.time;
  1370. timeField.OnChanged += x => { keyFrame.time = x; changesMade = true; updateCallback(keyFrame); };
  1371. GUIFloatField valueField = new GUIFloatField(new LocEdString("Value"), 40, "");
  1372. valueField.Value = keyFrame.value;
  1373. valueField.OnChanged += x => { keyFrame.value = x; changesMade = true; updateCallback(keyFrame); };
  1374. GUILayoutY vertLayout = GUI.AddLayoutY();
  1375. vertLayout.AddFlexibleSpace();
  1376. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1377. horzLayout.AddFlexibleSpace();
  1378. GUILayout contentLayout = horzLayout.AddLayoutY();
  1379. GUILayout timeLayout = contentLayout.AddLayoutX();
  1380. timeLayout.AddSpace(5);
  1381. timeLayout.AddElement(timeField);
  1382. timeLayout.AddFlexibleSpace();
  1383. GUILayout componentLayout = contentLayout.AddLayoutX();
  1384. componentLayout.AddSpace(5);
  1385. componentLayout.AddElement(valueField);
  1386. componentLayout.AddFlexibleSpace();
  1387. horzLayout.AddFlexibleSpace();
  1388. vertLayout.AddFlexibleSpace();
  1389. this.closeCallback = closeCallback;
  1390. }
  1391. private void OnDestroy()
  1392. {
  1393. closeCallback?.Invoke(changesMade);
  1394. }
  1395. }
  1396. /// <summary>
  1397. /// Drop down window that displays input boxes used for editing an event.
  1398. /// </summary>
  1399. [DefaultSize(200, 80)]
  1400. internal class EventEditWindow : DropDownWindow
  1401. {
  1402. private Action<bool> closeCallback;
  1403. private bool changesMade;
  1404. /// <summary>
  1405. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1406. /// use.
  1407. /// </summary>
  1408. /// <param name="animEvent">Event whose properties to edit.</param>
  1409. /// <param name="componentNames">List of component names that the user can select from.</param>
  1410. /// <param name="updateCallback">Callback triggered when event values change.</param>
  1411. /// <param name="closeCallback">Callback triggered just before the window closes.</param>
  1412. internal void Initialize(AnimationEvent animEvent, string[] componentNames, Action updateCallback,
  1413. Action<bool> closeCallback)
  1414. {
  1415. int selectedIndex = -1;
  1416. string methodName = "";
  1417. if (!string.IsNullOrEmpty(animEvent.name))
  1418. {
  1419. string[] nameEntries = animEvent.name.Split('/');
  1420. if (nameEntries.Length > 1)
  1421. {
  1422. string typeName = nameEntries[0];
  1423. for (int i = 0; i < componentNames.Length; i++)
  1424. {
  1425. if (componentNames[i] == typeName)
  1426. {
  1427. selectedIndex = i;
  1428. break;
  1429. }
  1430. }
  1431. methodName = nameEntries[nameEntries.Length - 1];
  1432. }
  1433. }
  1434. GUIFloatField timeField = new GUIFloatField(new LocEdString("Time"), 40, "");
  1435. timeField.Value = animEvent.time;
  1436. timeField.OnChanged += x => { animEvent.time = x; changesMade = true; updateCallback(); };
  1437. GUIListBoxField componentField = new GUIListBoxField(componentNames, new LocEdString("Component"), 40);
  1438. if (selectedIndex != -1)
  1439. componentField.Index = selectedIndex;
  1440. componentField.OnSelectionChanged += x =>
  1441. {
  1442. string compName = "";
  1443. if (x != -1)
  1444. compName = componentNames[x] + "/";
  1445. animEvent.name = compName + x;
  1446. changesMade = true;
  1447. updateCallback();
  1448. };
  1449. GUITextField methodField = new GUITextField(new LocEdString("Method"), 40, false, "", GUIOption.FixedWidth(190));
  1450. methodField.Value = methodName;
  1451. methodField.OnChanged += x =>
  1452. {
  1453. string compName = "";
  1454. if(componentField.Index != -1)
  1455. compName = componentNames[componentField.Index] + "/";
  1456. animEvent.name = compName + x;
  1457. changesMade = true;
  1458. updateCallback();
  1459. };
  1460. GUILayoutY vertLayout = GUI.AddLayoutY();
  1461. vertLayout.AddFlexibleSpace();
  1462. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  1463. horzLayout.AddFlexibleSpace();
  1464. GUILayout contentLayout = horzLayout.AddLayoutY();
  1465. GUILayout timeLayout = contentLayout.AddLayoutX();
  1466. timeLayout.AddSpace(5);
  1467. timeLayout.AddElement(timeField);
  1468. timeLayout.AddFlexibleSpace();
  1469. GUILayout componentLayout = contentLayout.AddLayoutX();
  1470. componentLayout.AddSpace(5);
  1471. componentLayout.AddElement(componentField);
  1472. componentLayout.AddFlexibleSpace();
  1473. GUILayout methodLayout = contentLayout.AddLayoutX();
  1474. methodLayout.AddSpace(5);
  1475. methodLayout.AddElement(methodField);
  1476. methodLayout.AddFlexibleSpace();
  1477. horzLayout.AddFlexibleSpace();
  1478. vertLayout.AddFlexibleSpace();
  1479. this.closeCallback = closeCallback;
  1480. }
  1481. private void OnDestroy()
  1482. {
  1483. closeCallback?.Invoke(changesMade);
  1484. }
  1485. }
  1486. /** @} */
  1487. }