AnimationWindow.cs 79 KB

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