AnimationWindow.cs 63 KB

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