AnimationWindow.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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. guiCurveEditor.SetFPS(clipInfo.sampleRate);
  417. SetCurrentFrame(0);
  418. fps = clipInfo.sampleRate;
  419. }
  420. /// <summary>
  421. /// Applies any changes made to the animation curves and events to the actual animation clip resource.
  422. /// </summary>
  423. private void ApplyClipChanges()
  424. {
  425. if (clipInfo == null)
  426. return;
  427. clipInfo.Apply(out _);
  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. clipInfo.Apply(out _);
  696. Animation animation = selectedSO.GetComponent<Animation>();
  697. if (animation != null && clipInfo.clip != null)
  698. {
  699. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  700. animation.EditorPlay(clipInfo.clip, time);
  701. EditorApplication.ToggleOnDemandDrawing("__AnimationPreview", false);
  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. EditorApplication.ToggleOnDemandDrawing("__AnimationPreview", true);
  712. playButton.Value = false;
  713. }
  714. /// <summary>
  715. /// Updates the visible animation to display the provided frame.
  716. /// </summary>
  717. /// <param name="frameIdx">Index of the animation frame to display.</param>
  718. private void PreviewFrame(int frameIdx)
  719. {
  720. if (selectedSO == null)
  721. return;
  722. float time = guiCurveEditor.GetTimeForFrame(frameIdx);
  723. Animation animation = selectedSO.GetComponent<Animation>();
  724. if (animation != null && clipInfo.clip != null)
  725. animation.EditorPlay(clipInfo.clip, time, true);
  726. UpdateGenericCurves(time);
  727. EditorApplication.NotifyNeedsRedraw();
  728. }
  729. /// <summary>
  730. /// Start recording modifications made to the selected scene object.
  731. /// </summary>
  732. private void StartRecord()
  733. {
  734. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  735. if (RecordState(time))
  736. {
  737. ApplyClipChanges();
  738. guiCurveEditor.Redraw();
  739. }
  740. recordButton.Value = true;
  741. }
  742. /// <summary>
  743. /// Stops recording modifications made to the selected scene object.
  744. /// </summary>
  745. private void EndRecord()
  746. {
  747. recordButton.Value = false;
  748. }
  749. /// <summary>
  750. /// Updates the states of all properties controlled by curves to the value of the curves at the provided time.
  751. /// </summary>
  752. /// <param name="time">Time at which to evaluate the curves controlling the properties.</param>
  753. private void UpdateGenericCurves(float time)
  754. {
  755. foreach (var KVP in clipInfo.curves)
  756. {
  757. FieldAnimCurves curves;
  758. if (!clipInfo.curves.TryGetValue(KVP.Key, out curves))
  759. continue;
  760. string suffix;
  761. SerializableProperty property = Animation.FindProperty(selectedSO, KVP.Key, out suffix);
  762. if (property == null)
  763. continue;
  764. float DoOnComponent(int index)
  765. {
  766. EdAnimationCurve curve = curves.curveInfos[index].curve;
  767. return curve.Evaluate(time);
  768. }
  769. ForEachPropertyComponentSet(property, DoOnComponent);
  770. }
  771. }
  772. /// <summary>
  773. /// Iterates over all curve path fields and records their current state. If the state differs from the current
  774. /// curve values, new keyframes are added.
  775. /// </summary>
  776. /// <param name="time">Time for which to record the state, in seconds.</param>
  777. /// <returns>True if any changes were recorded, false otherwise.</returns>
  778. private bool RecordState(float time)
  779. {
  780. bool changesMade = false;
  781. foreach (var KVP in clipInfo.curves)
  782. {
  783. if (RecordState(KVP.Key, time))
  784. changesMade = true;
  785. }
  786. return changesMade;
  787. }
  788. /// <summary>
  789. /// Records the state of the provided property and adds it as a keyframe to the related animation curve (or updates
  790. /// an existing keyframe if the value is different).
  791. /// </summary>
  792. /// <param name="path">Path to the property whose state to record.</param>
  793. /// <param name="time">Time for which to record the state, in seconds.</param>
  794. /// <returns>True if any changes were recorded, false otherwise.</returns>
  795. private bool RecordState(string path, float time)
  796. {
  797. FieldAnimCurves curves;
  798. if (!clipInfo.curves.TryGetValue(path, out curves))
  799. return false;
  800. string suffix;
  801. SerializableProperty property = Animation.FindProperty(selectedSO, path, out suffix);
  802. if (property == null)
  803. return false;
  804. bool changesMade = false;
  805. void DoOnComponent(float value, int index)
  806. {
  807. EdAnimationCurve curve = curves.curveInfos[index].curve;
  808. float curveVal = curve.Evaluate(time);
  809. if (!MathEx.ApproxEquals(value, curveVal, 0.001f))
  810. {
  811. curve.AddOrUpdateKeyframe(time, value);
  812. curve.Apply();
  813. changesMade = true;
  814. }
  815. }
  816. ForEachPropertyComponentGet(property, DoOnComponent);
  817. return changesMade;
  818. }
  819. #endregion
  820. #region Curve display
  821. private int currentFrameIdx;
  822. private int fps = 1;
  823. /// <summary>
  824. /// Sampling rate of the animation in frames per second. Determines granularity at which positions keyframes can be
  825. /// placed.
  826. /// </summary>
  827. internal int FPS
  828. {
  829. get { return fps; }
  830. set
  831. {
  832. fps = MathEx.Max(value, 1);
  833. guiCurveEditor.SetFPS(fps);
  834. if (clipInfo != null)
  835. clipInfo.sampleRate = fps;
  836. }
  837. }
  838. /// <summary>
  839. /// Changes the currently selected frame in the curve display.
  840. /// </summary>
  841. /// <param name="frameIdx">Index of the frame to select.</param>
  842. private void SetCurrentFrame(int frameIdx)
  843. {
  844. currentFrameIdx = Math.Max(0, frameIdx);
  845. frameInputField.Value = currentFrameIdx;
  846. guiCurveEditor.SetMarkedFrame(currentFrameIdx);
  847. float time = guiCurveEditor.GetTimeForFrame(currentFrameIdx);
  848. List<GUIAnimFieldPathValue> values = new List<GUIAnimFieldPathValue>();
  849. foreach (var kvp in clipInfo.curves)
  850. {
  851. GUIAnimFieldPathValue fieldValue = new GUIAnimFieldPathValue();
  852. fieldValue.path = kvp.Key;
  853. switch (kvp.Value.type)
  854. {
  855. case SerializableProperty.FieldType.Vector2:
  856. {
  857. Vector2 value = new Vector2();
  858. for (int i = 0; i < 2; i++)
  859. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  860. fieldValue.value = value;
  861. }
  862. break;
  863. case SerializableProperty.FieldType.Vector3:
  864. {
  865. Vector3 value = new Vector3();
  866. for (int i = 0; i < 3; i++)
  867. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  868. fieldValue.value = value;
  869. }
  870. break;
  871. case SerializableProperty.FieldType.Vector4:
  872. {
  873. Vector4 value = new Vector4();
  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.Color:
  880. {
  881. Color value = new Color();
  882. for (int i = 0; i < 4; i++)
  883. value[i] = kvp.Value.curveInfos[i].curve.Evaluate(time, false);
  884. fieldValue.value = value;
  885. }
  886. break;
  887. case SerializableProperty.FieldType.Bool:
  888. case SerializableProperty.FieldType.Int:
  889. case SerializableProperty.FieldType.Float:
  890. fieldValue.value = kvp.Value.curveInfos[0].curve.Evaluate(time, false); ;
  891. break;
  892. }
  893. values.Add(fieldValue);
  894. }
  895. guiFieldDisplay.SetDisplayValues(values.ToArray());
  896. }
  897. /// <summary>
  898. /// Returns a list of all animation curves that should be displayed in the curve display.
  899. /// </summary>
  900. /// <returns>Array of curves to display.</returns>
  901. private EdCurveDrawInfo[] GetDisplayedCurves()
  902. {
  903. List<EdCurveDrawInfo> curvesToDisplay = new List<EdCurveDrawInfo>();
  904. if (clipInfo == null)
  905. return curvesToDisplay.ToArray();
  906. for (int i = 0; i < selectedFields.Count; i++)
  907. {
  908. EdCurveDrawInfo[] curveInfos;
  909. if (TryGetCurve(selectedFields[i], out curveInfos))
  910. curvesToDisplay.AddRange(curveInfos);
  911. }
  912. return curvesToDisplay.ToArray();
  913. }
  914. /// <summary>
  915. /// Calculates an unique color for each animation curve.
  916. /// </summary>
  917. private void UpdateCurveColors()
  918. {
  919. int globalCurveIdx = 0;
  920. foreach (var curveGroup in clipInfo.curves)
  921. {
  922. for (int i = 0; i < curveGroup.Value.curveInfos.Length; i++)
  923. curveGroup.Value.curveInfos[i].color = EditorAnimClipInfo.GetUniqueColor(globalCurveIdx++);
  924. }
  925. }
  926. /// <summary>
  927. /// Updates the curve display with currently selected curves.
  928. /// </summary>
  929. /// <param name="resetTime">If true the time offset/range will be recalculated, otherwise current time offset will
  930. /// be kept as is.</param>
  931. private void UpdateDisplayedCurves(bool resetTime = false)
  932. {
  933. EdCurveDrawInfo[] curvesToDisplay = GetDisplayedCurves();
  934. guiCurveEditor.SetCurves(curvesToDisplay);
  935. guiCurveEditor.CenterAndResize(resetTime);
  936. }
  937. #endregion
  938. #region Field display
  939. private List<string> selectedFields = new List<string>();
  940. /// <summary>
  941. /// Registers a new animation curve field.
  942. /// </summary>
  943. /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param>
  944. /// <param name="type">Type of the field (float, vector, etc.)</param>
  945. private void AddNewField(string path, SerializableProperty.FieldType type)
  946. {
  947. bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path);
  948. switch (type)
  949. {
  950. case SerializableProperty.FieldType.Vector4:
  951. {
  952. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  953. fieldCurves.type = type;
  954. fieldCurves.isPropertyCurve = isPropertyCurve;
  955. fieldCurves.curveInfos = new EdCurveDrawInfo[4];
  956. string[] subPaths = { ".x", ".y", ".z", ".w" };
  957. for (int i = 0; i < subPaths.Length; i++)
  958. {
  959. string subFieldPath = path + subPaths[i];
  960. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  961. selectedFields.Add(subFieldPath);
  962. }
  963. clipInfo.curves[path] = fieldCurves;
  964. }
  965. break;
  966. case SerializableProperty.FieldType.Vector3:
  967. {
  968. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  969. fieldCurves.type = type;
  970. fieldCurves.isPropertyCurve = isPropertyCurve;
  971. fieldCurves.curveInfos = new EdCurveDrawInfo[3];
  972. string[] subPaths = { ".x", ".y", ".z" };
  973. for (int i = 0; i < subPaths.Length; i++)
  974. {
  975. string subFieldPath = path + subPaths[i];
  976. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  977. selectedFields.Add(subFieldPath);
  978. }
  979. clipInfo.curves[path] = fieldCurves;
  980. }
  981. break;
  982. case SerializableProperty.FieldType.Vector2:
  983. {
  984. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  985. fieldCurves.type = type;
  986. fieldCurves.isPropertyCurve = isPropertyCurve;
  987. fieldCurves.curveInfos = new EdCurveDrawInfo[2];
  988. string[] subPaths = { ".x", ".y" };
  989. for (int i = 0; i < subPaths.Length; i++)
  990. {
  991. string subFieldPath = path + subPaths[i];
  992. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  993. selectedFields.Add(subFieldPath);
  994. }
  995. clipInfo.curves[path] = fieldCurves;
  996. }
  997. break;
  998. case SerializableProperty.FieldType.Color:
  999. {
  1000. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1001. fieldCurves.type = type;
  1002. fieldCurves.isPropertyCurve = isPropertyCurve;
  1003. fieldCurves.curveInfos = new EdCurveDrawInfo[4];
  1004. string[] subPaths = { ".r", ".g", ".b", ".a" };
  1005. for (int i = 0; i < subPaths.Length; i++)
  1006. {
  1007. string subFieldPath = path + subPaths[i];
  1008. fieldCurves.curveInfos[i].curve = new EdAnimationCurve();
  1009. selectedFields.Add(subFieldPath);
  1010. }
  1011. clipInfo.curves[path] = fieldCurves;
  1012. }
  1013. break;
  1014. default: // Primitive type
  1015. {
  1016. FieldAnimCurves fieldCurves = new FieldAnimCurves();
  1017. fieldCurves.type = type;
  1018. fieldCurves.isPropertyCurve = isPropertyCurve;
  1019. fieldCurves.curveInfos = new EdCurveDrawInfo[1];
  1020. fieldCurves.curveInfos[0].curve = new EdAnimationCurve();
  1021. selectedFields.Add(path);
  1022. clipInfo.curves[path] = fieldCurves;
  1023. }
  1024. break;
  1025. }
  1026. UpdateCurveColors();
  1027. UpdateDisplayedFields();
  1028. EditorApplication.SetProjectDirty();
  1029. UpdateDisplayedCurves();
  1030. }
  1031. /// <summary>
  1032. /// Selects a new animation curve field, making the curve display in the curve display GUI element.
  1033. /// </summary>
  1034. /// <param name="path">Path of the field to display.</param>
  1035. /// <param name="additive">If true the field will be shown along with any already selected fields, or if false
  1036. /// only the provided field will be shown.</param>
  1037. private void SelectField(string path, bool additive)
  1038. {
  1039. if (!additive)
  1040. selectedFields.Clear();
  1041. if (!string.IsNullOrEmpty(path))
  1042. {
  1043. selectedFields.RemoveAll(x => { return x == path || IsPathParent(x, path); });
  1044. selectedFields.Add(path);
  1045. }
  1046. guiFieldDisplay.SetSelection(selectedFields.ToArray());
  1047. UpdateDisplayedCurves();
  1048. }
  1049. /// <summary>
  1050. /// Deletes all currently selecting fields, removing them their curves permanently.
  1051. /// </summary>
  1052. private void RemoveSelectedFields()
  1053. {
  1054. for (int i = 0; i < selectedFields.Count; i++)
  1055. clipInfo.curves.Remove(GetSubPathParent(selectedFields[i]));
  1056. UpdateCurveColors();
  1057. UpdateDisplayedFields();
  1058. selectedFields.Clear();
  1059. EditorApplication.SetProjectDirty();
  1060. UpdateDisplayedCurves();
  1061. }
  1062. /// <summary>
  1063. /// Updates the GUI element displaying the current animation curve fields.
  1064. /// </summary>
  1065. private void UpdateDisplayedFields()
  1066. {
  1067. List<AnimFieldInfo> existingFields = new List<AnimFieldInfo>();
  1068. foreach (var KVP in clipInfo.curves)
  1069. existingFields.Add(new AnimFieldInfo(KVP.Key, KVP.Value));
  1070. guiFieldDisplay.SetFields(existingFields.ToArray());
  1071. }
  1072. #endregion
  1073. #region Helpers
  1074. /// <summary>
  1075. /// Returns the size of the curve editor GUI element.
  1076. /// </summary>
  1077. /// <returns>Width/height of the curve editor, in pixels.</returns>
  1078. private Vector2I GetCurveEditorSize()
  1079. {
  1080. Vector2I output = new Vector2I();
  1081. output.x = Math.Max(0, Width - FIELD_DISPLAY_WIDTH);
  1082. output.y = Math.Max(0, Height - buttonLayoutHeight);
  1083. return output;
  1084. }
  1085. /// <summary>
  1086. /// Attempts to find a curve field at the specified path.
  1087. /// </summary>
  1088. /// <param name="path">Path of the curve field to look for.</param>
  1089. /// <param name="curveInfos">One or multiple curves found for the specific path (one field can have multiple curves
  1090. /// if it is a complex type, like a vector).</param>
  1091. /// <returns>True if the curve field was found, false otherwise.</returns>
  1092. private bool TryGetCurve(string path, out EdCurveDrawInfo[] curveInfos)
  1093. {
  1094. int index = path.LastIndexOf(".");
  1095. string parentPath;
  1096. string subPathSuffix = null;
  1097. if (index == -1)
  1098. {
  1099. parentPath = path;
  1100. }
  1101. else
  1102. {
  1103. parentPath = path.Substring(0, index);
  1104. subPathSuffix = path.Substring(index, path.Length - index);
  1105. }
  1106. FieldAnimCurves fieldCurves;
  1107. if (clipInfo.curves.TryGetValue(parentPath, out fieldCurves))
  1108. {
  1109. if (!string.IsNullOrEmpty(subPathSuffix))
  1110. {
  1111. if (subPathSuffix == ".x" || subPathSuffix == ".r")
  1112. {
  1113. curveInfos = new [] { fieldCurves.curveInfos[0] };
  1114. return true;
  1115. }
  1116. else if (subPathSuffix == ".y" || subPathSuffix == ".g")
  1117. {
  1118. curveInfos = new[] { fieldCurves.curveInfos[1] };
  1119. return true;
  1120. }
  1121. else if (subPathSuffix == ".z" || subPathSuffix == ".b")
  1122. {
  1123. curveInfos = new[] { fieldCurves.curveInfos[2] };
  1124. return true;
  1125. }
  1126. else if (subPathSuffix == ".w" || subPathSuffix == ".a")
  1127. {
  1128. curveInfos = new[] { fieldCurves.curveInfos[3] };
  1129. return true;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. curveInfos = fieldCurves.curveInfos;
  1135. return true;
  1136. }
  1137. }
  1138. curveInfos = new EdCurveDrawInfo[0];
  1139. return false;
  1140. }
  1141. /// <summary>
  1142. /// Checks if one curve field path a parent of the other.
  1143. /// </summary>
  1144. /// <param name="child">Path to check if it is a child of <paramref name="parent"/>.</param>
  1145. /// <param name="parent">Path to check if it is a parent of <paramref name="child"/>.</param>
  1146. /// <returns>True if <paramref name="child"/> is a child of <paramref name="parent"/>.</returns>
  1147. private bool IsPathParent(string child, string parent)
  1148. {
  1149. string[] childEntries = child.Split('/', '.');
  1150. string[] parentEntries = parent.Split('/', '.');
  1151. if (parentEntries.Length >= child.Length)
  1152. return false;
  1153. int compareLength = Math.Min(childEntries.Length, parentEntries.Length);
  1154. for (int i = 0; i < compareLength; i++)
  1155. {
  1156. if (childEntries[i] != parentEntries[i])
  1157. return false;
  1158. }
  1159. return true;
  1160. }
  1161. /// <summary>
  1162. /// If a path has sub-elements (e.g. .x, .r), returns a path without those elements. Otherwise returns the original
  1163. /// path.
  1164. /// </summary>
  1165. /// <param name="path">Path to check.</param>
  1166. /// <returns>Path without sub-elements.</returns>
  1167. private string GetSubPathParent(string path)
  1168. {
  1169. int index = path.LastIndexOf(".");
  1170. if (index == -1)
  1171. return path;
  1172. return path.Substring(0, index);
  1173. }
  1174. /// <summary>
  1175. /// Iterates over all components of a property and calls the provided action for every component with the current
  1176. /// value of the property. Only works with floating point (any dimension), integer, color and boolean property
  1177. /// types. Since reported values are always floating point booleans are encoded as -1.0f for false and 1.0f for
  1178. /// true, and integers are converted to floating point.
  1179. /// </summary>
  1180. /// <param name="property">Property whose components to iterate over.</param>
  1181. /// <param name="action">
  1182. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1183. /// and the sequential index of the component.
  1184. /// </param>
  1185. private void ForEachPropertyComponentGet(SerializableProperty property, Action<float, int> action)
  1186. {
  1187. switch (property.Type)
  1188. {
  1189. case SerializableProperty.FieldType.Vector2:
  1190. {
  1191. Vector2 value = property.GetValue<Vector2>();
  1192. for (int i = 0; i < 2; i++)
  1193. action(value[i], i);
  1194. }
  1195. break;
  1196. case SerializableProperty.FieldType.Vector3:
  1197. {
  1198. Vector3 value = property.GetValue<Vector3>();
  1199. for (int i = 0; i < 3; i++)
  1200. action(value[i], i);
  1201. }
  1202. break;
  1203. case SerializableProperty.FieldType.Vector4:
  1204. {
  1205. Vector4 value = property.GetValue<Vector4>();
  1206. for (int i = 0; i < 4; i++)
  1207. action(value[i], i);
  1208. }
  1209. break;
  1210. case SerializableProperty.FieldType.Color:
  1211. {
  1212. Color value = property.GetValue<Color>();
  1213. for (int i = 0; i < 4; i++)
  1214. action(value[i], i);
  1215. }
  1216. break;
  1217. case SerializableProperty.FieldType.Bool:
  1218. {
  1219. bool value = property.GetValue<bool>();
  1220. action(value ? 1.0f : -1.0f, 0);
  1221. }
  1222. break;
  1223. case SerializableProperty.FieldType.Int:
  1224. {
  1225. int value = property.GetValue<int>();
  1226. action(value, 0);
  1227. }
  1228. break;
  1229. case SerializableProperty.FieldType.Float:
  1230. {
  1231. float value = property.GetValue<float>();
  1232. action(value, 0);
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. /// <summary>
  1238. /// Iterates over all components of a property, calls the provided action which returns a new value to be
  1239. /// assigned to the property component. Only works with floating point (any dimension), integer, color and boolean
  1240. /// property types. Since reported values are always floating point booleans are encoded as -1.0f for false and
  1241. /// 1.0f for true, and integers are converted to floating point.
  1242. /// </summary>
  1243. /// <param name="property">Property whose components to iterate over.</param>
  1244. /// <param name="action">
  1245. /// Callback to trigger for each component. The callback receives the current value of the property's component
  1246. /// and the sequential index of the component.
  1247. /// </param>
  1248. private void ForEachPropertyComponentSet(SerializableProperty property, Func<int, float> action)
  1249. {
  1250. switch (property.Type)
  1251. {
  1252. case SerializableProperty.FieldType.Vector2:
  1253. {
  1254. Vector2 value = new Vector2();
  1255. for (int i = 0; i < 2; i++)
  1256. value[i] = action(i);
  1257. property.SetValue(value);
  1258. }
  1259. break;
  1260. case SerializableProperty.FieldType.Vector3:
  1261. {
  1262. Vector3 value = new Vector3();
  1263. for (int i = 0; i < 3; i++)
  1264. value[i] = action(i);
  1265. property.SetValue(value);
  1266. }
  1267. break;
  1268. case SerializableProperty.FieldType.Vector4:
  1269. {
  1270. Vector4 value = new Vector4();
  1271. for (int i = 0; i < 4; i++)
  1272. value[i] = action(i);
  1273. property.SetValue(value);
  1274. }
  1275. break;
  1276. case SerializableProperty.FieldType.Color:
  1277. {
  1278. Color value = new Color();
  1279. for (int i = 0; i < 4; i++)
  1280. value[i] = action(i);
  1281. property.SetValue(value);
  1282. }
  1283. break;
  1284. case SerializableProperty.FieldType.Bool:
  1285. {
  1286. bool value = action(0) > 0.0f ? true : false;
  1287. property.SetValue(value);
  1288. }
  1289. break;
  1290. case SerializableProperty.FieldType.Int:
  1291. {
  1292. int value = (int)action(0);
  1293. property.SetValue(value);
  1294. }
  1295. break;
  1296. case SerializableProperty.FieldType.Float:
  1297. {
  1298. float value = action(0);
  1299. property.SetValue(value);
  1300. }
  1301. break;
  1302. }
  1303. }
  1304. #endregion
  1305. #region Input callbacks
  1306. /// <summary>
  1307. /// Triggered when the user presses a mouse button.
  1308. /// </summary>
  1309. /// <param name="ev">Information about the mouse press event.</param>
  1310. private void OnPointerPressed(PointerEvent ev)
  1311. {
  1312. guiCurveEditor.OnPointerPressed(ev);
  1313. }
  1314. /// <summary>
  1315. /// Triggered when the user double clicks the left mouse button.
  1316. /// </summary>
  1317. /// <param name="ev">Information about the mouse event.</param>
  1318. private void OnPointerDoubleClicked(PointerEvent ev)
  1319. {
  1320. guiCurveEditor.OnPointerDoubleClicked(ev);
  1321. }
  1322. /// <summary>
  1323. /// Triggered when the user moves the mouse.
  1324. /// </summary>
  1325. /// <param name="ev">Information about the mouse move event.</param>
  1326. private void OnPointerMoved(PointerEvent ev)
  1327. {
  1328. guiCurveEditor.OnPointerMoved(ev);
  1329. }
  1330. /// <summary>
  1331. /// Triggered when the user releases a mouse button.
  1332. /// </summary>
  1333. /// <param name="ev">Information about the mouse release event.</param>
  1334. private void OnPointerReleased(PointerEvent ev)
  1335. {
  1336. guiCurveEditor.OnPointerReleased(ev);
  1337. }
  1338. /// <summary>
  1339. /// Triggered when the user releases a keyboard button.
  1340. /// </summary>
  1341. /// <param name="ev">Information about the keyboard release event.</param>
  1342. private void OnButtonUp(ButtonEvent ev)
  1343. {
  1344. guiCurveEditor.OnButtonUp(ev);
  1345. }
  1346. #endregion
  1347. #region General callbacks
  1348. /// <summary>
  1349. /// Triggered by the field selector, when user selects a new curve field.
  1350. /// </summary>
  1351. /// <param name="path">Path of the selected curve field.</param>
  1352. /// <param name="type">Type of the selected curve field (float, vector, etc.).</param>
  1353. private void OnFieldAdded(string path, SerializableProperty.FieldType type)
  1354. {
  1355. // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path)
  1356. string pathNoRoot = path.TrimStart('/');
  1357. int separatorIdx = pathNoRoot.IndexOf("/");
  1358. if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length)
  1359. return;
  1360. pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1);
  1361. AddNewField(pathNoRoot, type);
  1362. RecordState(pathNoRoot, 0.0f);
  1363. ApplyClipChanges();
  1364. }
  1365. /// <summary>
  1366. /// Triggered when the user selects a new curve field.
  1367. /// </summary>
  1368. /// <param name="path">Path of the selected curve field.</param>
  1369. private void OnFieldSelected(string path)
  1370. {
  1371. bool additive = Input.IsButtonHeld(ButtonCode.LeftShift) || Input.IsButtonHeld(ButtonCode.RightShift);
  1372. SelectField(path, additive);
  1373. }
  1374. /// <summary>
  1375. /// Triggered when the user selects a new scene object or a resource.
  1376. /// </summary>
  1377. /// <param name="sceneObjects">Newly selected scene objects.</param>
  1378. /// <param name="resourcePaths">Newly selected resources.</param>
  1379. private void OnSelectionChanged(SceneObject[] sceneObjects, string[] resourcePaths)
  1380. {
  1381. // While recording allow other objects to be selected so the user can modify them
  1382. if (state == State.Recording)
  1383. return;
  1384. UpdateSelectedSO(false);
  1385. }
  1386. /// <summary>
  1387. /// Triggered when the user selects a new frame in the curve display.
  1388. /// </summary>
  1389. /// <param name="frameIdx">Index of the selected frame.</param>
  1390. private void OnFrameSelected(int frameIdx)
  1391. {
  1392. SetCurrentFrame(frameIdx);
  1393. PreviewFrame(currentFrameIdx);
  1394. // HACK: Skip checking for record changes this frame, to give the preview a chance to update, otherwise
  1395. // the changes would be detected any time a frame is delayed. A proper fix for this would be to force the
  1396. // animation to be evaluated synchronously when PreviewFrame is called.
  1397. delayRecord = true;
  1398. }
  1399. /// <summary>
  1400. /// Triggered when the user changed (add, removed or modified) animation events in the curve display.
  1401. /// </summary>
  1402. private void OnEventsChanged()
  1403. {
  1404. clipInfo.events = guiCurveEditor.Events;
  1405. EditorApplication.SetProjectDirty();
  1406. }
  1407. #endregion
  1408. }
  1409. /// <summary>
  1410. /// Drop down window that displays options used by the animation window.
  1411. /// </summary>
  1412. [DefaultSize(100, 50)]
  1413. internal class AnimationOptions : DropDownWindow
  1414. {
  1415. /// <summary>
  1416. /// Initializes the drop down window by creating the necessary GUI. Must be called after construction and before
  1417. /// use.
  1418. /// </summary>
  1419. /// <param name="parent">Animation window that this drop down window is a part of.</param>
  1420. internal void Initialize(AnimationWindow parent)
  1421. {
  1422. GUIIntField fpsField = new GUIIntField(new LocEdString("FPS"), 40);
  1423. fpsField.Value = parent.FPS;
  1424. fpsField.OnChanged += x => { parent.FPS = x; };
  1425. GUILayoutY vertLayout = GUI.AddLayoutY();
  1426. vertLayout.AddFlexibleSpace();
  1427. GUILayoutX contentLayout = vertLayout.AddLayoutX();
  1428. contentLayout.AddFlexibleSpace();
  1429. contentLayout.AddElement(fpsField);
  1430. contentLayout.AddFlexibleSpace();
  1431. vertLayout.AddFlexibleSpace();
  1432. }
  1433. }
  1434. /// <summary>
  1435. /// Raw data representing a single animation curve.
  1436. /// </summary>
  1437. [SerializeObject]
  1438. class AnimationCurveState
  1439. {
  1440. public KeyFrame[] keyFrames;
  1441. public TangentMode[] tangentModes;
  1442. }
  1443. /// <summary>
  1444. /// Raw data representing a single animation clip state.
  1445. /// </summary>
  1446. [SerializeObject]
  1447. class AnimationClipState
  1448. {
  1449. public Dictionary<string, AnimationCurveState[]> curves = new Dictionary<string, AnimationCurveState[]>();
  1450. public AnimationEvent[] events;
  1451. }
  1452. /// <summary>
  1453. /// Undo command used in the AnimationWindow.
  1454. /// </summary>
  1455. [SerializeObject]
  1456. internal class AnimationUndo : UndoableCommand
  1457. {
  1458. private AnimationClipState prevClipState;
  1459. private AnimationClipState clipState;
  1460. public AnimationUndo(AnimationClipState prevClipState, AnimationClipState clipState)
  1461. {
  1462. this.prevClipState = prevClipState;
  1463. this.clipState = clipState;
  1464. }
  1465. /// <inheritdoc/>
  1466. protected override void Commit()
  1467. {
  1468. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1469. window?.ApplyClipState(clipState);
  1470. }
  1471. /// <inheritdoc/>
  1472. protected override void Revert()
  1473. {
  1474. AnimationWindow window = EditorWindow.GetWindow<AnimationWindow>();
  1475. window?.ApplyClipState(prevClipState);
  1476. }
  1477. }
  1478. /** @} */
  1479. }