SoloAnimation.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. using Animancer.Units;
  3. using System;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.Animations;
  7. using UnityEngine.Playables;
  8. namespace Animancer
  9. {
  10. /// <summary>Plays a single <see cref="AnimationClip"/>.</summary>
  11. /// <remarks>
  12. /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/playing/component-types">Component Types</see>
  13. /// </remarks>
  14. /// <example>
  15. /// <see href="https://kybernetik.com.au/animancer/docs/examples/fine-control/solo-animation">Solo Animation</see>
  16. /// </example>
  17. /// https://kybernetik.com.au/animancer/api/Animancer/SoloAnimation
  18. ///
  19. [AddComponentMenu(Strings.MenuPrefix + "Solo Animation")]
  20. [DefaultExecutionOrder(DefaultExecutionOrder)]
  21. [HelpURL(Strings.DocsURLs.APIDocumentation + "/" + nameof(SoloAnimation))]
  22. public class SoloAnimation : MonoBehaviour, IAnimationClipSource
  23. {
  24. /************************************************************************************************************************/
  25. #region Fields and Properties
  26. /************************************************************************************************************************/
  27. /// <summary>Initialize before anything else tries to use this component.</summary>
  28. public const int DefaultExecutionOrder = -5000;
  29. /************************************************************************************************************************/
  30. [SerializeField, Tooltip("The Animator component which this script controls")]
  31. private Animator _Animator;
  32. /// <summary>[<see cref="SerializeField"/>]
  33. /// The <see cref="UnityEngine.Animator"/> component which this script controls.
  34. /// </summary>
  35. /// <remarks>
  36. /// If you need to set this value at runtime you are likely better off using a proper
  37. /// <see cref="AnimancerComponent"/>.
  38. /// </remarks>
  39. public Animator Animator
  40. {
  41. get => _Animator;
  42. set
  43. {
  44. _Animator = value;
  45. if (IsInitialized)
  46. Play();
  47. }
  48. }
  49. /************************************************************************************************************************/
  50. [SerializeField, Tooltip("The animation that will be played")]
  51. private AnimationClip _Clip;
  52. /// <summary>[<see cref="SerializeField"/>] The <see cref="AnimationClip"/> that will be played.</summary>
  53. /// <remarks>
  54. /// If you need to set this value at runtime you are likely better off using a proper
  55. /// <see cref="AnimancerComponent"/>.
  56. /// </remarks>
  57. public AnimationClip Clip
  58. {
  59. get => _Clip;
  60. set
  61. {
  62. _Clip = value;
  63. if (IsInitialized)
  64. Play();
  65. }
  66. }
  67. /************************************************************************************************************************/
  68. /// <summary>
  69. /// If true, disabling this object will stop and rewind the animation. Otherwise it will simply be paused
  70. /// and will resume from its current state when it is re-enabled.
  71. /// </summary>
  72. /// <remarks>
  73. /// The default value is true.
  74. /// <para></para>
  75. /// This property wraps <see cref="Animator.keepAnimatorControllerStateOnDisable"/> and inverts its value.
  76. /// The value is serialized by the <see cref="UnityEngine.Animator"/>.
  77. /// </remarks>
  78. public bool StopOnDisable
  79. {
  80. get => !_Animator.keepAnimatorControllerStateOnDisable;
  81. set => _Animator.keepAnimatorControllerStateOnDisable = !value;
  82. }
  83. /************************************************************************************************************************/
  84. /// <summary>The <see cref="PlayableGraph"/> being used to play the <see cref="Clip"/>.</summary>
  85. private PlayableGraph _Graph;
  86. /// <summary>The <see cref="AnimationClipPlayable"/> being used to play the <see cref="Clip"/>.</summary>
  87. private AnimationClipPlayable _Playable;
  88. /************************************************************************************************************************/
  89. private bool _IsPlaying;
  90. /// <summary>Is the animation playing (true) or paused (false)?</summary>
  91. public bool IsPlaying
  92. {
  93. get => _IsPlaying;
  94. set
  95. {
  96. _IsPlaying = value;
  97. if (value)
  98. {
  99. if (!IsInitialized)
  100. Play();
  101. else
  102. _Graph.Play();
  103. }
  104. else
  105. {
  106. if (IsInitialized)
  107. _Graph.Stop();
  108. }
  109. }
  110. }
  111. /************************************************************************************************************************/
  112. [SerializeField, Multiplier, Tooltip("The speed at which the animation plays (default 1)")]
  113. private float _Speed = 1;
  114. /// <summary>[<see cref="SerializeField"/>] The speed at which the animation is playing (default 1).</summary>
  115. /// <exception cref="ArgumentException">This component is not yet <see cref="IsInitialized"/>.</exception>
  116. public float Speed
  117. {
  118. get => _Speed;
  119. set
  120. {
  121. _Speed = value;
  122. _Playable.SetSpeed(value);
  123. IsPlaying = value != 0;
  124. }
  125. }
  126. /************************************************************************************************************************/
  127. [SerializeField, Tooltip("Determines whether Foot IK will be applied to the model (if it is Humanoid)")]
  128. private bool _FootIK;
  129. /// <summary>[<see cref="SerializeField"/>] Should Foot IK will be applied to the model (if it is Humanoid)?</summary>
  130. /// <remarks>
  131. /// The developers of Unity have stated that they believe it looks better with this enabled, but more often
  132. /// than not it just makes the legs end up in a slightly different pose to what the animator intended.
  133. /// </remarks>
  134. /// <exception cref="ArgumentException">This component is not yet <see cref="IsInitialized"/>.</exception>
  135. public bool FootIK
  136. {
  137. get => _FootIK;
  138. set
  139. {
  140. _FootIK = value;
  141. _Playable.SetApplyFootIK(value);
  142. }
  143. }
  144. /************************************************************************************************************************/
  145. /// <summary>The number of seconds that have passed since the start of the animation.</summary>
  146. /// <exception cref="ArgumentException">This component is not yet <see cref="IsInitialized"/>.</exception>
  147. public float Time
  148. {
  149. get => (float)_Playable.GetTime();
  150. set
  151. {
  152. // We need to call SetTime twice to ensure that animation events aren't triggered incorrectly.
  153. _Playable.SetTime(value);
  154. _Playable.SetTime(value);
  155. IsPlaying = true;
  156. }
  157. }
  158. /// <summary>
  159. /// The <see cref="Time"/> of this state as a portion of the <see cref="AnimationClip.length"/>, meaning the
  160. /// value goes from 0 to 1 as it plays from start to end, regardless of how long that actually takes.
  161. /// </summary>
  162. /// <remarks>
  163. /// This value will continue increasing after the animation passes the end of its length and it will either
  164. /// freeze in place or start again from the beginning according to whether it is looping or not.
  165. /// <para></para>
  166. /// The fractional part of the value (<c>NormalizedTime % 1</c>) is the percentage (0-1) of progress in the
  167. /// current loop while the integer part (<c>(int)NormalizedTime</c>) is the number of times the animation has
  168. /// been looped.
  169. /// </remarks>
  170. /// <exception cref="ArgumentException">This component is not yet <see cref="IsInitialized"/>.</exception>
  171. public float NormalizedTime
  172. {
  173. get => Time / _Clip.length;
  174. set => Time = value * _Clip.length;
  175. }
  176. /************************************************************************************************************************/
  177. /// <summary>Indicates whether the <see cref="PlayableGraph"/> is valid.</summary>
  178. public bool IsInitialized => _Graph.IsValid();
  179. /************************************************************************************************************************/
  180. #endregion
  181. /************************************************************************************************************************/
  182. #if UNITY_EDITOR
  183. /************************************************************************************************************************/
  184. [SerializeField, Tooltip("Should the " + nameof(Clip) + " be automatically applied to the object in Edit Mode?")]
  185. private bool _ApplyInEditMode;
  186. /// <summary>[Editor-Only] Should the <see cref="Clip"/> be automatically applied to the object in Edit Mode?</summary>
  187. public ref bool ApplyInEditMode => ref _ApplyInEditMode;
  188. /************************************************************************************************************************/
  189. /// <summary>[Editor-Only]
  190. /// Tries to find an <see cref="UnityEngine.Animator"/> component on this <see cref="GameObject"/> or its
  191. /// children or parents (in that order).
  192. /// </summary>
  193. /// <remarks>
  194. /// Called by the Unity Editor when this component is first added (in Edit Mode) and whenever the Reset command
  195. /// is executed from its context menu.
  196. /// </remarks>
  197. protected virtual void Reset()
  198. {
  199. gameObject.GetComponentInParentOrChildren(ref _Animator);
  200. }
  201. /************************************************************************************************************************/
  202. /// <summary>[Editor-Only]
  203. /// Applies the <see cref="Speed"/>, <see cref="FootIK"/>, and <see cref="ApplyInEditMode"/>.
  204. /// </summary>
  205. /// <remarks>Called in Edit Mode whenever this script is loaded or a value is changed in the Inspector.</remarks>
  206. protected virtual void OnValidate()
  207. {
  208. if (IsInitialized)
  209. {
  210. Speed = Speed;
  211. FootIK = FootIK;
  212. }
  213. else if (_ApplyInEditMode && enabled)
  214. {
  215. _Clip.EditModeSampleAnimation(_Animator);
  216. }
  217. }
  218. /************************************************************************************************************************/
  219. #endif
  220. /************************************************************************************************************************/
  221. /// <summary>Plays the <see cref="Clip"/>.</summary>
  222. public void Play() => Play(_Clip);
  223. /// <summary>Plays the `clip`.</summary>
  224. public void Play(AnimationClip clip)
  225. {
  226. if (clip == null || _Animator == null)
  227. return;
  228. if (_Graph.IsValid())
  229. _Graph.Destroy();
  230. _Playable = AnimationPlayableUtilities.PlayClip(_Animator, clip, out _Graph);
  231. _Playable.SetSpeed(_Speed);
  232. if (!_FootIK)
  233. _Playable.SetApplyFootIK(false);
  234. if (!clip.isLooping)
  235. _Playable.SetDuration(clip.length);
  236. _IsPlaying = true;
  237. }
  238. /************************************************************************************************************************/
  239. /// <summary>Plays the <see cref="Clip"/> on the target <see cref="Animator"/>.</summary>
  240. protected virtual void OnEnable()
  241. {
  242. IsPlaying = true;
  243. }
  244. /************************************************************************************************************************/
  245. /// <summary>
  246. /// Checks if the animation is done so it can pause the <see cref="PlayableGraph"/> to improve performance.
  247. /// </summary>
  248. protected virtual void Update()
  249. {
  250. if (!IsPlaying)
  251. return;
  252. if (_Graph.IsDone())
  253. {
  254. IsPlaying = false;
  255. }
  256. else if (_Speed < 0 && Time <= 0)
  257. {
  258. IsPlaying = false;
  259. Time = 0;
  260. }
  261. }
  262. /************************************************************************************************************************/
  263. /// <summary>Ensures that the <see cref="_Graph"/> is properly cleaned up.</summary>
  264. protected virtual void OnDisable()
  265. {
  266. IsPlaying = false;
  267. if (IsInitialized && StopOnDisable)
  268. {
  269. // Call SetTime twice to ensure that animation events aren't triggered incorrectly.
  270. _Playable.SetTime(0);
  271. _Playable.SetTime(0);
  272. }
  273. }
  274. /************************************************************************************************************************/
  275. /// <summary>Ensures that the <see cref="PlayableGraph"/> is properly cleaned up.</summary>
  276. protected virtual void OnDestroy()
  277. {
  278. if (IsInitialized)
  279. _Graph.Destroy();
  280. }
  281. /************************************************************************************************************************/
  282. #if UNITY_EDITOR
  283. /// <summary>[Editor-Only] Ensures that the <see cref="PlayableGraph"/> is destroyed.</summary>
  284. ~SoloAnimation()
  285. {
  286. UnityEditor.EditorApplication.delayCall += OnDestroy;
  287. }
  288. #endif
  289. /************************************************************************************************************************/
  290. /// <summary>[<see cref="IAnimationClipSource"/>] Adds the <see cref="Clip"/> to the list.</summary>
  291. public void GetAnimationClips(List<AnimationClip> clips)
  292. {
  293. if (_Clip != null)
  294. clips.Add(_Clip);
  295. }
  296. /************************************************************************************************************************/
  297. }
  298. }
  299. /************************************************************************************************************************/
  300. #if UNITY_EDITOR
  301. /************************************************************************************************************************/
  302. namespace Animancer.Editor
  303. {
  304. /// <summary>[Editor-Only] A custom Inspector for <see cref="SoloAnimation"/>.</summary>
  305. /// https://kybernetik.com.au/animancer/api/Animancer.Editor/SoloAnimationEditor
  306. ///
  307. [UnityEditor.CustomEditor(typeof(SoloAnimation)), UnityEditor.CanEditMultipleObjects]
  308. public class SoloAnimationEditor : UnityEditor.Editor
  309. {
  310. /************************************************************************************************************************/
  311. /// <summary>The animator referenced by each target.</summary>
  312. [NonSerialized]
  313. private Animator[] _Animators;
  314. /// <summary>A <see cref="UnityEditor.SerializedObject"/> encapsulating the <see cref="_Animators"/>.</summary>
  315. [NonSerialized]
  316. private UnityEditor.SerializedObject _SerializedAnimator;
  317. /// <summary>The <see cref="Animator.keepAnimatorControllerStateOnDisable"/> property.</summary>
  318. [NonSerialized]
  319. private UnityEditor.SerializedProperty _KeepStateOnDisable;
  320. /************************************************************************************************************************/
  321. /// <inheritdoc/>
  322. public override void OnInspectorGUI()
  323. {
  324. DoSerializedFieldsGUI();
  325. RefreshSerializedAnimator();
  326. DoStopOnDisableGUI();
  327. DoRuntimeDetailsGUI();
  328. }
  329. /************************************************************************************************************************/
  330. /// <summary>Draws the target's serialized fields.</summary>
  331. private void DoSerializedFieldsGUI()
  332. {
  333. serializedObject.Update();
  334. var property = serializedObject.GetIterator();
  335. property.NextVisible(true);
  336. if (property.name != "m_Script")
  337. UnityEditor.EditorGUILayout.PropertyField(property, true);
  338. while (property.NextVisible(false))
  339. {
  340. UnityEditor.EditorGUILayout.PropertyField(property, true);
  341. }
  342. serializedObject.ApplyModifiedProperties();
  343. }
  344. /************************************************************************************************************************/
  345. /// <summary>Ensures that the cached references relating to the target's <see cref="Animator"/> are correct.</summary>
  346. private void RefreshSerializedAnimator()
  347. {
  348. var targets = this.targets;
  349. AnimancerUtilities.SetLength(ref _Animators, targets.Length);
  350. var dirty = false;
  351. var hasAll = true;
  352. for (int i = 0; i < _Animators.Length; i++)
  353. {
  354. var animator = (targets[i] as SoloAnimation).Animator;
  355. if (_Animators[i] != animator)
  356. {
  357. _Animators[i] = animator;
  358. dirty = true;
  359. }
  360. if (animator == null)
  361. hasAll = false;
  362. }
  363. if (!dirty)
  364. return;
  365. OnDisable();
  366. if (!hasAll)
  367. return;
  368. _SerializedAnimator = new UnityEditor.SerializedObject(_Animators);
  369. _KeepStateOnDisable = _SerializedAnimator.FindProperty("m_KeepAnimatorControllerStateOnDisable");
  370. }
  371. /************************************************************************************************************************/
  372. /// <summary>
  373. /// Draws a toggle inverted from the <see cref="Animator.keepAnimatorControllerStateOnDisable"/> field.
  374. /// </summary>
  375. private void DoStopOnDisableGUI()
  376. {
  377. var area = AnimancerGUI.LayoutSingleLineRect();
  378. using (ObjectPool.Disposable.AcquireContent(out var label, "Stop On Disable",
  379. "If true, disabling this object will stop and rewind all animations." +
  380. " Otherwise they will simply be paused and will resume from their current states when it is re-enabled."))
  381. {
  382. if (_KeepStateOnDisable != null)
  383. {
  384. _KeepStateOnDisable.serializedObject.Update();
  385. var content = UnityEditor.EditorGUI.BeginProperty(area, label, _KeepStateOnDisable);
  386. _KeepStateOnDisable.boolValue = !UnityEditor.EditorGUI.Toggle(area, content, !_KeepStateOnDisable.boolValue);
  387. UnityEditor.EditorGUI.EndProperty();
  388. _KeepStateOnDisable.serializedObject.ApplyModifiedProperties();
  389. }
  390. else
  391. {
  392. using (new UnityEditor.EditorGUI.DisabledScope(true))
  393. UnityEditor.EditorGUI.Toggle(area, label, false);
  394. }
  395. }
  396. }
  397. /************************************************************************************************************************/
  398. /// <summary>Draws the target's runtime details.</summary>
  399. private void DoRuntimeDetailsGUI()
  400. {
  401. if (!UnityEditor.EditorApplication.isPlaying ||
  402. targets.Length != 1)
  403. return;
  404. AnimancerGUI.BeginVerticalBox(GUI.skin.box);
  405. var target = (SoloAnimation)this.target;
  406. if (!target.IsInitialized)
  407. {
  408. GUILayout.Label("Not Initialized");
  409. }
  410. else
  411. {
  412. UnityEditor.EditorGUI.BeginChangeCheck();
  413. var isPlaying = UnityEditor.EditorGUILayout.Toggle("Is Playing", target.IsPlaying);
  414. if (UnityEditor.EditorGUI.EndChangeCheck())
  415. target.IsPlaying = isPlaying;
  416. UnityEditor.EditorGUI.BeginChangeCheck();
  417. var time = UnityEditor.EditorGUILayout.FloatField("Time", target.Time);
  418. if (UnityEditor.EditorGUI.EndChangeCheck())
  419. target.Time = time;
  420. time = AnimancerUtilities.Wrap01(target.NormalizedTime);
  421. if (time == 0 && target.Time != 0)
  422. time = 1;
  423. UnityEditor.EditorGUI.BeginChangeCheck();
  424. time = UnityEditor.EditorGUILayout.Slider("Normalized Time", time, 0, 1);
  425. if (UnityEditor.EditorGUI.EndChangeCheck())
  426. target.NormalizedTime = time;
  427. }
  428. AnimancerGUI.EndVerticalBox(GUI.skin.box);
  429. Repaint();
  430. }
  431. /************************************************************************************************************************/
  432. /// <summary>Cleans up cached references relating to the target's <see cref="Animator"/>.</summary>
  433. protected virtual void OnDisable()
  434. {
  435. if (_SerializedAnimator != null)
  436. {
  437. _SerializedAnimator.Dispose();
  438. _SerializedAnimator = null;
  439. _KeepStateOnDisable = null;
  440. }
  441. }
  442. /************************************************************************************************************************/
  443. }
  444. }
  445. /************************************************************************************************************************/
  446. #endif
  447. /************************************************************************************************************************/