TransitionDrawer.cs 24 KB

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