AnimationWindow.cs 41 KB

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