AnimationWindow.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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.Text;
  6. using BansheeEngine;
  7. namespace BansheeEditor
  8. {
  9. /** @addtogroup Windows
  10. * @{
  11. */
  12. /// <summary>
  13. /// Displays animation curve editor window.
  14. /// </summary>
  15. [DefaultSize(900, 500)]
  16. internal class AnimationWindow : EditorWindow
  17. {
  18. private const int FIELD_DISPLAY_WIDTH = 200;
  19. private const int DRAG_START_DISTANCE = 3;
  20. private const float DRAG_SCALE = 1.0f;
  21. private const float ZOOM_SCALE = 0.1f/120.0f; // One scroll step is usually 120 units, we want 1/10 of that
  22. private SceneObject selectedSO;
  23. /// <summary>
  24. /// Scene object for which are we currently changing the animation for.
  25. /// </summary>
  26. internal SceneObject SelectedSO
  27. {
  28. get { return selectedSO; }
  29. }
  30. #region Overrides
  31. /// <summary>
  32. /// Opens the animation window.
  33. /// </summary>
  34. [MenuItem("Windows/Animation", ButtonModifier.CtrlAlt, ButtonCode.A, 6000)]
  35. private static void OpenGameWindow()
  36. {
  37. OpenWindow<AnimationWindow>();
  38. }
  39. /// <inheritdoc/>
  40. protected override LocString GetDisplayName()
  41. {
  42. return new LocEdString("Animation");
  43. }
  44. private void OnInitialize()
  45. {
  46. Selection.OnSelectionChanged += OnSelectionChanged;
  47. UpdateSelectedSO(true);
  48. }
  49. private void OnEditorUpdate()
  50. {
  51. if (selectedSO == null)
  52. return;
  53. HandleDragAndZoomInput();
  54. }
  55. private void OnDestroy()
  56. {
  57. Selection.OnSelectionChanged -= OnSelectionChanged;
  58. if (selectedSO != null)
  59. {
  60. EditorInput.OnPointerPressed -= OnPointerPressed;
  61. EditorInput.OnPointerMoved -= OnPointerMoved;
  62. EditorInput.OnPointerReleased -= OnPointerReleased;
  63. EditorInput.OnButtonUp -= OnButtonUp;
  64. }
  65. }
  66. protected override void WindowResized(int width, int height)
  67. {
  68. if (selectedSO == null)
  69. return;
  70. ResizeGUI(width, height);
  71. }
  72. #endregion
  73. #region GUI
  74. private GUIButton playButton;
  75. private GUIButton recordButton;
  76. private GUIButton prevFrameButton;
  77. private GUIIntField frameInputField;
  78. private GUIButton nextFrameButton;
  79. private GUIButton addKeyframeButton;
  80. private GUIButton addEventButton;
  81. private GUIButton optionsButton;
  82. private GUIButton addPropertyBtn;
  83. private GUIButton delPropertyBtn;
  84. private GUILayout buttonLayout;
  85. private int buttonLayoutHeight;
  86. private int scrollBarWidth;
  87. private int scrollBarHeight;
  88. private GUIResizeableScrollBarH horzScrollBar;
  89. private GUIResizeableScrollBarV vertScrollBar;
  90. private GUIPanel editorPanel;
  91. private GUIAnimFieldDisplay guiFieldDisplay;
  92. private GUICurveEditor guiCurveEditor;
  93. private void RebuildGUI()
  94. {
  95. GUI.Clear();
  96. if (selectedSO == null)
  97. {
  98. GUILabel warningLbl = new GUILabel(new LocEdString("Select an object to animate in the Hierarchy or Scene windows."));
  99. GUILayoutY vertLayout = GUI.AddLayoutY();
  100. vertLayout.AddFlexibleSpace();
  101. GUILayoutX horzLayout = vertLayout.AddLayoutX();
  102. vertLayout.AddFlexibleSpace();
  103. horzLayout.AddFlexibleSpace();
  104. horzLayout.AddElement(warningLbl);
  105. horzLayout.AddFlexibleSpace();
  106. return;
  107. }
  108. // Top button row
  109. GUIContent playIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Play),
  110. new LocEdString("Play"));
  111. GUIContent recordIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.Record),
  112. new LocEdString("Record"));
  113. GUIContent prevFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameBack),
  114. new LocEdString("Previous frame"));
  115. GUIContent nextFrameIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.FrameForward),
  116. new LocEdString("Next frame"));
  117. GUIContent addKeyframeIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddKeyframe),
  118. new LocEdString("Add keyframe"));
  119. GUIContent addEventIcon = new GUIContent(EditorBuiltin.GetAnimationWindowIcon(AnimationWindowIcon.AddEvent),
  120. new LocEdString("Add event"));
  121. GUIContent optionsIcon = new GUIContent(EditorBuiltin.GetLibraryWindowIcon(LibraryWindowIcon.Options),
  122. new LocEdString("Options"));
  123. playButton = new GUIButton(playIcon);
  124. recordButton = new GUIButton(recordIcon);
  125. prevFrameButton = new GUIButton(prevFrameIcon);
  126. frameInputField = new GUIIntField();
  127. nextFrameButton = new GUIButton(nextFrameIcon);
  128. addKeyframeButton = new GUIButton(addKeyframeIcon);
  129. addEventButton = new GUIButton(addEventIcon);
  130. optionsButton = new GUIButton(optionsIcon);
  131. playButton.OnClick += () =>
  132. {
  133. // TODO
  134. // - Record current state of the scene object hierarchy
  135. // - Evaluate all curves manually and update them
  136. // - On end, restore original values of the scene object hierarchy
  137. };
  138. recordButton.OnClick += () =>
  139. {
  140. // TODO
  141. // - Every frame read back current values of all the current curve's properties and assign it to the current frame
  142. };
  143. prevFrameButton.OnClick += () =>
  144. {
  145. SetCurrentFrame(currentFrameIdx - 1);
  146. };
  147. frameInputField.OnChanged += SetCurrentFrame;
  148. nextFrameButton.OnClick += () =>
  149. {
  150. SetCurrentFrame(currentFrameIdx + 1);
  151. };
  152. addKeyframeButton.OnClick += () =>
  153. {
  154. guiCurveEditor.AddKeyFrameAtMarker();
  155. };
  156. addEventButton.OnClick += () =>
  157. {
  158. guiCurveEditor.AddEventAtMarker();
  159. };
  160. optionsButton.OnClick += () =>
  161. {
  162. Vector2I openPosition = ScreenToWindowPos(Input.PointerPosition);
  163. AnimationOptions dropDown = DropDownWindow.Open<AnimationOptions>(this, openPosition);
  164. dropDown.Initialize(this);
  165. };
  166. // Property buttons
  167. addPropertyBtn = new GUIButton(new LocEdString("Add property"));
  168. delPropertyBtn = new GUIButton(new LocEdString("Delete selected"));
  169. addPropertyBtn.OnClick += () =>
  170. {
  171. Action openPropertyWindow = () =>
  172. {
  173. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  174. FieldSelectionWindow fieldSelection = DropDownWindow.Open<FieldSelectionWindow>(this, windowPos);
  175. fieldSelection.OnFieldSelected += OnFieldAdded;
  176. };
  177. if (clipInfo.clip == null)
  178. {
  179. LocEdString title = new LocEdString("Warning");
  180. LocEdString message =
  181. new LocEdString("Selected object doesn't have an animation clip assigned. Would you like to create" +
  182. " a new animation clip?");
  183. DialogBox.Open(title, message, DialogBox.Type.YesNoCancel, type =>
  184. {
  185. if (type == DialogBox.ResultType.Yes)
  186. {
  187. string[] clipSavePaths;
  188. if (BrowseDialog.OpenFile(ProjectLibrary.ResourceFolder, "", false, out clipSavePaths))
  189. {
  190. if (clipSavePaths.Length > 0)
  191. {
  192. AnimationClip newClip = new AnimationClip();
  193. ProjectLibrary.Create(newClip, clipSavePaths[0]);
  194. LoadAnimClip(newClip);
  195. Animation animation = selectedSO.GetComponent<Animation>();
  196. if (animation == null)
  197. animation = selectedSO.AddComponent<Animation>();
  198. animation.DefaultClip = newClip;
  199. EditorApplication.SetSceneDirty();
  200. openPropertyWindow();
  201. }
  202. }
  203. }
  204. });
  205. }
  206. else
  207. {
  208. if (IsClipImported(clipInfo.clip))
  209. {
  210. LocEdString title = new LocEdString("Warning");
  211. LocEdString message =
  212. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  213. " are imported from an external file.");
  214. DialogBox.Open(title, message, DialogBox.Type.OK);
  215. }
  216. else
  217. openPropertyWindow();
  218. }
  219. };
  220. delPropertyBtn.OnClick += () =>
  221. {
  222. if (clipInfo.clip == null)
  223. return;
  224. if (IsClipImported(clipInfo.clip))
  225. {
  226. LocEdString title = new LocEdString("Warning");
  227. LocEdString message =
  228. new LocEdString("You cannot add/edit/remove curves from animation clips that" +
  229. " are imported from an external file.");
  230. DialogBox.Open(title, message, DialogBox.Type.OK);
  231. }
  232. else
  233. {
  234. LocEdString title = new LocEdString("Warning");
  235. LocEdString message = new LocEdString("Are you sure you want to remove all selected fields?");
  236. DialogBox.Open(title, message, DialogBox.Type.YesNo, x =>
  237. {
  238. if (x == DialogBox.ResultType.Yes)
  239. {
  240. RemoveSelectedFields();
  241. }
  242. });
  243. }
  244. };
  245. GUILayout mainLayout = GUI.AddLayoutY();
  246. buttonLayout = mainLayout.AddLayoutX();
  247. buttonLayout.AddSpace(5);
  248. buttonLayout.AddElement(playButton);
  249. buttonLayout.AddElement(recordButton);
  250. buttonLayout.AddSpace(5);
  251. buttonLayout.AddElement(prevFrameButton);
  252. buttonLayout.AddElement(frameInputField);
  253. buttonLayout.AddElement(nextFrameButton);
  254. buttonLayout.AddSpace(5);
  255. buttonLayout.AddElement(addKeyframeButton);
  256. buttonLayout.AddElement(addEventButton);
  257. buttonLayout.AddSpace(5);
  258. buttonLayout.AddElement(optionsButton);
  259. buttonLayout.AddFlexibleSpace();
  260. buttonLayoutHeight = playButton.Bounds.height;
  261. GUILayout contentLayout = mainLayout.AddLayoutX();
  262. GUILayout fieldDisplayLayout = contentLayout.AddLayoutY(GUIOption.FixedWidth(FIELD_DISPLAY_WIDTH));
  263. guiFieldDisplay = new GUIAnimFieldDisplay(fieldDisplayLayout, FIELD_DISPLAY_WIDTH,
  264. Height - buttonLayoutHeight * 2, selectedSO);
  265. guiFieldDisplay.OnEntrySelected += OnFieldSelected;
  266. GUILayout bottomButtonLayout = fieldDisplayLayout.AddLayoutX();
  267. bottomButtonLayout.AddElement(addPropertyBtn);
  268. bottomButtonLayout.AddElement(delPropertyBtn);
  269. horzScrollBar = new GUIResizeableScrollBarH();
  270. horzScrollBar.OnScrollOrResize += OnHorzScrollOrResize;
  271. vertScrollBar = new GUIResizeableScrollBarV();
  272. vertScrollBar.OnScrollOrResize += OnVertScrollOrResize;
  273. GUILayout curveLayout = contentLayout.AddLayoutY();
  274. GUILayout curveLayoutHorz = curveLayout.AddLayoutX();
  275. GUILayout horzScrollBarLayout = curveLayout.AddLayoutX();
  276. horzScrollBarLayout.AddElement(horzScrollBar);
  277. horzScrollBarLayout.AddFlexibleSpace();
  278. editorPanel = curveLayoutHorz.AddPanel();
  279. curveLayoutHorz.AddElement(vertScrollBar);
  280. curveLayoutHorz.AddFlexibleSpace();
  281. scrollBarHeight = horzScrollBar.Bounds.height;
  282. scrollBarWidth = vertScrollBar.Bounds.width;
  283. Vector2I curveEditorSize = GetCurveEditorSize();
  284. guiCurveEditor = new GUICurveEditor(this, editorPanel, curveEditorSize.x, curveEditorSize.y);
  285. guiCurveEditor.OnFrameSelected += OnFrameSelected;
  286. guiCurveEditor.OnEventAdded += OnEventsChanged;
  287. guiCurveEditor.OnEventModified += EditorApplication.SetProjectDirty;
  288. guiCurveEditor.OnEventDeleted += OnEventsChanged;
  289. guiCurveEditor.OnCurveModified += EditorApplication.SetProjectDirty;
  290. guiCurveEditor.Redraw();
  291. horzScrollBar.SetWidth(curveEditorSize.x);
  292. vertScrollBar.SetHeight(curveEditorSize.y);
  293. SetCurrentFrame(currentFrameIdx);
  294. UpdateScrollBarSize();
  295. }
  296. private void ResizeGUI(int width, int height)
  297. {
  298. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  299. Vector2I curveEditorSize = GetCurveEditorSize();
  300. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  301. guiCurveEditor.Redraw();
  302. horzScrollBar.SetWidth(curveEditorSize.x);
  303. vertScrollBar.SetHeight(curveEditorSize.y);
  304. UpdateScrollBarSize();
  305. UpdateScrollBarPosition();
  306. }
  307. #endregion
  308. #region Scroll, drag, zoom
  309. private Vector2I dragStartPos;
  310. private bool isButtonHeld;
  311. private bool isDragInProgress;
  312. private float zoomAmount;
  313. private void HandleDragAndZoomInput()
  314. {
  315. // Handle middle mouse dragging
  316. if (isDragInProgress)
  317. {
  318. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE;
  319. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE;
  320. Vector2 offset = guiCurveEditor.Offset;
  321. offset.x = Math.Max(0.0f, offset.x + dragX);
  322. offset.y -= dragY;
  323. guiCurveEditor.Offset = offset;
  324. UpdateScrollBarSize();
  325. UpdateScrollBarPosition();
  326. }
  327. // Handle zoom in/out
  328. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  329. if (scroll != 0.0f)
  330. {
  331. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  332. Vector2 curvePos;
  333. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  334. {
  335. float zoom = scroll * ZOOM_SCALE;
  336. Zoom(curvePos, zoom);
  337. }
  338. }
  339. }
  340. private void SetVertScrollbarProperties(float position, float size)
  341. {
  342. Vector2 visibleRange = guiCurveEditor.Range;
  343. Vector2 totalRange = GetTotalRange();
  344. visibleRange.y = totalRange.y*size;
  345. guiCurveEditor.Range = visibleRange;
  346. float scrollableRange = totalRange.y - visibleRange.y;
  347. Vector2 offset = guiCurveEditor.Offset;
  348. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  349. guiCurveEditor.Offset = offset;
  350. }
  351. private void SetHorzScrollbarProperties(float position, float size)
  352. {
  353. Vector2 visibleRange = guiCurveEditor.Range;
  354. Vector2 totalRange = GetTotalRange();
  355. visibleRange.x = totalRange.x * size;
  356. guiCurveEditor.Range = visibleRange;
  357. float scrollableRange = totalRange.x - visibleRange.x;
  358. Vector2 offset = guiCurveEditor.Offset;
  359. offset.x = scrollableRange * position;
  360. guiCurveEditor.Offset = offset;
  361. }
  362. private void UpdateScrollBarSize()
  363. {
  364. Vector2 visibleRange = guiCurveEditor.Range;
  365. Vector2 totalRange = GetTotalRange();
  366. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  367. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  368. }
  369. private void UpdateScrollBarPosition()
  370. {
  371. Vector2 visibleRange = guiCurveEditor.Range;
  372. Vector2 totalRange = GetTotalRange();
  373. Vector2 scrollableRange = totalRange - visibleRange;
  374. Vector2 offset = guiCurveEditor.Offset;
  375. if (scrollableRange.x > 0.0f)
  376. horzScrollBar.Position = offset.x / scrollableRange.x;
  377. else
  378. horzScrollBar.Position = 0.0f;
  379. if (scrollableRange.y > 0.0f)
  380. {
  381. float pos = offset.y/scrollableRange.y;
  382. float sign = MathEx.Sign(pos);
  383. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  384. pos = (1.0f - pos) /2.0f;
  385. vertScrollBar.Position = pos;
  386. }
  387. else
  388. vertScrollBar.Position = 0.0f;
  389. }
  390. private Vector2 GetZoomedRange()
  391. {
  392. float zoomLevel = MathEx.Pow(2, zoomAmount);
  393. Vector2 optimalRange = GetOptimalRange();
  394. return optimalRange / zoomLevel;
  395. }
  396. private Vector2 GetTotalRange()
  397. {
  398. // Return optimal range (that covers the visible curve)
  399. Vector2 optimalRange = GetOptimalRange();
  400. // Increase range in case user zoomed out
  401. Vector2 zoomedRange = GetZoomedRange();
  402. return Vector2.Max(optimalRange, zoomedRange);
  403. }
  404. private void Zoom(Vector2 curvePos, float amount)
  405. {
  406. // Increase or decrease the visible range depending on zoom level
  407. Vector2 oldZoomedRange = GetZoomedRange();
  408. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  409. Vector2 zoomedRange = GetZoomedRange();
  410. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  411. Vector2 currentRange = guiCurveEditor.Range;
  412. Vector2 newRange = currentRange + zoomedDiff;
  413. guiCurveEditor.Range = newRange;
  414. // When zooming, make sure to focus on the point provided, so adjust the offset
  415. Vector2 rangeScale = newRange;
  416. rangeScale.x /= currentRange.x;
  417. rangeScale.y /= currentRange.y;
  418. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  419. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  420. Vector2 diff = newCurvePos - relativeCurvePos;
  421. guiCurveEditor.Offset -= diff;
  422. UpdateScrollBarSize();
  423. UpdateScrollBarPosition();
  424. }
  425. #endregion
  426. #region Curve save/load
  427. private EditorAnimClipInfo clipInfo;
  428. private void LoadAnimClip(AnimationClip clip)
  429. {
  430. EditorPersistentData persistentData = EditorApplication.PersistentData;
  431. bool clipIsImported = IsClipImported(clip);
  432. if (persistentData.dirtyAnimClips.TryGetValue(clip.UUID, out clipInfo))
  433. {
  434. // If an animation clip is imported, we don't care about it's cached curve values as they could have changed
  435. // since last modification, so we re-load the clip. But we persist the events as those can only be set
  436. // within the editor.
  437. if (clipIsImported)
  438. {
  439. EditorAnimClipInfo newClipInfo = EditorAnimClipInfo.Create(clip);
  440. newClipInfo.events = clipInfo.events;
  441. }
  442. }
  443. else
  444. clipInfo = EditorAnimClipInfo.Create(clip);
  445. persistentData.dirtyAnimClips[clip.UUID] = clipInfo;
  446. foreach (var curve in clipInfo.curves)
  447. guiFieldDisplay.AddField(curve.Key);
  448. guiCurveEditor.Events = clipInfo.events;
  449. guiCurveEditor.DisableCurveEdit = clipIsImported;
  450. }
  451. private static bool IsClipImported(AnimationClip clip)
  452. {
  453. string resourcePath = ProjectLibrary.GetPath(clip);
  454. return ProjectLibrary.IsSubresource(resourcePath);
  455. }
  456. private void UpdateSelectedSO(bool force)
  457. {
  458. SceneObject so = Selection.SceneObject;
  459. if (selectedSO != so || force)
  460. {
  461. if (selectedSO != null && so == null)
  462. {
  463. EditorInput.OnPointerPressed -= OnPointerPressed;
  464. EditorInput.OnPointerMoved -= OnPointerMoved;
  465. EditorInput.OnPointerReleased -= OnPointerReleased;
  466. EditorInput.OnButtonUp -= OnButtonUp;
  467. }
  468. else if (selectedSO == null && so != null)
  469. {
  470. EditorInput.OnPointerPressed += OnPointerPressed;
  471. EditorInput.OnPointerMoved += OnPointerMoved;
  472. EditorInput.OnPointerReleased += OnPointerReleased;
  473. EditorInput.OnButtonUp += OnButtonUp;
  474. }
  475. zoomAmount = 0.0f;
  476. selectedSO = so;
  477. selectedFields.Clear();
  478. RebuildGUI();
  479. clipInfo = null;
  480. // Load existing clip if one exists
  481. if (selectedSO != null)
  482. {
  483. Animation animation = selectedSO.GetComponent<Animation>();
  484. if (animation != null)
  485. {
  486. AnimationClip clip = animation.DefaultClip;
  487. if (clip != null)
  488. LoadAnimClip(clip);
  489. }
  490. }
  491. if(clipInfo == null)
  492. clipInfo = new EditorAnimClipInfo();
  493. }
  494. }
  495. #endregion
  496. #region Curve display
  497. private int currentFrameIdx;
  498. private int fps = 1;
  499. internal int FPS
  500. {
  501. get { return fps; }
  502. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  503. }
  504. private void SetCurrentFrame(int frameIdx)
  505. {
  506. currentFrameIdx = Math.Max(0, frameIdx);
  507. frameInputField.Value = currentFrameIdx;
  508. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  509. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  510. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  511. foreach (var kvp in clipInfo.curves)
  512. {
  513. string suffix;
  514. SerializableProperty property = Animation.FindProperty(selectedSO, kvp.Key, out suffix);
  515. if (property != null)
  516. {
  517. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  518. fieldValue.path = kvp.Key;
  519. switch (kvp.Value.type)
  520. {
  521. case SerializableProperty.FieldType.Vector2:
  522. {
  523. Vector2 value = new Vector2();
  524. for (int i = 0; i < 2; i++)
  525. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  526. fieldValue.value = value;
  527. }
  528. break;
  529. case SerializableProperty.FieldType.Vector3:
  530. {
  531. Vector3 value = new Vector3();
  532. for (int i = 0; i < 3; i++)
  533. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  534. fieldValue.value = value;
  535. }
  536. break;
  537. case SerializableProperty.FieldType.Vector4:
  538. {
  539. Vector4 value = new Vector4();
  540. for (int i = 0; i < 4; i++)
  541. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  542. fieldValue.value = value;
  543. }
  544. break;
  545. case SerializableProperty.FieldType.Color:
  546. {
  547. Color value = new Color();
  548. for (int i = 0; i < 4; i++)
  549. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  550. fieldValue.value = value;
  551. }
  552. break;
  553. case SerializableProperty.FieldType.Bool:
  554. case SerializableProperty.FieldType.Int:
  555. case SerializableProperty.FieldType.Float:
  556. fieldValue.value = kvp.Value.curves[0].Evaluate(time, false); ;
  557. break;
  558. }
  559. values.Add(fieldValue);
  560. }
  561. }
  562. guiFieldDisplay.SetDisplayValues(values.ToArray());
  563. }
  564. private Vector2 GetOptimalRange()
  565. {
  566. List<EdAnimationCurve> displayedCurves = new List<EdAnimationCurve>();
  567. for (int i = 0; i < selectedFields.Count; i++)
  568. {
  569. EdAnimationCurve curve;
  570. if (TryGetCurve(selectedFields[i], out curve))
  571. displayedCurves.Add(curve);
  572. }
  573. float xRange;
  574. float yRange;
  575. CalculateRange(displayedCurves, out xRange, out yRange);
  576. // Add padding to y range
  577. yRange *= 1.05f;
  578. // Don't allow zero range
  579. if (xRange == 0.0f)
  580. xRange = 60.0f;
  581. if (yRange == 0.0f)
  582. yRange = 10.0f;
  583. return new Vector2(xRange, yRange);
  584. }
  585. private void UpdateDisplayedCurves()
  586. {
  587. List<EdAnimationCurve> curvesToDisplay = new List<EdAnimationCurve>();
  588. for (int i = 0; i < selectedFields.Count; i++)
  589. {
  590. EdAnimationCurve curve;
  591. if (TryGetCurve(selectedFields[i], out curve))
  592. curvesToDisplay.Add(curve);
  593. }
  594. guiCurveEditor.SetCurves(curvesToDisplay.ToArray());
  595. Vector2 newRange = GetOptimalRange();
  596. // Don't reduce visible range
  597. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  598. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  599. guiCurveEditor.Range = newRange;
  600. UpdateScrollBarSize();
  601. }
  602. #endregion
  603. #region Field display
  604. private List<string> selectedFields = new List<string>();
  605. private void AddNewField(string path, SerializableProperty.FieldType type)
  606. {
  607. guiFieldDisplay.AddField(path);
  608. switch (type)
  609. {
  610. case SerializableProperty.FieldType.Vector4:
  611. {
  612. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  613. fieldCurves.type = type;
  614. fieldCurves.curves = new EdAnimationCurve[4];
  615. string[] subPaths = { ".x", ".y", ".z", ".w" };
  616. for (int i = 0; i < subPaths.Length; i++)
  617. {
  618. string subFieldPath = path + subPaths[i];
  619. fieldCurves.curves[i] = new EdAnimationCurve();
  620. selectedFields.Add(subFieldPath);
  621. }
  622. clipInfo.curves[path] = fieldCurves;
  623. }
  624. break;
  625. case SerializableProperty.FieldType.Vector3:
  626. {
  627. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  628. fieldCurves.type = type;
  629. fieldCurves.curves = new EdAnimationCurve[3];
  630. string[] subPaths = { ".x", ".y", ".z" };
  631. for (int i = 0; i < subPaths.Length; i++)
  632. {
  633. string subFieldPath = path + subPaths[i];
  634. fieldCurves.curves[i] = new EdAnimationCurve();
  635. selectedFields.Add(subFieldPath);
  636. }
  637. clipInfo.curves[path] = fieldCurves;
  638. }
  639. break;
  640. case SerializableProperty.FieldType.Vector2:
  641. {
  642. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  643. fieldCurves.type = type;
  644. fieldCurves.curves = new EdAnimationCurve[2];
  645. string[] subPaths = { ".x", ".y" };
  646. for (int i = 0; i < subPaths.Length; i++)
  647. {
  648. string subFieldPath = path + subPaths[i];
  649. fieldCurves.curves[i] = new EdAnimationCurve();
  650. selectedFields.Add(subFieldPath);
  651. }
  652. clipInfo.curves[path] = fieldCurves;
  653. }
  654. break;
  655. case SerializableProperty.FieldType.Color:
  656. {
  657. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  658. fieldCurves.type = type;
  659. fieldCurves.curves = new EdAnimationCurve[4];
  660. string[] subPaths = { ".r", ".g", ".b", ".a" };
  661. for (int i = 0; i < subPaths.Length; i++)
  662. {
  663. string subFieldPath = path + subPaths[i];
  664. fieldCurves.curves[i] = new EdAnimationCurve();
  665. selectedFields.Add(subFieldPath);
  666. }
  667. clipInfo.curves[path] = fieldCurves;
  668. }
  669. break;
  670. default: // Primitive type
  671. {
  672. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  673. fieldCurves.type = type;
  674. fieldCurves.curves = new EdAnimationCurve[1];
  675. fieldCurves.curves[0] = new EdAnimationCurve();
  676. selectedFields.Add(path);
  677. clipInfo.curves[path] = fieldCurves;
  678. }
  679. break;
  680. }
  681. EditorApplication.SetProjectDirty();
  682. UpdateDisplayedCurves();
  683. }
  684. private void SelectField(string path, bool additive)
  685. {
  686. if (!additive)
  687. selectedFields.Clear();
  688. if (!string.IsNullOrEmpty(path))
  689. {
  690. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  691. selectedFields.Add(path);
  692. }
  693. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  694. UpdateDisplayedCurves();
  695. }
  696. private void RemoveSelectedFields()
  697. {
  698. for (int i = 0; i < selectedFields.Count; i++)
  699. {
  700. selectedFields.Remove(selectedFields[i]);
  701. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  702. }
  703. List<string> existingFields = new List<string>();
  704. foreach (var KVP in clipInfo.curves)
  705. existingFields.Add(KVP.Key);
  706. guiFieldDisplay.SetFields(existingFields.ToArray());
  707. selectedFields.Clear();
  708. EditorApplication.SetProjectDirty();
  709. UpdateDisplayedCurves();
  710. }
  711. #endregion
  712. #region Helpers
  713. private Vector2I GetCurveEditorSize()
  714. {
  715. Vector2I output = new Vector2I();
  716. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  717. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  718. return output;
  719. }
  720. private static void CalculateRange(List<EdAnimationCurve> curves, out float xRange, out float yRange)
  721. {
  722. xRange = 0.0f;
  723. yRange = 0.0f;
  724. foreach (var curve in curves)
  725. {
  726. KeyFrame[] keyframes = curve.KeyFrames;
  727. foreach (var key in keyframes)
  728. {
  729. xRange = Math.Max(xRange, key.time);
  730. yRange = Math.Max(yRange, Math.Abs(key.value));
  731. }
  732. }
  733. }
  734. private bool TryGetCurve(string path, out EdAnimationCurve curve)
  735. {
  736. int index = path.LastIndexOf(".");
  737. string parentPath;
  738. string subPathSuffix = null;
  739. if (index == -1)
  740. {
  741. parentPath = path;
  742. }
  743. else
  744. {
  745. parentPath = path.Substring(0, index);
  746. subPathSuffix = path.Substring(index, path.Length - index);
  747. }
  748. FieldAnimCurves fieldCurves;
  749. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  750. {
  751. if (!string.IsNullOrEmpty(subPathSuffix))
  752. {
  753. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  754. {
  755. curve = fieldCurves.curves[0];
  756. return true;
  757. }
  758. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  759. {
  760. curve = fieldCurves.curves[1];
  761. return true;
  762. }
  763. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  764. {
  765. curve = fieldCurves.curves[2];
  766. return true;
  767. }
  768. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  769. {
  770. curve = fieldCurves.curves[3];
  771. return true;
  772. }
  773. }
  774. else
  775. {
  776. curve = fieldCurves.curves[0];
  777. return true;
  778. }
  779. }
  780. curve = null;
  781. return false;
  782. }
  783. private bool IsPathParent(string child, string parent)
  784. {
  785. string[] childEntries = child.Split('/', '.');
  786. string[] parentEntries = parent.Split('/', '.');
  787. if (parentEntries.Length >= child.Length)
  788. return false;
  789. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  790. for (int i = 0; i < compareLength; i++)
  791. {
  792. if (childEntries[i] != parentEntries[i])
  793. return false;
  794. }
  795. return true;
  796. }
  797. private string GetSubPathParent(string path)
  798. {
  799. int index = path.LastIndexOf(".");
  800. if (index == -1)
  801. return path;
  802. return path.Substring(0, index);
  803. }
  804. #endregion
  805. #region Input callbacks
  806. private void OnPointerPressed(PointerEvent ev)
  807. {
  808. guiCurveEditor.OnPointerPressed(ev);
  809. if (ev.button == PointerButton.Middle)
  810. {
  811. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  812. Vector2 curvePos;
  813. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  814. {
  815. dragStartPos = windowPos;
  816. isButtonHeld = true;
  817. }
  818. }
  819. }
  820. private void OnPointerMoved(PointerEvent ev)
  821. {
  822. guiCurveEditor.OnPointerMoved(ev);
  823. if (isButtonHeld)
  824. {
  825. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  826. int distance = Vector2I.Distance(dragStartPos, windowPos);
  827. if (distance >= DRAG_START_DISTANCE)
  828. {
  829. isDragInProgress = true;
  830. Cursor.Hide();
  831. Rect2I clipRect;
  832. clipRect.x = ev.ScreenPos.x - 2;
  833. clipRect.y = ev.ScreenPos.y - 2;
  834. clipRect.width = 4;
  835. clipRect.height = 4;
  836. Cursor.ClipToRect(clipRect);
  837. }
  838. }
  839. }
  840. private void OnPointerReleased(PointerEvent ev)
  841. {
  842. if (isDragInProgress)
  843. {
  844. Cursor.Show();
  845. Cursor.ClipDisable();
  846. }
  847. isButtonHeld = false;
  848. isDragInProgress = false;
  849. guiCurveEditor.OnPointerReleased(ev);
  850. }
  851. private void OnButtonUp(ButtonEvent ev)
  852. {
  853. guiCurveEditor.OnButtonUp(ev);
  854. }
  855. #endregion
  856. #region General callbacks
  857. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  858. {
  859. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  860. string pathNoRoot = path.TrimStart('/');
  861. int separatorIdx = pathNoRoot.IndexOf("/");
  862. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  863. return;
  864. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  865. AddNewField(pathNoRoot, type);
  866. }
  867. private void OnHorzScrollOrResize(float position, float size)
  868. {
  869. SetHorzScrollbarProperties(position, size);
  870. }
  871. private void OnVertScrollOrResize(float position, float size)
  872. {
  873. SetVertScrollbarProperties(position, size);
  874. }
  875. private void OnFieldSelected(string path)
  876. {
  877. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  878. SelectField(path, additive);
  879. }
  880. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  881. {
  882. UpdateSelectedSO(false);
  883. }
  884. private void OnFrameSelected(int frameIdx)
  885. {
  886. SetCurrentFrame(frameIdx);
  887. }
  888. private void OnEventsChanged()
  889. {
  890. clipInfo.events = guiCurveEditor.Events;
  891. EditorApplication.SetProjectDirty();
  892. }
  893. #endregion
  894. }
  895. /// <summary>
  896. /// Drop down window that displays options used by the animation window.
  897. /// </summary>
  898. [DefaultSize(100, 50)]
  899. internal class AnimationOptions : DropDownWindow
  900. {
  901. /// <summary>
  902. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  903. /// use.
  904. /// </summary>
  905. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  906. internal void Initialize(AnimationWindow parent)
  907. {
  908. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  909. fpsField.Value = parent.FPS;
  910. fpsField.OnChanged += x => { parent.FPS = x; };
  911. GUILayoutY vertLayout = GUI.AddLayoutY();
  912. vertLayout.AddFlexibleSpace();
  913. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  914. contentLayout.AddFlexibleSpace();
  915. contentLayout.AddElement(fpsField);
  916. contentLayout.AddFlexibleSpace();
  917. vertLayout.AddFlexibleSpace();
  918. }
  919. }
  920. /** @} */
  921. }