AnimationWindow.cs 63 KB

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