TransitionDrawer.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. #if UNITY_EDITOR && UNITY_IMGUI
  3. using Animancer.Editor.Previews;
  4. using Animancer.Units.Editor;
  5. using System;
  6. using System.Collections.Generic;
  7. using UnityEditor;
  8. using UnityEngine;
  9. namespace Animancer.Editor
  10. {
  11. /// <summary>[Editor-Only] Draws the Inspector GUI for an <see cref="ITransitionDetailed"/>.</summary>
  12. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/TransitionDrawer
  13. [CustomPropertyDrawer(typeof(ITransitionDetailed), true)]
  14. public class TransitionDrawer : PropertyDrawer,
  15. IPolymorphic
  16. {
  17. /************************************************************************************************************************/
  18. /// <summary>The visual state of a drawer.</summary>
  19. private enum Mode
  20. {
  21. Uninitialized,
  22. Normal,
  23. AlwaysExpanded,
  24. }
  25. /// <summary>The current state of this drawer.</summary>
  26. private Mode _Mode;
  27. /************************************************************************************************************************/
  28. /// <summary>
  29. /// If set, the field with this name will be drawn on the header line with the foldout arrow instead of in its
  30. /// regular place.
  31. /// </summary>
  32. protected readonly string MainPropertyName;
  33. /// <summary>"." + <see cref="MainPropertyName"/> (to avoid creating garbage repeatedly).</summary>
  34. protected readonly string MainPropertyPathSuffix;
  35. /************************************************************************************************************************/
  36. /// <summary>Creates a new <see cref="TransitionDrawer"/>.</summary>
  37. public TransitionDrawer() { }
  38. /// <summary>Creates a new <see cref="TransitionDrawer"/> and sets the <see cref="MainPropertyName"/>.</summary>
  39. public TransitionDrawer(string mainPropertyName)
  40. {
  41. MainPropertyName = mainPropertyName;
  42. MainPropertyPathSuffix = "." + mainPropertyName;
  43. }
  44. /************************************************************************************************************************/
  45. /// <summary>Returns the property specified by the <see cref="MainPropertyName"/>.</summary>
  46. private SerializedProperty GetMainProperty(SerializedProperty rootProperty)
  47. => MainPropertyName == null
  48. ? null
  49. : rootProperty.FindPropertyRelative(MainPropertyName);
  50. /************************************************************************************************************************/
  51. /// <summary>Returns the number of vertical pixels the `property` will occupy when it is drawn.</summary>
  52. public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
  53. {
  54. using (new DrawerContext(property))
  55. {
  56. InitializeMode(property);
  57. var height = EditorGUI.GetPropertyHeight(property, label, true);
  58. if (property.isExpanded)
  59. {
  60. if (property.propertyType != SerializedPropertyType.ManagedReference)
  61. {
  62. var mainProperty = GetMainProperty(property);
  63. if (mainProperty != null)
  64. height -= EditorGUI.GetPropertyHeight(mainProperty) + AnimancerGUI.StandardSpacing;
  65. }
  66. // The End Time from the Event Sequence is drawn out in the main transition so we need to add it.
  67. // But rather than figuring out which array element actually holds the end time, we just use the
  68. // Start Time field since it will have the same height.
  69. var startTime = property.FindPropertyRelative(NormalizedStartTimeFieldName);
  70. if (startTime != null)
  71. height += EditorGUI.GetPropertyHeight(startTime) + AnimancerGUI.StandardSpacing;
  72. }
  73. return height;
  74. }
  75. }
  76. /************************************************************************************************************************/
  77. /// <summary>Draws the root `property` GUI and calls <see cref="DoChildPropertyGUI"/> for each of its children.</summary>
  78. public override void OnGUI(Rect area, SerializedProperty property, GUIContent label)
  79. {
  80. InitializeMode(property);
  81. // Highlight the whole area if this transition is currently being previewed.
  82. var isPreviewing = TransitionPreviewWindow.IsPreviewing(property);
  83. if (isPreviewing)
  84. {
  85. var highlightArea = area;
  86. highlightArea.xMin -= AnimancerGUI.IndentSize;
  87. EditorGUI.DrawRect(highlightArea, new(0.35f, 0.5f, 1, 0.2f));
  88. }
  89. if (property.propertyType == SerializedPropertyType.ObjectReference)
  90. {
  91. DoObjectReferenceGUI(area, property, label);
  92. return;
  93. }
  94. var headerArea = area;
  95. if (property.propertyType == SerializedPropertyType.ManagedReference)
  96. DoPreviewButtonGUI(ref headerArea, property, isPreviewing);
  97. using (new TypeSelectionButton(headerArea, property, true))
  98. {
  99. DoPropertyGUI(area, property, label, isPreviewing);
  100. }
  101. }
  102. /************************************************************************************************************************/
  103. private readonly CachedEditor NestedEditor = new();
  104. private static GUIStyle _NestAreaStyle;
  105. private void DoObjectReferenceGUI(Rect area, SerializedProperty property, GUIContent label)
  106. {
  107. EditorGUI.PropertyField(area, property, label, property.isExpanded);
  108. if (property.hasMultipleDifferentValues)
  109. return;
  110. var value = property.objectReferenceValue;
  111. if (value == null)
  112. return;
  113. property.isExpanded = EditorGUI.Foldout(area, property.isExpanded, GUIContent.none, true);
  114. if (!property.isExpanded)
  115. return;
  116. const float NegativePadding = 4;
  117. EditorGUIUtility.labelWidth -= NegativePadding;
  118. if (_NestAreaStyle == null)
  119. {
  120. _NestAreaStyle = new GUIStyle(GUI.skin.box);
  121. var rect = _NestAreaStyle.margin;
  122. rect.bottom = rect.top = 0;
  123. _NestAreaStyle.margin = rect;
  124. }
  125. EditorGUI.indentLevel++;
  126. GUILayout.BeginVertical(_NestAreaStyle);
  127. try
  128. {
  129. NestedEditor.GetEditor(value).OnInspectorGUI();
  130. }
  131. catch (ExitGUIException)
  132. {
  133. }
  134. catch (Exception exception)
  135. {
  136. Debug.LogException(exception);
  137. }
  138. GUILayout.EndVertical();
  139. EditorGUI.indentLevel--;
  140. EditorGUIUtility.labelWidth += NegativePadding;
  141. }
  142. /************************************************************************************************************************/
  143. private void DoPropertyGUI(Rect area, SerializedProperty property, GUIContent label, bool isPreviewing)
  144. {
  145. using (new DrawerContext(property))
  146. {
  147. var indent = !string.IsNullOrEmpty(label.text);
  148. EditorGUI.BeginChangeCheck();
  149. var mainProperty = GetMainProperty(property);
  150. DoHeaderGUI(ref area, property, mainProperty, label, isPreviewing);
  151. DoChildPropertiesGUI(area, property, mainProperty, indent);
  152. if (EditorGUI.EndChangeCheck() && isPreviewing)
  153. TransitionPreviewWindow.PreviewNormalizedTime = TransitionPreviewWindow.PreviewNormalizedTime;
  154. }
  155. }
  156. /************************************************************************************************************************/
  157. /// <summary>
  158. /// If the <see cref="_Mode"/> is <see cref="Mode.Uninitialized"/>, this method determines how it should start
  159. /// based on the number of properties in the `serializedObject`. If the only serialized field is an
  160. /// <see cref="ITransition"/> then it should start expanded.
  161. /// </summary>
  162. protected void InitializeMode(SerializedProperty property)
  163. {
  164. if (_Mode == Mode.Uninitialized)
  165. {
  166. if (property.depth > 0)
  167. {
  168. _Mode = Mode.Normal;
  169. return;
  170. }
  171. _Mode = Mode.AlwaysExpanded;
  172. var iterator = property.serializedObject.GetIterator();
  173. iterator.Next(true);
  174. var count = 0;
  175. do
  176. {
  177. switch (iterator.propertyPath)
  178. {
  179. // Ignore MonoBehaviour inherited fields.
  180. case "m_ObjectHideFlags":
  181. case "m_Script":
  182. break;
  183. default:
  184. count++;
  185. if (count > 1)
  186. {
  187. _Mode = Mode.Normal;
  188. return;
  189. }
  190. break;
  191. }
  192. }
  193. while (iterator.NextVisible(false));
  194. }
  195. if (_Mode == Mode.AlwaysExpanded)
  196. property.isExpanded = true;
  197. }
  198. /************************************************************************************************************************/
  199. /// <summary>Draws the root property of a transition with an optional main property on the same line.</summary>
  200. protected virtual void DoHeaderGUI(
  201. ref Rect area,
  202. SerializedProperty rootProperty,
  203. SerializedProperty mainProperty,
  204. GUIContent label,
  205. bool isPreviewing)
  206. {
  207. area.height = AnimancerGUI.LineHeight;
  208. var labelArea = area;
  209. AnimancerGUI.NextVerticalArea(ref area);
  210. if (rootProperty.propertyType != SerializedPropertyType.ManagedReference)
  211. DoPreviewButtonGUI(ref labelArea, rootProperty, isPreviewing);
  212. // Draw the Root Property after the Main Property to give better spacing between the label and field.
  213. // Drawing the main property might assign its details to the label so we keep our own copy.
  214. using (var rootLabel = PooledGUIContent.Acquire(label.text, label.tooltip))
  215. {
  216. // Main Property.
  217. DoMainPropertyGUI(labelArea, out labelArea, rootProperty, mainProperty);
  218. // Root Property.
  219. var propertyLabel = EditorGUI.BeginProperty(labelArea, rootLabel, rootProperty);
  220. EditorGUI.LabelField(labelArea, propertyLabel);
  221. EditorGUI.EndProperty();
  222. if (_Mode != Mode.AlwaysExpanded)
  223. {
  224. var hierarchyMode = EditorGUIUtility.hierarchyMode;
  225. EditorGUIUtility.hierarchyMode = true;
  226. rootProperty.isExpanded =
  227. EditorGUI.Foldout(labelArea, rootProperty.isExpanded, GUIContent.none, true);
  228. EditorGUIUtility.hierarchyMode = hierarchyMode;
  229. }
  230. }
  231. }
  232. /************************************************************************************************************************/
  233. /// <summary>Draws the GUI the the target transition's main property.</summary>
  234. protected virtual void DoMainPropertyGUI(
  235. Rect area,
  236. out Rect labelArea,
  237. SerializedProperty rootProperty,
  238. SerializedProperty mainProperty)
  239. {
  240. labelArea = area;
  241. if (mainProperty == null)
  242. return;
  243. var fullArea = area;
  244. labelArea = AnimancerGUI.StealFromLeft(
  245. ref area,
  246. EditorGUIUtility.labelWidth,
  247. AnimancerGUI.StandardSpacing);
  248. var mainPropertyReferenceIsMissing =
  249. mainProperty.propertyType == SerializedPropertyType.ObjectReference &&
  250. mainProperty.objectReferenceValue == null;
  251. var hierarchyMode = EditorGUIUtility.hierarchyMode;
  252. EditorGUIUtility.hierarchyMode = true;
  253. if (rootProperty.propertyType == SerializedPropertyType.ManagedReference)
  254. {
  255. if (rootProperty.isExpanded ||
  256. _Mode == Mode.AlwaysExpanded)
  257. {
  258. EditorGUI.indentLevel++;
  259. AnimancerGUI.NextVerticalArea(ref fullArea);
  260. using (var label = PooledGUIContent.Acquire(mainProperty))
  261. EditorGUI.PropertyField(fullArea, mainProperty, label, true);
  262. EditorGUI.indentLevel--;
  263. }
  264. }
  265. else
  266. {
  267. var indentLevel = EditorGUI.indentLevel;
  268. EditorGUI.indentLevel = 0;
  269. EditorGUI.PropertyField(area, mainProperty, GUIContent.none, true);
  270. EditorGUI.indentLevel = indentLevel;
  271. }
  272. EditorGUIUtility.hierarchyMode = hierarchyMode;
  273. // If the main Object reference was just assigned and all fields were at their type default,
  274. // reset the value to run its default constructor and field initializers then reassign the reference.
  275. var reference = mainProperty.objectReferenceValue;
  276. if (mainPropertyReferenceIsMissing && reference != null)
  277. {
  278. mainProperty.objectReferenceValue = null;
  279. if (Serialization.IsDefaultValueByType(rootProperty))
  280. rootProperty.GetAccessor().ResetValue(rootProperty);
  281. mainProperty.objectReferenceValue = reference;
  282. }
  283. }
  284. /************************************************************************************************************************/
  285. /// <summary>Draws a small button using the <see cref="TransitionPreviewWindow.Icon"/>.</summary>
  286. private static void DoPreviewButtonGUI(ref Rect area, SerializedProperty property, bool isPreviewing)
  287. {
  288. if (property.serializedObject.targetObjects.Length != 1 ||
  289. !TransitionPreviewWindow.CanBePreviewed(property))
  290. return;
  291. var enabled = GUI.enabled;
  292. var currentEvent = Event.current;
  293. if (currentEvent.button == 1)// Ignore Right Clicks on the Preview Button.
  294. {
  295. switch (currentEvent.type)
  296. {
  297. case EventType.MouseDown:
  298. case EventType.MouseUp:
  299. case EventType.ContextClick:
  300. GUI.enabled = false;
  301. break;
  302. }
  303. }
  304. var tooltip = isPreviewing ? TransitionPreviewWindow.Inspector.CloseTooltip : "Preview this transition";
  305. if (DoPreviewButtonGUI(ref area, isPreviewing, tooltip))
  306. TransitionPreviewWindow.OpenOrClose(property);
  307. GUI.enabled = enabled;
  308. }
  309. /// <summary>Draws a small button using the <see cref="TransitionPreviewWindow.Icon"/>.</summary>
  310. public static bool DoPreviewButtonGUI(ref Rect area, bool selected, string tooltip)
  311. {
  312. var width = AnimancerGUI.LineHeight + AnimancerGUI.StandardSpacing * 2;
  313. var buttonArea = AnimancerGUI.StealFromRight(ref area, width, AnimancerGUI.StandardSpacing);
  314. buttonArea.height = AnimancerGUI.LineHeight;
  315. using (var content = PooledGUIContent.Acquire("", tooltip))
  316. {
  317. content.image = TransitionPreviewWindow.Icon;
  318. return GUI.Toggle(buttonArea, selected, content, PreviewButtonStyle) != selected;
  319. }
  320. }
  321. /************************************************************************************************************************/
  322. private static GUIStyle _PreviewButtonStyle;
  323. /// <summary>The style used for the button that opens the <see cref="TransitionPreviewWindow"/>.</summary>
  324. public static GUIStyle PreviewButtonStyle
  325. => _PreviewButtonStyle ??= new(AnimancerGUI.MiniButtonStyle)
  326. {
  327. padding = new(0, 0, 0, 1),
  328. fixedWidth = 0,
  329. fixedHeight = 0,
  330. };
  331. /************************************************************************************************************************/
  332. private void DoChildPropertiesGUI(Rect area, SerializedProperty rootProperty, SerializedProperty mainProperty, bool indent)
  333. {
  334. if (!rootProperty.isExpanded && _Mode != Mode.AlwaysExpanded)
  335. return;
  336. // Skip over the main property if it was already drawn by the header.
  337. if (rootProperty.propertyType == SerializedPropertyType.ManagedReference &&
  338. mainProperty != null)
  339. AnimancerGUI.NextVerticalArea(ref area);
  340. if (indent)
  341. EditorGUI.indentLevel++;
  342. var property = rootProperty.Copy();
  343. SerializedProperty eventsProperty = null;
  344. var depth = property.depth;
  345. if (property.NextVisible(true))
  346. {
  347. while (property.depth > depth)
  348. {
  349. // Grab the Events property and draw it last.
  350. var path = property.propertyPath;
  351. if (eventsProperty == null && path.EndsWith("._Events"))
  352. {
  353. eventsProperty = property.Copy();
  354. }
  355. // Don't draw the main property again.
  356. else if (mainProperty != null && path.EndsWith(MainPropertyPathSuffix))
  357. {
  358. }
  359. else
  360. {
  361. if (eventsProperty != null)
  362. {
  363. var type = Context.Transition.GetType();
  364. var accessor = property.GetAccessor();
  365. var field = Serialization.GetField(type, accessor.Name);
  366. if (field != null && field.IsDefined(typeof(DrawAfterEventsAttribute), false))
  367. {
  368. using (var eventsLabel = PooledGUIContent.Acquire(eventsProperty))
  369. DoChildPropertyGUI(ref area, rootProperty, eventsProperty, eventsLabel);
  370. AnimancerGUI.NextVerticalArea(ref area);
  371. eventsProperty = null;
  372. }
  373. }
  374. using (var label = PooledGUIContent.Acquire(property))
  375. DoChildPropertyGUI(ref area, rootProperty, property, label);
  376. AnimancerGUI.NextVerticalArea(ref area);
  377. }
  378. if (!property.NextVisible(false))
  379. break;
  380. }
  381. }
  382. if (eventsProperty != null)
  383. {
  384. using (var label = PooledGUIContent.Acquire(eventsProperty))
  385. DoChildPropertyGUI(ref area, rootProperty, eventsProperty, label);
  386. }
  387. if (indent)
  388. EditorGUI.indentLevel--;
  389. }
  390. /************************************************************************************************************************/
  391. /// <summary>
  392. /// Draws the `property` GUI in relation to the `rootProperty` which was passed into <see cref="OnGUI"/>.
  393. /// </summary>
  394. protected virtual void DoChildPropertyGUI(
  395. ref Rect area,
  396. SerializedProperty rootProperty,
  397. SerializedProperty property,
  398. GUIContent label)
  399. {
  400. // If we keep using the GUIContent that was passed into OnGUI then GetPropertyHeight will change it to
  401. // match the 'property' which we don't want.
  402. using (var content = PooledGUIContent.Acquire(label.text, label.tooltip))
  403. {
  404. area.height = EditorGUI.GetPropertyHeight(property, content, true);
  405. if (TryDoStartTimeField(ref area, rootProperty, property, content))
  406. return;
  407. EditorGUI.PropertyField(area, property, content, true);
  408. }
  409. }
  410. /************************************************************************************************************************/
  411. /// <summary>The name of the backing field of <c>ClipTransition.NormalizedStartTime</c>.</summary>
  412. public const string NormalizedStartTimeFieldName = "_NormalizedStartTime";
  413. /// <summary>
  414. /// If the `property` is a "Start Time" field, this method draws it as well as the "End Time" below it and
  415. /// returns true.
  416. /// </summary>
  417. public static bool TryDoStartTimeField(
  418. ref Rect area,
  419. SerializedProperty rootProperty,
  420. SerializedProperty property,
  421. GUIContent label)
  422. {
  423. if (!property.propertyPath.EndsWith("." + NormalizedStartTimeFieldName))
  424. return false;
  425. // Start Time.
  426. label.text = "Start Time";
  427. AnimationTimeAttributeDrawer.NextDefaultValue =
  428. AnimancerEvent.Sequence.GetDefaultNormalizedStartTime(Context.Transition.Speed);
  429. EditorGUI.PropertyField(area, property, label, false);
  430. AnimancerGUI.NextVerticalArea(ref area);
  431. // End Time.
  432. var events = rootProperty.FindPropertyRelative("_Events");
  433. using (var context = SerializableEventSequenceDrawer.Context.Get(events))
  434. {
  435. var areaCopy = area;
  436. var index = Mathf.Max(0, context.Times.Count - 1);
  437. SerializableEventSequenceDrawer.DoTimeGUI(ref areaCopy, context, index, true);
  438. }
  439. return true;
  440. }
  441. /************************************************************************************************************************/
  442. #region Context
  443. /************************************************************************************************************************/
  444. /// <summary>The current <see cref="DrawerContext"/>.</summary>
  445. public static DrawerContext Context { get; private set; }
  446. /************************************************************************************************************************/
  447. /// <summary>Details used to draw an <see cref="ITransition"/>.</summary>
  448. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/DrawerContext
  449. public readonly struct DrawerContext : IDisposable
  450. {
  451. /************************************************************************************************************************/
  452. /// <summary>The stack of active contexts.</summary>
  453. public static readonly List<DrawerContext> Stack = new();
  454. /************************************************************************************************************************/
  455. /// <summary>The main property representing the <see cref="ITransition"/> field.</summary>
  456. public readonly SerializedProperty Property;
  457. /// <summary>The actual transition object rerieved from the <see cref="Property"/>.</summary>
  458. public readonly ITransitionDetailed Transition;
  459. /// <summary>The cached value of <see cref="ITransitionDetailed.MaximumDuration"/>.</summary>
  460. public readonly float MaximumDuration;
  461. /************************************************************************************************************************/
  462. /// <summary>Creates a new <see cref="DrawerContext"/>.</summary>
  463. /// <remarks>Be sure to <see cref="Dispose"/> it when done.</remarks>
  464. public DrawerContext(
  465. SerializedProperty transitionProperty)
  466. {
  467. Property = transitionProperty;
  468. Transition = transitionProperty.GetValue<ITransitionDetailed>();
  469. AnimancerUtilities.TryGetLength(Transition, out MaximumDuration);
  470. EditorGUI.BeginChangeCheck();
  471. Stack.Add(this);
  472. Context = this;
  473. }
  474. /************************************************************************************************************************/
  475. /// <summary>Applies any modified properties and decrements the stack.</summary>
  476. public void Dispose()
  477. {
  478. Debug.Assert(
  479. Transition == Context.Transition,
  480. $"{nameof(DrawerContext)}.{nameof(Dispose)}" +
  481. $" must be called in the reverse order in which instances were created." +
  482. $" Recommended: using (new DrawerContext(property)) to ensure correct disposal.");
  483. if (EditorGUI.EndChangeCheck())
  484. Property.serializedObject.ApplyModifiedProperties();
  485. Stack.RemoveAt(Stack.Count - 1);
  486. Context = Stack.Count > 0
  487. ? Stack[^1]
  488. : default;
  489. }
  490. /************************************************************************************************************************/
  491. }
  492. /************************************************************************************************************************/
  493. #endregion
  494. /************************************************************************************************************************/
  495. }
  496. }
  497. #endif