AnimationWindow.cs 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Text;
  7. using BansheeEngine;
  8. namespace BansheeEditor
  9. {
  10. /** @addtogroup Windows
  11. * @{
  12. */
  13. /// <summary>
  14. /// Displays animation curve editor window. Allows the user to manipulate keyframes of animation curves, add/remove
  15. /// curves from an animation clip, and manipulate animation events.
  16. /// </summary>
  17. [DefaultSize(900, 500)]
  18. internal class AnimationWindow : EditorWindow
  19. {
  20. private const int FIELD_DISPLAY_WIDTH = 300;
  21. private const int DRAG_START_DISTANCE = 3;
  22. private const float DRAG_SCALE = 3.0f;
  23. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  24. private SceneObject selectedSO;
  25. /// <summary>
  26. /// Scene object for which are we currently changing the animation for.
  27. /// </summary>
  28. internal SceneObject SelectedSO
  29. {
  30. get { return selectedSO; }
  31. }
  32. #region Overrides
  33. /// <summary>
  34. /// Opens the animation window.
  35. /// </summary>
  36. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  37. private static void OpenGameWindow()
  38. {
  39. OpenWindow<AnimationWindow>();
  40. }
  41. /// <inheritdoc/>
  42. protected override LocString GetDisplayName()
  43. {
  44. return new LocEdString("Animation");
  45. }
  46. private void OnInitialize()
  47. {
  48. Selection.OnSelectionChanged += OnSelectionChanged;
  49. UpdateSelectedSO(true);
  50. }
  51. private void OnEditorUpdate()
  52. {
  53. if (selectedSO == null)
  54. return;
  55. HandleDragAndZoomInput();
  56. if (state == State.Playback)
  57. {
  58. Animation animation = selectedSO.GetComponent<Animation>();
  59. if (animation != null)
  60. {
  61. float time = animation.EditorGetTime();
  62. int frameIdx = (int)(time * fps);
  63. SetCurrentFrame(frameIdx);
  64. animation.UpdateFloatProperties();
  65. }
  66. }
  67. else if (state == State.Recording)
  68. {
  69. if (!delayRecord)
  70. {
  71. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  72. if (RecordState(time))
  73. {
  74. ApplyClipChanges();
  75. guiCurveEditor.Redraw();
  76. }
  77. }
  78. }
  79. delayRecord = false;
  80. }
  81. private void OnDestroy()
  82. {
  83. SwitchState(State.Empty);
  84. Selection.OnSelectionChanged -= OnSelectionChanged;
  85. if (selectedSO != null)
  86. {
  87. EditorInput.OnPointerPressed -= OnPointerPressed;
  88. EditorInput.OnPointerMoved -= OnPointerMoved;
  89. EditorInput.OnPointerReleased -= OnPointerReleased;
  90. EditorInput.OnButtonUp -= OnButtonUp;
  91. }
  92. }
  93. /// <inheritdoc/>
  94. protected override void WindowResized(int width, int height)
  95. {
  96. if (selectedSO == null)
  97. return;
  98. ResizeGUI(width, height);
  99. }
  100. #endregion
  101. #region GUI
  102. private GUIToggle playButton;
  103. private GUIToggle recordButton;
  104. private GUIButton prevFrameButton;
  105. private GUIIntField frameInputField;
  106. private GUIButton nextFrameButton;
  107. private GUIButton addKeyframeButton;
  108. private GUIButton addEventButton;
  109. private GUIButton optionsButton;
  110. private GUIButton addPropertyBtn;
  111. private GUIButton delPropertyBtn;
  112. private GUILayout buttonLayout;
  113. private int buttonLayoutHeight;
  114. private int scrollBarWidth;
  115. private int scrollBarHeight;
  116. private GUIResizeableScrollBarH horzScrollBar;
  117. private GUIResizeableScrollBarV vertScrollBar;
  118. private GUIPanel editorPanel;
  119. private GUIAnimFieldDisplay guiFieldDisplay;
  120. private GUICurveEditor guiCurveEditor;
  121. /// <summary>
  122. /// Recreates the entire curve editor GUI depending on the currently selected scene object.
  123. /// </summary>
  124. private void RebuildGUI()
  125. {
  126. GUI.Clear();
  127. guiCurveEditor = null;
  128. guiFieldDisplay = null;
  129. if (selectedSO == null)
  130. {
  131. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  132. GUILayoutY vertLayout = GUI.AddLayoutY();
  133. vertLayout.AddFlexibleSpace();
  134. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  135. vertLayout.AddFlexibleSpace();
  136. horzLayout.AddFlexibleSpace();
  137. horzLayout.AddElement(warningLbl);
  138. horzLayout.AddFlexibleSpace();
  139. return;
  140. }
  141. // Top button row
  142. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  143. new LocEdString("Play"));
  144. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  145. new LocEdString("Record"));
  146. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  147. new LocEdString("Previous frame"));
  148. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  149. new LocEdString("Next frame"));
  150. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  151. new LocEdString("Add keyframe"));
  152. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  153. new LocEdString("Add event"));
  154. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  155. new LocEdString("Options"));
  156. playButton = new GUIToggle(playIcon, EditorStyles.Button);
  157. recordButton = new GUIToggle(recordIcon, EditorStyles.Button);
  158. prevFrameButton = new GUIButton(prevFrameIcon);
  159. frameInputField = new GUIIntField();
  160. nextFrameButton = new GUIButton(nextFrameIcon);
  161. addKeyframeButton = new GUIButton(addKeyframeIcon);
  162. addEventButton = new GUIButton(addEventIcon);
  163. optionsButton = new GUIButton(optionsIcon);
  164. playButton.OnToggled += x =>
  165. {
  166. if(x)
  167. SwitchState(State.Playback);
  168. else
  169. SwitchState(State.Normal);
  170. };
  171. recordButton.OnToggled += x =>
  172. {
  173. if (x)
  174. SwitchState(State.Recording);
  175. else
  176. SwitchState(State.Normal);
  177. };
  178. prevFrameButton.OnClick += () =>
  179. {
  180. SetCurrentFrame(currentFrameIdx - 1);
  181. switch (state)
  182. {
  183. case State.Recording:
  184. case State.Normal:
  185. PreviewFrame(currentFrameIdx);
  186. break;
  187. default:
  188. SwitchState(State.Normal);
  189. break;
  190. }
  191. };
  192. frameInputField.OnChanged += x =>
  193. {
  194. SetCurrentFrame(x);
  195. switch (state)
  196. {
  197. case State.Recording:
  198. case State.Normal:
  199. PreviewFrame(currentFrameIdx);
  200. break;
  201. default:
  202. SwitchState(State.Normal);
  203. break;
  204. }
  205. };
  206. nextFrameButton.OnClick += () =>
  207. {
  208. SetCurrentFrame(currentFrameIdx + 1);
  209. switch (state)
  210. {
  211. case State.Recording:
  212. case State.Normal:
  213. PreviewFrame(currentFrameIdx);
  214. break;
  215. default:
  216. SwitchState(State.Normal);
  217. break;
  218. }
  219. };
  220. addKeyframeButton.OnClick += () =>
  221. {
  222. SwitchState(State.Normal);
  223. guiCurveEditor.AddKeyFrameAtMarker();
  224. };
  225. addEventButton.OnClick += () =>
  226. {
  227. SwitchState(State.Normal);
  228. guiCurveEditor.AddEventAtMarker();
  229. };
  230. optionsButton.OnClick += () =>
  231. {
  232. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  233. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
  234. dropDown.Initialize(this);
  235. };
  236. // Property buttons
  237. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  238. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  239. addPropertyBtn.OnClick += () =>
  240. {
  241. Action openPropertyWindow = () =>
  242. {
  243. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  244. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
  245. fieldSelection.OnFieldSelected += OnFieldAdded;
  246. };
  247. if (clipInfo.clip == null)
  248. {
  249. LocEdString title = new LocEdString("Warning");
  250. LocEdString message =
  251. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  252. " a new animation clip?");
  253. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  254. {
  255. if (type == DialogBox.ResultType.Yes)
  256. {
  257. string clipSavePath;
  258. if (BrowseDialog.SaveFile(ProjectLibrary.ResourceFolder, "*.asset", out clipSavePath))
  259. {
  260. SwitchState(State.Empty);
  261. clipSavePath = Path.ChangeExtension(clipSavePath, ".asset");
  262. AnimationClip newClip = new AnimationClip();
  263. ProjectLibrary.Create(newClip, clipSavePath);
  264. LoadAnimClip(newClip);
  265. Animation animation = selectedSO.GetComponent<Animation>();
  266. if (animation == null)
  267. animation = selectedSO.AddComponent<Animation>();
  268. animation.DefaultClip = newClip;
  269. EditorApplication.SetSceneDirty();
  270. SwitchState(State.Normal);
  271. openPropertyWindow();
  272. }
  273. }
  274. });
  275. }
  276. else
  277. {
  278. if (clipInfo.isImported)
  279. {
  280. LocEdString title = new LocEdString("Warning");
  281. LocEdString message =
  282. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  283. " are imported from an external file.");
  284. DialogBox.Open(title, message, DialogBox.Type.OK);
  285. }
  286. else
  287. {
  288. SwitchState(State.Normal);
  289. openPropertyWindow();
  290. }
  291. }
  292. };
  293. delPropertyBtn.OnClick += () =>
  294. {
  295. if (clipInfo.clip == null)
  296. return;
  297. SwitchState(State.Normal);
  298. if (clipInfo.isImported)
  299. {
  300. LocEdString title = new LocEdString("Warning");
  301. LocEdString message =
  302. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  303. " are imported from an external file.");
  304. DialogBox.Open(title, message, DialogBox.Type.OK);
  305. }
  306. else
  307. {
  308. LocEdString title = new LocEdString("Warning");
  309. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  310. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  311. {
  312. if (x == DialogBox.ResultType.Yes)
  313. {
  314. RemoveSelectedFields();
  315. ApplyClipChanges();
  316. }
  317. });
  318. }
  319. };
  320. GUIPanel mainPanel = GUI.AddPanel();
  321. GUIPanel backgroundPanel = GUI.AddPanel(1);
  322. GUILayout mainLayout = mainPanel.AddLayoutY();
  323. buttonLayout = mainLayout.AddLayoutX();
  324. buttonLayout.AddSpace(5);
  325. buttonLayout.AddElement(playButton);
  326. buttonLayout.AddElement(recordButton);
  327. buttonLayout.AddSpace(5);
  328. buttonLayout.AddElement(prevFrameButton);
  329. buttonLayout.AddElement(frameInputField);
  330. buttonLayout.AddElement(nextFrameButton);
  331. buttonLayout.AddSpace(5);
  332. buttonLayout.AddElement(addKeyframeButton);
  333. buttonLayout.AddElement(addEventButton);
  334. buttonLayout.AddSpace(5);
  335. buttonLayout.AddElement(optionsButton);
  336. buttonLayout.AddFlexibleSpace();
  337. buttonLayoutHeight = playButton.Bounds.height;
  338. GUITexture buttonBackground = new GUITexture(null, EditorStyles.HeaderBackground);
  339. buttonBackground.Bounds = new Rect2I(0, 0, Width, buttonLayoutHeight);
  340. backgroundPanel.AddElement(buttonBackground);
  341. GUILayout contentLayout = mainLayout.AddLayoutX();
  342. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  343. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  344. Height - buttonLayoutHeight * 2, selectedSO);
  345. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  346. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  347. bottomButtonLayout.AddElement(addPropertyBtn);
  348. bottomButtonLayout.AddElement(delPropertyBtn);
  349. horzScrollBar = new GUIResizeableScrollBarH();
  350. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  351. vertScrollBar = new GUIResizeableScrollBarV();
  352. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  353. GUITexture separator = new GUITexture(null, EditorStyles.Separator, GUIOption.FixedWidth(3));
  354. contentLayout.AddElement(separator);
  355. GUILayout curveLayout = contentLayout.AddLayoutY();
  356. GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
  357. GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
  358. horzScrollBarLayout.AddElement(horzScrollBar);
  359. horzScrollBarLayout.AddFlexibleSpace();
  360. editorPanel = curveLayoutHorz.AddPanel();
  361. curveLayoutHorz.AddElement(vertScrollBar);
  362. curveLayoutHorz.AddFlexibleSpace();
  363. scrollBarHeight = horzScrollBar.Bounds.height;
  364. scrollBarWidth = vertScrollBar.Bounds.width;
  365. Vector2I curveEditorSize = GetCurveEditorSize();
  366. guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
  367. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  368. guiCurveEditor.OnEventAdded += OnEventsChanged;
  369. guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
  370. guiCurveEditor.OnEventDeleted += OnEventsChanged;
  371. guiCurveEditor.OnCurveModified += () =>
  372. {
  373. SwitchState(State.Normal);
  374. ApplyClipChanges();
  375. PreviewFrame(currentFrameIdx);
  376. EditorApplication.SetProjectDirty();
  377. };
  378. guiCurveEditor.OnClicked += () =>
  379. {
  380. if(state != State.Recording)
  381. SwitchState(State.Normal);
  382. };
  383. guiCurveEditor.Redraw();
  384. horzScrollBar.SetWidth(curveEditorSize.x);
  385. vertScrollBar.SetHeight(curveEditorSize.y);
  386. UpdateScrollBarSize();
  387. }
  388. /// <summary>
  389. /// Resizes GUI elements so they fit within the provided boundaries.
  390. /// </summary>
  391. /// <param name="width">Width of the GUI bounds, in pixels.</param>
  392. /// <param name="height">Height of the GUI bounds, in pixels.</param>
  393. private void ResizeGUI(int width, int height)
  394. {
  395. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  396. Vector2I curveEditorSize = GetCurveEditorSize();
  397. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  398. guiCurveEditor.Redraw();
  399. horzScrollBar.SetWidth(curveEditorSize.x);
  400. vertScrollBar.SetHeight(curveEditorSize.y);
  401. UpdateScrollBarSize();
  402. UpdateScrollBarPosition();
  403. }
  404. #endregion
  405. #region Scroll, drag, zoom
  406. private Vector2I dragStartPos;
  407. private bool isButtonHeld;
  408. private bool isDragInProgress;
  409. private float zoomAmount;
  410. /// <summary>
  411. /// Handles mouse scroll wheel and dragging events in order to zoom or drag the displayed curve editor contents.
  412. /// </summary>
  413. private void HandleDragAndZoomInput()
  414. {
  415. // Handle middle mouse dragging
  416. if (isDragInProgress)
  417. {
  418. float lengthPerPixel = guiCurveEditor.Range.x / guiCurveEditor.Width;
  419. float heightPerPixel = guiCurveEditor.Range.y / guiCurveEditor.Height;
  420. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  421. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  422. Vector2 offset = guiCurveEditor.Offset;
  423. offset.x = Math.Max(0.0f, offset.x + dragX);
  424. offset.y -= dragY;
  425. guiCurveEditor.Offset = offset;
  426. UpdateScrollBarSize();
  427. UpdateScrollBarPosition();
  428. }
  429. // Handle zoom in/out
  430. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  431. if (scroll != 0.0f)
  432. {
  433. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  434. Vector2 curvePos;
  435. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  436. {
  437. float zoom = scroll * ZOOM_SCALE;
  438. Zoom(curvePos, zoom);
  439. }
  440. }
  441. }
  442. /// <summary>
  443. /// Moves or resizes the vertical scroll bar under the curve editor.
  444. /// </summary>
  445. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  446. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  447. private void SetVertScrollbarProperties(float position, float size)
  448. {
  449. Vector2 visibleRange = guiCurveEditor.Range;
  450. Vector2 totalRange = GetTotalRange();
  451. visibleRange.y = totalRange.y*size;
  452. guiCurveEditor.Range = visibleRange;
  453. float scrollableRange = totalRange.y - visibleRange.y;
  454. Vector2 offset = guiCurveEditor.Offset;
  455. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  456. guiCurveEditor.Offset = offset;
  457. }
  458. /// <summary>
  459. /// Moves or resizes the horizontal scroll bar under the curve editor.
  460. /// </summary>
  461. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  462. /// <param name="size">New size of the scrollbar handle, in range [0, 1].</param>
  463. private void SetHorzScrollbarProperties(float position, float size)
  464. {
  465. Vector2 visibleRange = guiCurveEditor.Range;
  466. Vector2 totalRange = GetTotalRange();
  467. visibleRange.x = totalRange.x * size;
  468. guiCurveEditor.Range = visibleRange;
  469. float scrollableRange = totalRange.x - visibleRange.x;
  470. Vector2 offset = guiCurveEditor.Offset;
  471. offset.x = scrollableRange * position;
  472. guiCurveEditor.Offset = offset;
  473. }
  474. /// <summary>
  475. /// Updates the size of both scrollbars depending on the currently visible curve area vs. the total curve area.
  476. /// </summary>
  477. private void UpdateScrollBarSize()
  478. {
  479. Vector2 visibleRange = guiCurveEditor.Range;
  480. Vector2 totalRange = GetTotalRange();
  481. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  482. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  483. }
  484. /// <summary>
  485. /// Updates the position of both scrollbars depending on the offset currently applied to the visible curve area.
  486. /// </summary>
  487. private void UpdateScrollBarPosition()
  488. {
  489. Vector2 visibleRange = guiCurveEditor.Range;
  490. Vector2 totalRange = GetTotalRange();
  491. Vector2 scrollableRange = totalRange - visibleRange;
  492. Vector2 offset = guiCurveEditor.Offset;
  493. if (scrollableRange.x > 0.0f)
  494. horzScrollBar.Position = offset.x / scrollableRange.x;
  495. else
  496. horzScrollBar.Position = 0.0f;
  497. if (scrollableRange.y > 0.0f)
  498. {
  499. float pos = offset.y/scrollableRange.y;
  500. float sign = MathEx.Sign(pos);
  501. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  502. pos = (1.0f - pos) /2.0f;
  503. vertScrollBar.Position = pos;
  504. }
  505. else
  506. vertScrollBar.Position = 0.0f;
  507. }
  508. /// <summary>
  509. /// Calculates the width/height of the curve area depending on the current zoom level.
  510. /// </summary>
  511. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  512. private Vector2 GetZoomedRange()
  513. {
  514. float zoomLevel = MathEx.Pow(2, zoomAmount);
  515. Vector2 optimalRange = GetOptimalRange();
  516. return optimalRange / zoomLevel;
  517. }
  518. /// <summary>
  519. /// Returns the total width/height of the contents of the curve area.
  520. /// </summary>
  521. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  522. private Vector2 GetTotalRange()
  523. {
  524. // Return optimal range (that covers the visible curve)
  525. Vector2 optimalRange = GetOptimalRange();
  526. // Increase range in case user zoomed out
  527. Vector2 zoomedRange = GetZoomedRange();
  528. return Vector2.Max(optimalRange, zoomedRange);
  529. }
  530. /// <summary>
  531. /// Zooms in or out at the provided position in the curve display.
  532. /// </summary>
  533. /// <param name="curvePos">Position to zoom towards, relative to the curve display area, in curve space
  534. /// (value, time)</param>
  535. /// <param name="amount">Amount to zoom in (positive), or out (negative).</param>
  536. private void Zoom(Vector2 curvePos, float amount)
  537. {
  538. // Increase or decrease the visible range depending on zoom level
  539. Vector2 oldZoomedRange = GetZoomedRange();
  540. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  541. Vector2 zoomedRange = GetZoomedRange();
  542. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  543. Vector2 currentRange = guiCurveEditor.Range;
  544. Vector2 newRange = currentRange + zoomedDiff;
  545. guiCurveEditor.Range = newRange;
  546. // When zooming, make sure to focus on the point provided, so adjust the offset
  547. Vector2 rangeScale = newRange;
  548. rangeScale.x /= currentRange.x;
  549. rangeScale.y /= currentRange.y;
  550. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  551. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  552. Vector2 diff = newCurvePos - relativeCurvePos;
  553. guiCurveEditor.Offset -= diff;
  554. UpdateScrollBarSize();
  555. UpdateScrollBarPosition();
  556. }
  557. #endregion
  558. #region Curve save/load
  559. private EditorAnimClipInfo clipInfo;
  560. /// <summary>
  561. /// Refreshes the contents of the curve and property display by loading animation curves from the provided
  562. /// animation clip.
  563. /// </summary>
  564. /// <param name="clip">Clip containing the animation to load.</param>
  565. private void LoadAnimClip(AnimationClip clip)
  566. {
  567. EditorPersistentData persistentData = EditorApplication.PersistentData;
  568. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  569. {
  570. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  571. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  572. // within the editor.
  573. if (clipInfo.isImported)
  574. {
  575. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  576. newClipInfo.events = clipInfo.events;
  577. }
  578. }
  579. else
  580. clipInfo = EditorAnimClipInfo.Create(clip);
  581. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  582. foreach (var curve in clipInfo.curves)
  583. guiFieldDisplay.AddField(new AnimFieldInfo(curve.Key, curve.Value, !clipInfo.isImported));
  584. guiCurveEditor.Events = clipInfo.events;
  585. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  586. SetCurrentFrame(0);
  587. FPS = clipInfo.sampleRate;
  588. }
  589. /// <summary>
  590. /// Applies any changes made to the animation curves and events to the actual animation clip resource.
  591. /// </summary>
  592. private void ApplyClipChanges()
  593. {
  594. if (clipInfo == null)
  595. return;
  596. EditorAnimClipTangents unused;
  597. clipInfo.Apply(out unused);
  598. }
  599. /// <summary>
  600. /// Checks if the currently selected object has changed, and rebuilds the GUI and loads the animation clip if needed.
  601. /// </summary>
  602. /// <param name="force">If true the GUI rebuild and animation clip load will be forced regardless if the active
  603. /// scene object changed.</param>
  604. private void UpdateSelectedSO(bool force)
  605. {
  606. SceneObject so = Selection.SceneObject;
  607. if (selectedSO != so || force)
  608. {
  609. if (selectedSO != null && so == null)
  610. {
  611. EditorInput.OnPointerPressed -= OnPointerPressed;
  612. EditorInput.OnPointerMoved -= OnPointerMoved;
  613. EditorInput.OnPointerReleased -= OnPointerReleased;
  614. EditorInput.OnButtonUp -= OnButtonUp;
  615. }
  616. else if (selectedSO == null && so != null)
  617. {
  618. EditorInput.OnPointerPressed += OnPointerPressed;
  619. EditorInput.OnPointerMoved += OnPointerMoved;
  620. EditorInput.OnPointerReleased += OnPointerReleased;
  621. EditorInput.OnButtonUp += OnButtonUp;
  622. }
  623. SwitchState(State.Empty);
  624. selectedSO = so;
  625. zoomAmount = 0.0f;
  626. selectedFields.Clear();
  627. clipInfo = null;
  628. RebuildGUI();
  629. // Load existing clip if one exists
  630. if (selectedSO != null)
  631. {
  632. Animation animation = selectedSO.GetComponent<Animation>();
  633. if (animation != null)
  634. {
  635. AnimationClip clip = animation.DefaultClip;
  636. if (clip != null)
  637. LoadAnimClip(clip);
  638. }
  639. }
  640. if(clipInfo == null)
  641. clipInfo = new EditorAnimClipInfo();
  642. SwitchState(State.Normal);
  643. if (selectedSO != null)
  644. UpdateDisplayedCurves(true);
  645. }
  646. }
  647. /// <summary>
  648. /// Initializes the currently selected scene object. This should be called whenever the selected scene object
  649. /// changes.
  650. /// </summary>
  651. private void InitializeSO()
  652. {
  653. if (selectedSO != null)
  654. soState = new SerializedSceneObject(selectedSO, true);
  655. }
  656. /// <summary>
  657. /// Clears a selected scene object. This must be called on every scene object <see cref="InitializeSO"/> has been called
  658. /// on, after operations on it are done.
  659. /// </summary>
  660. private void ClearSO()
  661. {
  662. if (selectedSO != null)
  663. {
  664. Animation animation = selectedSO.GetComponent<Animation>();
  665. if (animation != null)
  666. animation.EditorStop();
  667. }
  668. if (soState != null)
  669. {
  670. soState.Restore();
  671. soState = null;
  672. }
  673. }
  674. #endregion
  675. #region Record/Playback
  676. /// <summary>
  677. /// Possible states the animation window can be in.
  678. /// </summary>
  679. private enum State
  680. {
  681. Empty,
  682. Normal,
  683. Recording,
  684. Playback
  685. }
  686. private State state = State.Empty;
  687. private SerializedSceneObject soState;
  688. private bool delayRecord = false;
  689. /// <summary>
  690. /// Transitions the window into a different state. Caller must validate state transitions.
  691. /// </summary>
  692. /// <param name="state">New state to transition to.</param>
  693. private void SwitchState(State state)
  694. {
  695. switch (this.state)
  696. {
  697. case State.Normal:
  698. {
  699. switch (state)
  700. {
  701. case State.Playback:
  702. StartPlayback();
  703. break;
  704. case State.Recording:
  705. StartRecord();
  706. break;
  707. case State.Empty:
  708. ClearSO();
  709. break;
  710. }
  711. }
  712. break;
  713. case State.Playback:
  714. {
  715. switch (state)
  716. {
  717. case State.Normal:
  718. EndPlayback();
  719. PreviewFrame(currentFrameIdx);
  720. break;
  721. case State.Recording:
  722. EndPlayback();
  723. StartRecord();
  724. break;
  725. case State.Empty:
  726. EndPlayback();
  727. ClearSO();
  728. break;
  729. }
  730. }
  731. break;
  732. case State.Recording:
  733. {
  734. switch (state)
  735. {
  736. case State.Normal:
  737. EndRecord();
  738. PreviewFrame(currentFrameIdx);
  739. break;
  740. case State.Playback:
  741. EndRecord();
  742. StartPlayback();
  743. break;
  744. case State.Empty:
  745. EndRecord();
  746. ClearSO();
  747. break;
  748. }
  749. }
  750. break;
  751. case State.Empty:
  752. {
  753. switch (state)
  754. {
  755. case State.Normal:
  756. InitializeSO();
  757. PreviewFrame(currentFrameIdx);
  758. break;
  759. case State.Playback:
  760. InitializeSO();
  761. StartPlayback();
  762. break;
  763. case State.Recording:
  764. InitializeSO();
  765. StartRecord();
  766. break;
  767. }
  768. }
  769. break;
  770. }
  771. this.state = state;
  772. }
  773. /// <summary>
  774. /// Plays back the animation on the currently selected object.
  775. /// </summary>
  776. private void StartPlayback()
  777. {
  778. EditorAnimClipTangents unused;
  779. clipInfo.Apply(out unused);
  780. Animation animation = selectedSO.GetComponent<Animation>();
  781. if (animation != null && clipInfo.clip != null)
  782. {
  783. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  784. animation.EditorPlay(clipInfo.clip, time);
  785. }
  786. playButton.Value = true;
  787. }
  788. /// <summary>
  789. /// Ends playback started with <see cref="StartPlayback"/>
  790. /// </summary>
  791. private void EndPlayback()
  792. {
  793. PreviewFrame(currentFrameIdx);
  794. playButton.Value = false;
  795. }
  796. /// <summary>
  797. /// Updates the visible animation to display the provided frame.
  798. /// </summary>
  799. /// <param name="frameIdx">Index of the animation frame to display.</param>
  800. private void PreviewFrame(int frameIdx)
  801. {
  802. if (selectedSO == null)
  803. return;
  804. Animation animation = selectedSO.GetComponent<Animation>();
  805. if (animation != null && clipInfo.clip != null)
  806. {
  807. float time = guiCurveEditor.GetTimeForFrame(frameIdx);
  808. animation.EditorPlay(clipInfo.clip, time, true);
  809. }
  810. }
  811. /// <summary>
  812. /// Start recording modifications made to the selected scene object.
  813. /// </summary>
  814. private void StartRecord()
  815. {
  816. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  817. if (RecordState(time))
  818. {
  819. ApplyClipChanges();
  820. guiCurveEditor.Redraw();
  821. }
  822. recordButton.Value = true;
  823. }
  824. /// <summary>
  825. /// Stops recording modifications made to the selected scene object.
  826. /// </summary>
  827. private void EndRecord()
  828. {
  829. recordButton.Value = false;
  830. }
  831. /// <summary>
  832. /// Iterates over all curve path fields and records their current state. If the state differs from the current
  833. /// curve values, new keyframes are added.
  834. /// </summary>
  835. /// <param name="time">Time for which to record the state, in seconds.</param>
  836. /// <returns>True if any changes were recorded, false otherwise.</returns>
  837. private bool RecordState(float time)
  838. {
  839. Action<EdAnimationCurve, float, float> addOrUpdateKeyframe = (curve, keyTime, keyValue) =>
  840. {
  841. KeyFrame[] keyframes = curve.KeyFrames;
  842. int keyframeIdx = -1;
  843. for (int i = 0; i < keyframes.Length; i++)
  844. {
  845. if (MathEx.ApproxEquals(keyframes[i].time, time))
  846. {
  847. keyframeIdx = i;
  848. break;
  849. }
  850. }
  851. if (keyframeIdx != -1)
  852. curve.UpdateKeyframe(keyframeIdx, keyTime, keyValue);
  853. else
  854. curve.AddKeyframe(keyTime, keyValue);
  855. curve.Apply();
  856. };
  857. bool changesMade = false;
  858. foreach (var KVP in clipInfo.curves)
  859. {
  860. string suffix;
  861. SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
  862. if (property == null)
  863. continue;
  864. switch (KVP.Value.type)
  865. {
  866. case SerializableProperty.FieldType.Vector2:
  867. {
  868. Vector2 value = property.GetValue<Vector2>();
  869. for (int i = 0; i < 2; i++)
  870. {
  871. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  872. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  873. {
  874. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  875. changesMade = true;
  876. }
  877. }
  878. }
  879. break;
  880. case SerializableProperty.FieldType.Vector3:
  881. {
  882. Vector3 value = property.GetValue<Vector3>();
  883. for (int i = 0; i < 3; i++)
  884. {
  885. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  886. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  887. {
  888. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  889. changesMade = true;
  890. }
  891. }
  892. }
  893. break;
  894. case SerializableProperty.FieldType.Vector4:
  895. {
  896. if (property.InternalType == typeof(Vector4))
  897. {
  898. Vector4 value = property.GetValue<Vector4>();
  899. for (int i = 0; i < 4; i++)
  900. {
  901. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  902. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  903. {
  904. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  905. changesMade = true;
  906. }
  907. }
  908. }
  909. else if (property.InternalType == typeof(Quaternion))
  910. {
  911. Quaternion value = property.GetValue<Quaternion>();
  912. for (int i = 0; i < 4; i++)
  913. {
  914. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  915. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  916. {
  917. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  918. changesMade = true;
  919. }
  920. }
  921. }
  922. }
  923. break;
  924. case SerializableProperty.FieldType.Color:
  925. {
  926. Color value = property.GetValue<Color>();
  927. for (int i = 0; i < 4; i++)
  928. {
  929. float curveVal = KVP.Value.curveInfos[i].curve.Evaluate(time);
  930. if (!MathEx.ApproxEquals(value[i], curveVal, 0.001f))
  931. {
  932. addOrUpdateKeyframe(KVP.Value.curveInfos[i].curve, time, value[i]);
  933. changesMade = true;
  934. }
  935. }
  936. }
  937. break;
  938. case SerializableProperty.FieldType.Bool:
  939. {
  940. bool value = property.GetValue<bool>();
  941. bool curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time) > 0.0f;
  942. if (value != curveVal)
  943. {
  944. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value ? 1.0f : -1.0f);
  945. changesMade = true;
  946. }
  947. }
  948. break;
  949. case SerializableProperty.FieldType.Int:
  950. {
  951. int value = property.GetValue<int>();
  952. int curveVal = (int)KVP.Value.curveInfos[0].curve.Evaluate(time);
  953. if (value != curveVal)
  954. {
  955. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value);
  956. changesMade = true;
  957. }
  958. }
  959. break;
  960. case SerializableProperty.FieldType.Float:
  961. {
  962. float value = property.GetValue<float>();
  963. float curveVal = KVP.Value.curveInfos[0].curve.Evaluate(time);
  964. if (!MathEx.ApproxEquals(value, curveVal, 0.001f))
  965. {
  966. addOrUpdateKeyframe(KVP.Value.curveInfos[0].curve, time, value);
  967. changesMade = true;
  968. }
  969. }
  970. break;
  971. }
  972. }
  973. return changesMade;
  974. }
  975. #endregion
  976. #region Curve display
  977. private int currentFrameIdx;
  978. private int fps = 1;
  979. /// <summary>
  980. /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
  981. /// placed.
  982. /// </summary>
  983. internal int FPS
  984. {
  985. get { return fps; }
  986. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  987. }
  988. /// <summary>
  989. /// Changes the currently selected frame in the curve display.
  990. /// </summary>
  991. /// <param name="frameIdx">Index of the frame to select.</param>
  992. private void SetCurrentFrame(int frameIdx)
  993. {
  994. currentFrameIdx = Math.Max(0, frameIdx);
  995. frameInputField.Value = currentFrameIdx;
  996. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  997. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  998. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  999. foreach (var kvp in clipInfo.curves)
  1000. {
  1001. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  1002. fieldValue.path = kvp.Key;
  1003. switch (kvp.Value.type)
  1004. {
  1005. case SerializableProperty.FieldType.Vector2:
  1006. {
  1007. Vector2 value = new Vector2();
  1008. for (int i = 0; i < 2; i++)
  1009. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1010. fieldValue.value = value;
  1011. }
  1012. break;
  1013. case SerializableProperty.FieldType.Vector3:
  1014. {
  1015. Vector3 value = new Vector3();
  1016. for (int i = 0; i < 3; i++)
  1017. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1018. fieldValue.value = value;
  1019. }
  1020. break;
  1021. case SerializableProperty.FieldType.Vector4:
  1022. {
  1023. Vector4 value = new Vector4();
  1024. for (int i = 0; i < 4; i++)
  1025. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1026. fieldValue.value = value;
  1027. }
  1028. break;
  1029. case SerializableProperty.FieldType.Color:
  1030. {
  1031. Color value = new Color();
  1032. for (int i = 0; i < 4; i++)
  1033. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  1034. fieldValue.value = value;
  1035. }
  1036. break;
  1037. case SerializableProperty.FieldType.Bool:
  1038. case SerializableProperty.FieldType.Int:
  1039. case SerializableProperty.FieldType.Float:
  1040. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  1041. break;
  1042. }
  1043. values.Add(fieldValue);
  1044. }
  1045. guiFieldDisplay.SetDisplayValues(values.ToArray());
  1046. }
  1047. /// <summary>
  1048. /// Returns a list of all animation curves that should be displayed in the curve display.
  1049. /// </summary>
  1050. /// <returns>Array of curves to display.</returns>
  1051. private CurveDrawInfo[] GetDisplayedCurves()
  1052. {
  1053. List<CurveDrawInfo> curvesToDisplay = new List<CurveDrawInfo>();
  1054. if (selectedFields.Count == 0) // Display all if nothing is selected
  1055. {
  1056. if (clipInfo == null)
  1057. return curvesToDisplay.ToArray();
  1058. foreach (var curve in clipInfo.curves)
  1059. {
  1060. for (int i = 0; i < curve.Value.curveInfos.Length; i++)
  1061. curvesToDisplay.Add(curve.Value.curveInfos[i]);
  1062. }
  1063. }
  1064. else
  1065. {
  1066. for (int i = 0; i < selectedFields.Count; i++)
  1067. {
  1068. CurveDrawInfo[] curveInfos;
  1069. if (TryGetCurve(selectedFields[i], out curveInfos))
  1070. curvesToDisplay.AddRange(curveInfos);
  1071. }
  1072. }
  1073. return curvesToDisplay.ToArray();
  1074. }
  1075. /// <summary>
  1076. /// Returns width/height required to show the entire contents of the currently displayed curves.
  1077. /// </summary>
  1078. /// <returns>Width/height of the curve area, in curve space (value, time).</returns>
  1079. private Vector2 GetOptimalRange()
  1080. {
  1081. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1082. float xRange;
  1083. float yRange;
  1084. CalculateRange(curvesToDisplay, out xRange, out yRange);
  1085. // Add padding to y range
  1086. yRange *= 1.05f;
  1087. // Don't allow zero range
  1088. if (xRange == 0.0f)
  1089. xRange = 60.0f;
  1090. if (yRange == 0.0f)
  1091. yRange = 10.0f;
  1092. return new Vector2(xRange, yRange);
  1093. }
  1094. /// <summary>
  1095. /// Calculates an unique color for each animation curve.
  1096. /// </summary>
  1097. private void UpdateCurveColors()
  1098. {
  1099. int globalCurveIdx = 0;
  1100. foreach (var curveGroup in clipInfo.curves)
  1101. {
  1102. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  1103. curveGroup.Value.curveInfos[i].color = GUICurveDrawing.GetUniqueColor(globalCurveIdx++);
  1104. }
  1105. }
  1106. /// <summary>
  1107. /// Updates the curve display with currently selected curves.
  1108. /// </summary>
  1109. /// <param name="allowReduce">Normally the curve display will expand if newly selected curves cover a larger area
  1110. /// than currently available, but the area won't be reduced if the selected curves cover
  1111. /// a smaller area. Set this to true to allow the area to be reduced.</param>
  1112. private void UpdateDisplayedCurves(bool allowReduce = false)
  1113. {
  1114. CurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  1115. guiCurveEditor.SetCurves(curvesToDisplay);
  1116. Vector2 newRange = GetOptimalRange();
  1117. if (!allowReduce)
  1118. {
  1119. // Don't reduce visible range
  1120. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  1121. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  1122. }
  1123. guiCurveEditor.Range = newRange;
  1124. UpdateScrollBarSize();
  1125. }
  1126. #endregion
  1127. #region Field display
  1128. private List<string> selectedFields = new List<string>();
  1129. /// <summary>
  1130. /// Registers a new animation curve field.
  1131. /// </summary>
  1132. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  1133. /// <param name="type">Type of the field (float, vector, etc.)</param>
  1134. private void AddNewField(string path, SerializableProperty.FieldType type)
  1135. {
  1136. bool noSelection = selectedFields.Count == 0;
  1137. switch (type)
  1138. {
  1139. case SerializableProperty.FieldType.Vector4:
  1140. {
  1141. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1142. fieldCurves.type = type;
  1143. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1144. string[] subPaths = { ".x", ".y", ".z", ".w" };
  1145. for (int i = 0; i < subPaths.Length; i++)
  1146. {
  1147. string subFieldPath = path + subPaths[i];
  1148. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1149. selectedFields.Add(subFieldPath);
  1150. }
  1151. clipInfo.curves[path] = fieldCurves;
  1152. }
  1153. break;
  1154. case SerializableProperty.FieldType.Vector3:
  1155. {
  1156. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1157. fieldCurves.type = type;
  1158. fieldCurves.curveInfos = new CurveDrawInfo[3];
  1159. string[] subPaths = { ".x", ".y", ".z" };
  1160. for (int i = 0; i < subPaths.Length; i++)
  1161. {
  1162. string subFieldPath = path + subPaths[i];
  1163. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1164. selectedFields.Add(subFieldPath);
  1165. }
  1166. clipInfo.curves[path] = fieldCurves;
  1167. }
  1168. break;
  1169. case SerializableProperty.FieldType.Vector2:
  1170. {
  1171. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1172. fieldCurves.type = type;
  1173. fieldCurves.curveInfos = new CurveDrawInfo[2];
  1174. string[] subPaths = { ".x", ".y" };
  1175. for (int i = 0; i < subPaths.Length; i++)
  1176. {
  1177. string subFieldPath = path + subPaths[i];
  1178. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1179. selectedFields.Add(subFieldPath);
  1180. }
  1181. clipInfo.curves[path] = fieldCurves;
  1182. }
  1183. break;
  1184. case SerializableProperty.FieldType.Color:
  1185. {
  1186. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1187. fieldCurves.type = type;
  1188. fieldCurves.curveInfos = new CurveDrawInfo[4];
  1189. string[] subPaths = { ".r", ".g", ".b", ".a" };
  1190. for (int i = 0; i < subPaths.Length; i++)
  1191. {
  1192. string subFieldPath = path + subPaths[i];
  1193. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1194. selectedFields.Add(subFieldPath);
  1195. }
  1196. clipInfo.curves[path] = fieldCurves;
  1197. }
  1198. break;
  1199. default: // Primitive type
  1200. {
  1201. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1202. fieldCurves.type = type;
  1203. fieldCurves.curveInfos = new CurveDrawInfo[1];
  1204. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  1205. selectedFields.Add(path);
  1206. clipInfo.curves[path] = fieldCurves;
  1207. }
  1208. break;
  1209. }
  1210. UpdateCurveColors();
  1211. UpdateDisplayedFields();
  1212. EditorApplication.SetProjectDirty();
  1213. UpdateDisplayedCurves(noSelection);
  1214. }
  1215. /// <summary>
  1216. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  1217. /// </summary>
  1218. /// <param name="path">Path of the field to display.</param>
  1219. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  1220. /// only the provided field will be shown.</param>
  1221. private void SelectField(string path, bool additive)
  1222. {
  1223. if (!additive)
  1224. selectedFields.Clear();
  1225. bool noSelection = selectedFields.Count == 0;
  1226. if (!string.IsNullOrEmpty(path))
  1227. {
  1228. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  1229. selectedFields.Add(path);
  1230. }
  1231. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  1232. UpdateDisplayedCurves(noSelection);
  1233. }
  1234. /// <summary>
  1235. /// Deletes all currently selecting fields, removing them their curves permanently.
  1236. /// </summary>
  1237. private void RemoveSelectedFields()
  1238. {
  1239. for (int i = 0; i < selectedFields.Count; i++)
  1240. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  1241. UpdateCurveColors();
  1242. UpdateDisplayedFields();
  1243. selectedFields.Clear();
  1244. EditorApplication.SetProjectDirty();
  1245. UpdateDisplayedCurves();
  1246. }
  1247. /// <summary>
  1248. /// Updates the GUI element displaying the current animation curve fields.
  1249. /// </summary>
  1250. private void UpdateDisplayedFields()
  1251. {
  1252. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  1253. foreach (var KVP in clipInfo.curves)
  1254. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value, !clipInfo.isImported));
  1255. guiFieldDisplay.SetFields(existingFields.ToArray());
  1256. }
  1257. #endregion
  1258. #region Helpers
  1259. /// <summary>
  1260. /// Returns the size of the curve editor GUI element.
  1261. /// </summary>
  1262. /// <returns>Width/height of the curve editor, in pixels.</returns>
  1263. private Vector2I GetCurveEditorSize()
  1264. {
  1265. Vector2I output = new Vector2I();
  1266. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  1267. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  1268. return output;
  1269. }
  1270. /// <summary>
  1271. /// Calculates the total range covered by a set of curves.
  1272. /// </summary>
  1273. /// <param name="curveInfos">Curves to calculate range for.</param>
  1274. /// <param name="xRange">Maximum time value present in the curves.</param>
  1275. /// <param name="yRange">Maximum absolute curve value present in the curves.</param>
  1276. private static void CalculateRange(CurveDrawInfo[] curveInfos, out float xRange, out float yRange)
  1277. {
  1278. // Note: This only evaluates at keyframes, we should also evaluate in-between in order to account for steep
  1279. // tangents
  1280. xRange = 0.0f;
  1281. yRange = 0.0f;
  1282. foreach (var curveInfo in curveInfos)
  1283. {
  1284. KeyFrame[] keyframes = curveInfo.curve.KeyFrames;
  1285. foreach (var key in keyframes)
  1286. {
  1287. xRange = Math.Max(xRange, key.time);
  1288. yRange = Math.Max(yRange, Math.Abs(key.value));
  1289. }
  1290. }
  1291. }
  1292. /// <summary>
  1293. /// Attempts to find a curve field at the specified path.
  1294. /// </summary>
  1295. /// <param name="path">Path of the curve field to look for.</param>
  1296. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  1297. /// if it is a complex type, like a vector).</param>
  1298. /// <returns>True if the curve field was found, false otherwise.</returns>
  1299. private bool TryGetCurve(string path, out CurveDrawInfo[] curveInfos)
  1300. {
  1301. int index = path.LastIndexOf(".");
  1302. string parentPath;
  1303. string subPathSuffix = null;
  1304. if (index == -1)
  1305. {
  1306. parentPath = path;
  1307. }
  1308. else
  1309. {
  1310. parentPath = path.Substring(0, index);
  1311. subPathSuffix = path.Substring(index, path.Length - index);
  1312. }
  1313. FieldAnimCurves fieldCurves;
  1314. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1315. {
  1316. if (!string.IsNullOrEmpty(subPathSuffix))
  1317. {
  1318. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1319. {
  1320. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1321. return true;
  1322. }
  1323. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1324. {
  1325. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1326. return true;
  1327. }
  1328. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1329. {
  1330. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1331. return true;
  1332. }
  1333. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1334. {
  1335. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1336. return true;
  1337. }
  1338. }
  1339. else
  1340. {
  1341. curveInfos = fieldCurves.curveInfos;
  1342. return true;
  1343. }
  1344. }
  1345. curveInfos = new CurveDrawInfo[0];
  1346. return false;
  1347. }
  1348. /// <summary>
  1349. /// Checks if one curve field path a parent of the other.
  1350. /// </summary>
  1351. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1352. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1353. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1354. private bool IsPathParent(string child, string parent)
  1355. {
  1356. string[] childEntries = child.Split('/', '.');
  1357. string[] parentEntries = parent.Split('/', '.');
  1358. if (parentEntries.Length >= child.Length)
  1359. return false;
  1360. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1361. for (int i = 0; i < compareLength; i++)
  1362. {
  1363. if (childEntries[i] != parentEntries[i])
  1364. return false;
  1365. }
  1366. return true;
  1367. }
  1368. /// <summary>
  1369. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1370. /// path.
  1371. /// </summary>
  1372. /// <param name="path">Path to check.</param>
  1373. /// <returns>Path without sub-elements.</returns>
  1374. private string GetSubPathParent(string path)
  1375. {
  1376. int index = path.LastIndexOf(".");
  1377. if (index == -1)
  1378. return path;
  1379. return path.Substring(0, index);
  1380. }
  1381. #endregion
  1382. #region Input callbacks
  1383. /// <summary>
  1384. /// Triggered when the user presses a mouse button.
  1385. /// </summary>
  1386. /// <param name="ev">Information about the mouse press event.</param>
  1387. private void OnPointerPressed(PointerEvent ev)
  1388. {
  1389. guiCurveEditor.OnPointerPressed(ev);
  1390. if (ev.button == PointerButton.Middle)
  1391. {
  1392. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1393. Vector2 curvePos;
  1394. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  1395. {
  1396. dragStartPos = windowPos;
  1397. isButtonHeld = true;
  1398. }
  1399. }
  1400. }
  1401. /// <summary>
  1402. /// Triggered when the user moves the mouse.
  1403. /// </summary>
  1404. /// <param name="ev">Information about the mouse move event.</param>
  1405. private void OnPointerMoved(PointerEvent ev)
  1406. {
  1407. guiCurveEditor.OnPointerMoved(ev);
  1408. if (isButtonHeld)
  1409. {
  1410. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  1411. int distance = Vector2I.Distance(dragStartPos, windowPos);
  1412. if (distance >= DRAG_START_DISTANCE)
  1413. {
  1414. isDragInProgress = true;
  1415. Cursor.Hide();
  1416. Rect2I clipRect;
  1417. clipRect.x = ev.ScreenPos.x - 2;
  1418. clipRect.y = ev.ScreenPos.y - 2;
  1419. clipRect.width = 4;
  1420. clipRect.height = 4;
  1421. Cursor.ClipToRect(clipRect);
  1422. }
  1423. }
  1424. }
  1425. /// <summary>
  1426. /// Triggered when the user releases a mouse button.
  1427. /// </summary>
  1428. /// <param name="ev">Information about the mouse release event.</param>
  1429. private void OnPointerReleased(PointerEvent ev)
  1430. {
  1431. if (isDragInProgress)
  1432. {
  1433. Cursor.Show();
  1434. Cursor.ClipDisable();
  1435. }
  1436. isButtonHeld = false;
  1437. isDragInProgress = false;
  1438. guiCurveEditor.OnPointerReleased(ev);
  1439. }
  1440. /// <summary>
  1441. /// Triggered when the user releases a keyboard button.
  1442. /// </summary>
  1443. /// <param name="ev">Information about the keyboard release event.</param>
  1444. private void OnButtonUp(ButtonEvent ev)
  1445. {
  1446. guiCurveEditor.OnButtonUp(ev);
  1447. }
  1448. #endregion
  1449. #region General callbacks
  1450. /// <summary>
  1451. /// Triggered by the field selector, when user selects a new curve field.
  1452. /// </summary>
  1453. /// <param name="path">Path of the selected curve field.</param>
  1454. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1455. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1456. {
  1457. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1458. string pathNoRoot = path.TrimStart('/');
  1459. int separatorIdx = pathNoRoot.IndexOf("/");
  1460. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1461. return;
  1462. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1463. AddNewField(pathNoRoot, type);
  1464. ApplyClipChanges();
  1465. }
  1466. /// <summary>
  1467. /// Triggered when the user moves or resizes the horizontal scrollbar.
  1468. /// </summary>
  1469. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1470. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1471. private void OnHorzScrollOrResize(float position, float size)
  1472. {
  1473. SetHorzScrollbarProperties(position, size);
  1474. }
  1475. /// <summary>
  1476. /// Triggered when the user moves or resizes the vertical scrollbar.
  1477. /// </summary>
  1478. /// <param name="position">New position of the scrollbar, in range [0, 1].</param>
  1479. /// <param name="size">New size of the scrollbar, in range [0, 1].</param>
  1480. private void OnVertScrollOrResize(float position, float size)
  1481. {
  1482. SetVertScrollbarProperties(position, size);
  1483. }
  1484. /// <summary>
  1485. /// Triggered when the user selects a new curve field.
  1486. /// </summary>
  1487. /// <param name="path">Path of the selected curve field.</param>
  1488. private void OnFieldSelected(string path)
  1489. {
  1490. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1491. SelectField(path, additive);
  1492. }
  1493. /// <summary>
  1494. /// Triggered when the user selects a new scene object or a resource.
  1495. /// </summary>
  1496. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1497. /// <param name="resourcePaths">Newly selected resources.</param>
  1498. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1499. {
  1500. // While recording allow other objects to be selected so the user can modify them
  1501. if (state == State.Recording)
  1502. return;
  1503. UpdateSelectedSO(false);
  1504. }
  1505. /// <summary>
  1506. /// Triggered when the user selects a new frame in the curve display.
  1507. /// </summary>
  1508. /// <param name="frameIdx">Index of the selected frame.</param>
  1509. private void OnFrameSelected(int frameIdx)
  1510. {
  1511. SetCurrentFrame(frameIdx);
  1512. PreviewFrame(currentFrameIdx);
  1513. // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
  1514. // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
  1515. // animation to be evaluated synchronously when PreviewFrame is called.
  1516. delayRecord = true;
  1517. }
  1518. /// <summary>
  1519. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1520. /// </summary>
  1521. private void OnEventsChanged()
  1522. {
  1523. clipInfo.events = guiCurveEditor.Events;
  1524. EditorApplication.SetProjectDirty();
  1525. }
  1526. #endregion
  1527. }
  1528. /// <summary>
  1529. /// Drop down window that displays options used by the animation window.
  1530. /// </summary>
  1531. [DefaultSize(100, 50)]
  1532. internal class AnimationOptions : DropDownWindow
  1533. {
  1534. /// <summary>
  1535. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1536. /// use.
  1537. /// </summary>
  1538. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1539. internal void Initialize(AnimationWindow parent)
  1540. {
  1541. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1542. fpsField.Value = parent.FPS;
  1543. fpsField.OnChanged += x => { parent.FPS = x; };
  1544. GUILayoutY vertLayout = GUI.AddLayoutY();
  1545. vertLayout.AddFlexibleSpace();
  1546. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1547. contentLayout.AddFlexibleSpace();
  1548. contentLayout.AddElement(fpsField);
  1549. contentLayout.AddFlexibleSpace();
  1550. vertLayout.AddFlexibleSpace();
  1551. }
  1552. }
  1553. /** @} */
  1554. }