AnimationWindow.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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 = 300;
  19. private const int DRAG_START_DISTANCE = 3;
  20. private const float DRAG_SCALE = 3.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 (clipInfo.isImported)
  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 (clipInfo.isImported)
  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. UpdateScrollBarSize();
  294. }
  295. private void ResizeGUI(int width, int height)
  296. {
  297. guiFieldDisplay.SetSize(FIELD_DISPLAY_WIDTH, height - buttonLayoutHeight * 2);
  298. Vector2I curveEditorSize = GetCurveEditorSize();
  299. guiCurveEditor.SetSize(curveEditorSize.x, curveEditorSize.y);
  300. guiCurveEditor.Redraw();
  301. horzScrollBar.SetWidth(curveEditorSize.x);
  302. vertScrollBar.SetHeight(curveEditorSize.y);
  303. UpdateScrollBarSize();
  304. UpdateScrollBarPosition();
  305. }
  306. #endregion
  307. #region Scroll, drag, zoom
  308. private Vector2I dragStartPos;
  309. private bool isButtonHeld;
  310. private bool isDragInProgress;
  311. private float zoomAmount;
  312. private void HandleDragAndZoomInput()
  313. {
  314. // Handle middle mouse dragging
  315. if (isDragInProgress)
  316. {
  317. float lengthPerPixel = guiCurveEditor.Range.x / guiCurveEditor.Width;
  318. float heightPerPixel = guiCurveEditor.Range.y / guiCurveEditor.Height;
  319. float dragX = Input.GetAxisValue(InputAxis.MouseX) * DRAG_SCALE * lengthPerPixel;
  320. float dragY = Input.GetAxisValue(InputAxis.MouseY) * DRAG_SCALE * heightPerPixel;
  321. Vector2 offset = guiCurveEditor.Offset;
  322. offset.x = Math.Max(0.0f, offset.x + dragX);
  323. offset.y -= dragY;
  324. guiCurveEditor.Offset = offset;
  325. UpdateScrollBarSize();
  326. UpdateScrollBarPosition();
  327. }
  328. // Handle zoom in/out
  329. float scroll = Input.GetAxisValue(InputAxis.MouseZ);
  330. if (scroll != 0.0f)
  331. {
  332. Vector2I windowPos = ScreenToWindowPos(Input.PointerPosition);
  333. Vector2 curvePos;
  334. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  335. {
  336. float zoom = scroll * ZOOM_SCALE;
  337. Zoom(curvePos, zoom);
  338. }
  339. }
  340. }
  341. private void SetVertScrollbarProperties(float position, float size)
  342. {
  343. Vector2 visibleRange = guiCurveEditor.Range;
  344. Vector2 totalRange = GetTotalRange();
  345. visibleRange.y = totalRange.y*size;
  346. guiCurveEditor.Range = visibleRange;
  347. float scrollableRange = totalRange.y - visibleRange.y;
  348. Vector2 offset = guiCurveEditor.Offset;
  349. offset.y = -scrollableRange * (position * 2.0f - 1.0f);
  350. guiCurveEditor.Offset = offset;
  351. }
  352. private void SetHorzScrollbarProperties(float position, float size)
  353. {
  354. Vector2 visibleRange = guiCurveEditor.Range;
  355. Vector2 totalRange = GetTotalRange();
  356. visibleRange.x = totalRange.x * size;
  357. guiCurveEditor.Range = visibleRange;
  358. float scrollableRange = totalRange.x - visibleRange.x;
  359. Vector2 offset = guiCurveEditor.Offset;
  360. offset.x = scrollableRange * position;
  361. guiCurveEditor.Offset = offset;
  362. }
  363. private void UpdateScrollBarSize()
  364. {
  365. Vector2 visibleRange = guiCurveEditor.Range;
  366. Vector2 totalRange = GetTotalRange();
  367. horzScrollBar.HandleSize = visibleRange.x / totalRange.x;
  368. vertScrollBar.HandleSize = visibleRange.y / totalRange.y;
  369. }
  370. private void UpdateScrollBarPosition()
  371. {
  372. Vector2 visibleRange = guiCurveEditor.Range;
  373. Vector2 totalRange = GetTotalRange();
  374. Vector2 scrollableRange = totalRange - visibleRange;
  375. Vector2 offset = guiCurveEditor.Offset;
  376. if (scrollableRange.x > 0.0f)
  377. horzScrollBar.Position = offset.x / scrollableRange.x;
  378. else
  379. horzScrollBar.Position = 0.0f;
  380. if (scrollableRange.y > 0.0f)
  381. {
  382. float pos = offset.y/scrollableRange.y;
  383. float sign = MathEx.Sign(pos);
  384. pos = sign*MathEx.Clamp01(MathEx.Abs(pos));
  385. pos = (1.0f - pos) /2.0f;
  386. vertScrollBar.Position = pos;
  387. }
  388. else
  389. vertScrollBar.Position = 0.0f;
  390. }
  391. private Vector2 GetZoomedRange()
  392. {
  393. float zoomLevel = MathEx.Pow(2, zoomAmount);
  394. Vector2 optimalRange = GetOptimalRange();
  395. return optimalRange / zoomLevel;
  396. }
  397. private Vector2 GetTotalRange()
  398. {
  399. // Return optimal range (that covers the visible curve)
  400. Vector2 optimalRange = GetOptimalRange();
  401. // Increase range in case user zoomed out
  402. Vector2 zoomedRange = GetZoomedRange();
  403. return Vector2.Max(optimalRange, zoomedRange);
  404. }
  405. private void Zoom(Vector2 curvePos, float amount)
  406. {
  407. // Increase or decrease the visible range depending on zoom level
  408. Vector2 oldZoomedRange = GetZoomedRange();
  409. zoomAmount = MathEx.Clamp(zoomAmount + amount, -10.0f, 10.0f);
  410. Vector2 zoomedRange = GetZoomedRange();
  411. Vector2 zoomedDiff = zoomedRange - oldZoomedRange;
  412. Vector2 currentRange = guiCurveEditor.Range;
  413. Vector2 newRange = currentRange + zoomedDiff;
  414. guiCurveEditor.Range = newRange;
  415. // When zooming, make sure to focus on the point provided, so adjust the offset
  416. Vector2 rangeScale = newRange;
  417. rangeScale.x /= currentRange.x;
  418. rangeScale.y /= currentRange.y;
  419. Vector2 relativeCurvePos = curvePos - guiCurveEditor.Offset;
  420. Vector2 newCurvePos = relativeCurvePos * rangeScale;
  421. Vector2 diff = newCurvePos - relativeCurvePos;
  422. guiCurveEditor.Offset -= diff;
  423. UpdateScrollBarSize();
  424. UpdateScrollBarPosition();
  425. }
  426. #endregion
  427. #region Curve save/load
  428. private EditorAnimClipInfo clipInfo;
  429. private void LoadAnimClip(AnimationClip clip)
  430. {
  431. EditorPersistentData persistentData = EditorApplication.PersistentData;
  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 (clipInfo.isImported)
  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(new AnimFieldInfo(curve.Key, curve.Value.type, !clipInfo.isImported));
  448. guiCurveEditor.Events = clipInfo.events;
  449. guiCurveEditor.DisableCurveEdit = clipInfo.isImported;
  450. SetCurrentFrame(0);
  451. }
  452. private void UpdateSelectedSO(bool force)
  453. {
  454. SceneObject so = Selection.SceneObject;
  455. if (selectedSO != so || force)
  456. {
  457. if (selectedSO != null && so == null)
  458. {
  459. EditorInput.OnPointerPressed -= OnPointerPressed;
  460. EditorInput.OnPointerMoved -= OnPointerMoved;
  461. EditorInput.OnPointerReleased -= OnPointerReleased;
  462. EditorInput.OnButtonUp -= OnButtonUp;
  463. }
  464. else if (selectedSO == null && so != null)
  465. {
  466. EditorInput.OnPointerPressed += OnPointerPressed;
  467. EditorInput.OnPointerMoved += OnPointerMoved;
  468. EditorInput.OnPointerReleased += OnPointerReleased;
  469. EditorInput.OnButtonUp += OnButtonUp;
  470. }
  471. zoomAmount = 0.0f;
  472. selectedSO = so;
  473. selectedFields.Clear();
  474. clipInfo = null;
  475. RebuildGUI();
  476. // Load existing clip if one exists
  477. if (selectedSO != null)
  478. {
  479. Animation animation = selectedSO.GetComponent<Animation>();
  480. if (animation != null)
  481. {
  482. AnimationClip clip = animation.DefaultClip;
  483. if (clip != null)
  484. LoadAnimClip(clip);
  485. }
  486. }
  487. if(clipInfo == null)
  488. clipInfo = new EditorAnimClipInfo();
  489. UpdateDisplayedCurves(true);
  490. }
  491. }
  492. #endregion
  493. #region Curve display
  494. private int currentFrameIdx;
  495. private int fps = 1;
  496. internal int FPS
  497. {
  498. get { return fps; }
  499. set { guiCurveEditor.SetFPS(value); fps = MathEx.Max(value, 1); }
  500. }
  501. private void SetCurrentFrame(int frameIdx)
  502. {
  503. currentFrameIdx = Math.Max(0, frameIdx);
  504. frameInputField.Value = currentFrameIdx;
  505. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  506. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  507. Debug.Log(currentFrameIdx + " - " + time);
  508. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  509. foreach (var kvp in clipInfo.curves)
  510. {
  511. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  512. fieldValue.path = kvp.Key;
  513. switch (kvp.Value.type)
  514. {
  515. case SerializableProperty.FieldType.Vector2:
  516. {
  517. Vector2 value = new Vector2();
  518. for (int i = 0; i < 2; i++)
  519. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  520. fieldValue.value = value;
  521. }
  522. break;
  523. case SerializableProperty.FieldType.Vector3:
  524. {
  525. Vector3 value = new Vector3();
  526. for (int i = 0; i < 3; i++)
  527. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  528. fieldValue.value = value;
  529. }
  530. break;
  531. case SerializableProperty.FieldType.Vector4:
  532. {
  533. Vector4 value = new Vector4();
  534. for (int i = 0; i < 4; i++)
  535. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  536. fieldValue.value = value;
  537. }
  538. break;
  539. case SerializableProperty.FieldType.Color:
  540. {
  541. Color value = new Color();
  542. for (int i = 0; i < 4; i++)
  543. value[i] = kvp.Value.curves[i].Evaluate(time, false);
  544. fieldValue.value = value;
  545. }
  546. break;
  547. case SerializableProperty.FieldType.Bool:
  548. case SerializableProperty.FieldType.Int:
  549. case SerializableProperty.FieldType.Float:
  550. fieldValue.value = kvp.Value.curves[0].Evaluate(time, false); ;
  551. break;
  552. }
  553. values.Add(fieldValue);
  554. }
  555. guiFieldDisplay.SetDisplayValues(values.ToArray());
  556. }
  557. private EdAnimationCurve[] GetDisplayedCurves()
  558. {
  559. List<EdAnimationCurve> curvesToDisplay = new List<EdAnimationCurve>();
  560. if (selectedFields.Count == 0) // Display all if nothing is selected
  561. {
  562. if (clipInfo == null)
  563. return curvesToDisplay.ToArray();
  564. foreach (var curve in clipInfo.curves)
  565. {
  566. for (int i = 0; i < curve.Value.curves.Length; i++)
  567. curvesToDisplay.Add(curve.Value.curves[i]);
  568. }
  569. }
  570. else
  571. {
  572. for (int i = 0; i < selectedFields.Count; i++)
  573. {
  574. EdAnimationCurve curve;
  575. if (TryGetCurve(selectedFields[i], out curve))
  576. curvesToDisplay.Add(curve);
  577. }
  578. }
  579. return curvesToDisplay.ToArray();
  580. }
  581. private Vector2 GetOptimalRange()
  582. {
  583. EdAnimationCurve[] curvesToDisplay = GetDisplayedCurves();
  584. float xRange;
  585. float yRange;
  586. CalculateRange(curvesToDisplay, out xRange, out yRange);
  587. // Add padding to y range
  588. yRange *= 1.05f;
  589. // Don't allow zero range
  590. if (xRange == 0.0f)
  591. xRange = 60.0f;
  592. if (yRange == 0.0f)
  593. yRange = 10.0f;
  594. return new Vector2(xRange, yRange);
  595. }
  596. private void UpdateDisplayedCurves(bool allowReduce = false)
  597. {
  598. EdAnimationCurve[] curvesToDisplay = GetDisplayedCurves();
  599. guiCurveEditor.SetCurves(curvesToDisplay);
  600. Vector2 newRange = GetOptimalRange();
  601. if (!allowReduce)
  602. {
  603. // Don't reduce visible range
  604. newRange.x = Math.Max(newRange.x, guiCurveEditor.Range.x);
  605. newRange.y = Math.Max(newRange.y, guiCurveEditor.Range.y);
  606. }
  607. guiCurveEditor.Range = newRange;
  608. UpdateScrollBarSize();
  609. }
  610. #endregion
  611. #region Field display
  612. private List<string> selectedFields = new List<string>();
  613. private void AddNewField(string path, SerializableProperty.FieldType type)
  614. {
  615. bool noSelection = selectedFields.Count == 0;
  616. guiFieldDisplay.AddField(new AnimFieldInfo(path, type, !clipInfo.isImported));
  617. switch (type)
  618. {
  619. case SerializableProperty.FieldType.Vector4:
  620. {
  621. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  622. fieldCurves.type = type;
  623. fieldCurves.curves = new EdAnimationCurve[4];
  624. string[] subPaths = { ".x", ".y", ".z", ".w" };
  625. for (int i = 0; i < subPaths.Length; i++)
  626. {
  627. string subFieldPath = path + subPaths[i];
  628. fieldCurves.curves[i] = new EdAnimationCurve();
  629. selectedFields.Add(subFieldPath);
  630. }
  631. clipInfo.curves[path] = fieldCurves;
  632. }
  633. break;
  634. case SerializableProperty.FieldType.Vector3:
  635. {
  636. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  637. fieldCurves.type = type;
  638. fieldCurves.curves = new EdAnimationCurve[3];
  639. string[] subPaths = { ".x", ".y", ".z" };
  640. for (int i = 0; i < subPaths.Length; i++)
  641. {
  642. string subFieldPath = path + subPaths[i];
  643. fieldCurves.curves[i] = new EdAnimationCurve();
  644. selectedFields.Add(subFieldPath);
  645. }
  646. clipInfo.curves[path] = fieldCurves;
  647. }
  648. break;
  649. case SerializableProperty.FieldType.Vector2:
  650. {
  651. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  652. fieldCurves.type = type;
  653. fieldCurves.curves = new EdAnimationCurve[2];
  654. string[] subPaths = { ".x", ".y" };
  655. for (int i = 0; i < subPaths.Length; i++)
  656. {
  657. string subFieldPath = path + subPaths[i];
  658. fieldCurves.curves[i] = new EdAnimationCurve();
  659. selectedFields.Add(subFieldPath);
  660. }
  661. clipInfo.curves[path] = fieldCurves;
  662. }
  663. break;
  664. case SerializableProperty.FieldType.Color:
  665. {
  666. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  667. fieldCurves.type = type;
  668. fieldCurves.curves = new EdAnimationCurve[4];
  669. string[] subPaths = { ".r", ".g", ".b", ".a" };
  670. for (int i = 0; i < subPaths.Length; i++)
  671. {
  672. string subFieldPath = path + subPaths[i];
  673. fieldCurves.curves[i] = new EdAnimationCurve();
  674. selectedFields.Add(subFieldPath);
  675. }
  676. clipInfo.curves[path] = fieldCurves;
  677. }
  678. break;
  679. default: // Primitive type
  680. {
  681. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  682. fieldCurves.type = type;
  683. fieldCurves.curves = new EdAnimationCurve[1];
  684. fieldCurves.curves[0] = new EdAnimationCurve();
  685. selectedFields.Add(path);
  686. clipInfo.curves[path] = fieldCurves;
  687. }
  688. break;
  689. }
  690. EditorApplication.SetProjectDirty();
  691. UpdateDisplayedCurves(noSelection);
  692. }
  693. private void SelectField(string path, bool additive)
  694. {
  695. if (!additive)
  696. selectedFields.Clear();
  697. bool noSelection = selectedFields.Count == 0;
  698. if (!string.IsNullOrEmpty(path))
  699. {
  700. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  701. selectedFields.Add(path);
  702. }
  703. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  704. UpdateDisplayedCurves(noSelection);
  705. }
  706. private void RemoveSelectedFields()
  707. {
  708. for (int i = 0; i < selectedFields.Count; i++)
  709. {
  710. selectedFields.Remove(selectedFields[i]);
  711. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  712. }
  713. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  714. foreach (var KVP in clipInfo.curves)
  715. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value.type, !clipInfo.isImported));
  716. guiFieldDisplay.SetFields(existingFields.ToArray());
  717. selectedFields.Clear();
  718. EditorApplication.SetProjectDirty();
  719. UpdateDisplayedCurves();
  720. }
  721. #endregion
  722. #region Helpers
  723. private Vector2I GetCurveEditorSize()
  724. {
  725. Vector2I output = new Vector2I();
  726. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH - scrollBarWidth);
  727. output.y = Math.Max(0, Height - buttonLayoutHeight - scrollBarHeight);
  728. return output;
  729. }
  730. private static void CalculateRange(EdAnimationCurve[] curves, out float xRange, out float yRange)
  731. {
  732. xRange = 0.0f;
  733. yRange = 0.0f;
  734. foreach (var curve in curves)
  735. {
  736. KeyFrame[] keyframes = curve.KeyFrames;
  737. foreach (var key in keyframes)
  738. {
  739. xRange = Math.Max(xRange, key.time);
  740. yRange = Math.Max(yRange, Math.Abs(key.value));
  741. }
  742. }
  743. }
  744. private bool TryGetCurve(string path, out EdAnimationCurve curve)
  745. {
  746. int index = path.LastIndexOf(".");
  747. string parentPath;
  748. string subPathSuffix = null;
  749. if (index == -1)
  750. {
  751. parentPath = path;
  752. }
  753. else
  754. {
  755. parentPath = path.Substring(0, index);
  756. subPathSuffix = path.Substring(index, path.Length - index);
  757. }
  758. FieldAnimCurves fieldCurves;
  759. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  760. {
  761. if (!string.IsNullOrEmpty(subPathSuffix))
  762. {
  763. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  764. {
  765. curve = fieldCurves.curves[0];
  766. return true;
  767. }
  768. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  769. {
  770. curve = fieldCurves.curves[1];
  771. return true;
  772. }
  773. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  774. {
  775. curve = fieldCurves.curves[2];
  776. return true;
  777. }
  778. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  779. {
  780. curve = fieldCurves.curves[3];
  781. return true;
  782. }
  783. }
  784. else
  785. {
  786. curve = fieldCurves.curves[0];
  787. return true;
  788. }
  789. }
  790. curve = null;
  791. return false;
  792. }
  793. private bool IsPathParent(string child, string parent)
  794. {
  795. string[] childEntries = child.Split('/', '.');
  796. string[] parentEntries = parent.Split('/', '.');
  797. if (parentEntries.Length >= child.Length)
  798. return false;
  799. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  800. for (int i = 0; i < compareLength; i++)
  801. {
  802. if (childEntries[i] != parentEntries[i])
  803. return false;
  804. }
  805. return true;
  806. }
  807. private string GetSubPathParent(string path)
  808. {
  809. int index = path.LastIndexOf(".");
  810. if (index == -1)
  811. return path;
  812. return path.Substring(0, index);
  813. }
  814. #endregion
  815. #region Input callbacks
  816. private void OnPointerPressed(PointerEvent ev)
  817. {
  818. guiCurveEditor.OnPointerPressed(ev);
  819. if (ev.button == PointerButton.Middle)
  820. {
  821. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  822. Vector2 curvePos;
  823. if (guiCurveEditor.WindowToCurveSpace(windowPos, out curvePos))
  824. {
  825. dragStartPos = windowPos;
  826. isButtonHeld = true;
  827. }
  828. }
  829. }
  830. private void OnPointerMoved(PointerEvent ev)
  831. {
  832. guiCurveEditor.OnPointerMoved(ev);
  833. if (isButtonHeld)
  834. {
  835. Vector2I windowPos = ScreenToWindowPos(ev.ScreenPos);
  836. int distance = Vector2I.Distance(dragStartPos, windowPos);
  837. if (distance >= DRAG_START_DISTANCE)
  838. {
  839. isDragInProgress = true;
  840. Cursor.Hide();
  841. Rect2I clipRect;
  842. clipRect.x = ev.ScreenPos.x - 2;
  843. clipRect.y = ev.ScreenPos.y - 2;
  844. clipRect.width = 4;
  845. clipRect.height = 4;
  846. Cursor.ClipToRect(clipRect);
  847. }
  848. }
  849. }
  850. private void OnPointerReleased(PointerEvent ev)
  851. {
  852. if (isDragInProgress)
  853. {
  854. Cursor.Show();
  855. Cursor.ClipDisable();
  856. }
  857. isButtonHeld = false;
  858. isDragInProgress = false;
  859. guiCurveEditor.OnPointerReleased(ev);
  860. }
  861. private void OnButtonUp(ButtonEvent ev)
  862. {
  863. guiCurveEditor.OnButtonUp(ev);
  864. }
  865. #endregion
  866. #region General callbacks
  867. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  868. {
  869. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  870. string pathNoRoot = path.TrimStart('/');
  871. int separatorIdx = pathNoRoot.IndexOf("/");
  872. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  873. return;
  874. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  875. AddNewField(pathNoRoot, type);
  876. }
  877. private void OnHorzScrollOrResize(float position, float size)
  878. {
  879. SetHorzScrollbarProperties(position, size);
  880. }
  881. private void OnVertScrollOrResize(float position, float size)
  882. {
  883. SetVertScrollbarProperties(position, size);
  884. }
  885. private void OnFieldSelected(string path)
  886. {
  887. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  888. SelectField(path, additive);
  889. }
  890. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  891. {
  892. UpdateSelectedSO(false);
  893. }
  894. private void OnFrameSelected(int frameIdx)
  895. {
  896. SetCurrentFrame(frameIdx);
  897. }
  898. private void OnEventsChanged()
  899. {
  900. clipInfo.events = guiCurveEditor.Events;
  901. EditorApplication.SetProjectDirty();
  902. }
  903. #endregion
  904. }
  905. /// <summary>
  906. /// Drop down window that displays options used by the animation window.
  907. /// </summary>
  908. [DefaultSize(100, 50)]
  909. internal class AnimationOptions : DropDownWindow
  910. {
  911. /// <summary>
  912. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  913. /// use.
  914. /// </summary>
  915. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  916. internal void Initialize(AnimationWindow parent)
  917. {
  918. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  919. fpsField.Value = parent.FPS;
  920. fpsField.OnChanged += x => { parent.FPS = x; };
  921. GUILayoutY vertLayout = GUI.AddLayoutY();
  922. vertLayout.AddFlexibleSpace();
  923. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  924. contentLayout.AddFlexibleSpace();
  925. contentLayout.AddElement(fpsField);
  926. contentLayout.AddFlexibleSpace();
  927. vertLayout.AddFlexibleSpace();
  928. }
  929. }
  930. /** @} */
  931. }