AnimationWindow.cs 63 KB

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