AnimancerNode.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using UnityEngine;
  7. using UnityEngine.Playables;
  8. using Object = UnityEngine.Object;
  9. namespace Animancer
  10. {
  11. /// <summary>Base class for <see cref="Playable"/> wrapper objects in an <see cref="AnimancerPlayable"/>.</summary>
  12. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerNode
  13. ///
  14. public abstract class AnimancerNode : Key, IUpdatable, IEnumerable<AnimancerState>, IEnumerator, IPlayableWrapper
  15. {
  16. /************************************************************************************************************************/
  17. #region Playable
  18. /************************************************************************************************************************/
  19. /// <summary>
  20. /// The internal object this node manages in the <see cref="PlayableGraph"/>.
  21. /// <para></para>
  22. /// Must be set by <see cref="CreatePlayable()"/>. Failure to do so will throw the following exception throughout
  23. /// the system when using this node: "<see cref="ArgumentException"/>: The playable passed as an argument is
  24. /// invalid. To create a valid playable, please use the appropriate Create method".
  25. /// </summary>
  26. protected internal Playable _Playable;
  27. /// <summary>[Internal] The <see cref="Playable"/> managed by this node.</summary>
  28. Playable IPlayableWrapper.Playable => _Playable;
  29. /// <summary>
  30. /// Indicates whether the <see cref="_Playable"/> is usable (properly initialized and not destroyed).
  31. /// </summary>
  32. public bool IsValid => _Playable.IsValid();
  33. /************************************************************************************************************************/
  34. #if UNITY_EDITOR
  35. /// <summary>[Editor-Only, Internal] Indicates whether the Inspector details for this node are expanded.</summary>
  36. internal bool _IsInspectorExpanded;
  37. #endif
  38. /************************************************************************************************************************/
  39. /// <summary>Creates and assigns the <see cref="Playable"/> managed by this node.</summary>
  40. /// <remarks>This method also applies the <see cref="Speed"/> if it was set beforehand.</remarks>
  41. public virtual void CreatePlayable()
  42. {
  43. #if UNITY_ASSERTIONS
  44. if (Root == null)
  45. throw new InvalidOperationException($"{nameof(AnimancerNode)}.{nameof(Root)}" +
  46. $" is null when attempting to create its {nameof(Playable)}: {this}" +
  47. $"\nThe {nameof(Root)} is generally set when you first play a state," +
  48. " so you probably just need to play it before trying to access it.");
  49. if (_Playable.IsValid())
  50. Debug.LogWarning($"{nameof(AnimancerNode)}.{nameof(CreatePlayable)}" +
  51. $" was called before destroying the previous {nameof(Playable)}: {this}", Root?.Component as Object);
  52. #endif
  53. CreatePlayable(out _Playable);
  54. #if UNITY_ASSERTIONS
  55. if (!_Playable.IsValid())
  56. throw new InvalidOperationException(
  57. $"{nameof(AnimancerNode)}.{nameof(CreatePlayable)} did not create a valid {nameof(Playable)}:" + this);
  58. #endif
  59. if (_Speed != 1)
  60. _Playable.SetSpeed(_Speed);
  61. var parent = Parent;
  62. if (parent != null)
  63. ApplyConnectedState(parent);
  64. }
  65. /// <summary>Creates and assigns the <see cref="Playable"/> managed by this node.</summary>
  66. protected abstract void CreatePlayable(out Playable playable);
  67. /************************************************************************************************************************/
  68. /// <summary>Destroys the <see cref="Playable"/>.</summary>
  69. public void DestroyPlayable()
  70. {
  71. if (_Playable.IsValid())
  72. Root._Graph.DestroyPlayable(_Playable);
  73. }
  74. /************************************************************************************************************************/
  75. /// <summary>Calls <see cref="DestroyPlayable"/> and <see cref="CreatePlayable()"/>.</summary>
  76. public virtual void RecreatePlayable()
  77. {
  78. DestroyPlayable();
  79. CreatePlayable();
  80. }
  81. /// <summary>Calls <see cref="RecreatePlayable"/> on this node and all its children recursively.</summary>
  82. public void RecreatePlayableRecursive()
  83. {
  84. RecreatePlayable();
  85. for (int i = ChildCount - 1; i >= 0; i--)
  86. GetChild(i)?.RecreatePlayableRecursive();
  87. }
  88. /************************************************************************************************************************/
  89. #endregion
  90. /************************************************************************************************************************/
  91. #region Graph
  92. /************************************************************************************************************************/
  93. /// <summary>The <see cref="AnimancerPlayable"/> at the root of the graph.</summary>
  94. public AnimancerPlayable Root { get; internal set; }
  95. /************************************************************************************************************************/
  96. /// <summary>The root <see cref="AnimancerLayer"/> which this node is connected to.</summary>
  97. public abstract AnimancerLayer Layer { get; }
  98. /// <summary>The object which receives the output of this node.</summary>
  99. public abstract IPlayableWrapper Parent { get; }
  100. /************************************************************************************************************************/
  101. /// <summary>The index of the port this node is connected to on the parent's <see cref="Playable"/>.</summary>
  102. /// <remarks>
  103. /// A negative value indicates that it is not assigned to a port.
  104. /// <para></para>
  105. /// Indices are generally assigned starting from 0, ascending in the order they are connected to their layer.
  106. /// They will not usually change unless the <see cref="Parent"/> changes or another state on the same layer is
  107. /// destroyed so the last state is swapped into its place to avoid shuffling everything down to cover the gap.
  108. /// <para></para>
  109. /// The setter is internal so user defined states cannot set it incorrectly. Ideally,
  110. /// <see cref="AnimancerLayer"/> should be able to set the port in its constructor and
  111. /// <see cref="AnimancerState.SetParent"/> should also be able to set it, but classes that further inherit from
  112. /// there should not be able to change it without properly calling that method.
  113. /// </remarks>
  114. public int Index { get; internal set; } = int.MinValue;
  115. /************************************************************************************************************************/
  116. /// <summary>Creates a new <see cref="AnimancerNode"/>.</summary>
  117. protected AnimancerNode()
  118. {
  119. #if UNITY_ASSERTIONS
  120. if (TraceConstructor)
  121. _ConstructorStackTrace = new System.Diagnostics.StackTrace(true);
  122. #endif
  123. }
  124. /************************************************************************************************************************/
  125. #if UNITY_ASSERTIONS
  126. /************************************************************************************************************************/
  127. /// <summary>[Assert-Only]
  128. /// Should a <see cref="System.Diagnostics.StackTrace"/> be captured in the constructor of all new nodes so
  129. /// <see cref="OptionalWarning.UnusedNode"/> can include it in the warning if that node ends up being unused?
  130. /// </summary>
  131. /// <remarks>This has a notable performance cost so it should only be used when trying to identify a problem.</remarks>
  132. public static bool TraceConstructor { get; set; }
  133. /************************************************************************************************************************/
  134. /// <summary>[Assert-Only]
  135. /// The stack trace of the constructor (or null if <see cref="TraceConstructor"/> was false).
  136. /// </summary>
  137. private System.Diagnostics.StackTrace _ConstructorStackTrace;
  138. /************************************************************************************************************************/
  139. /// <summary>[Assert-Only] Checks <see cref="OptionalWarning.UnusedNode"/>.</summary>
  140. ~AnimancerNode()
  141. {
  142. if (Root != null ||
  143. OptionalWarning.UnusedNode.IsDisabled())
  144. return;
  145. var name = DebugName;
  146. if (string.IsNullOrEmpty(name))
  147. {
  148. // ToString will likely throw an exception since finalizers are not run on the main thread.
  149. try { name = ToString(); }
  150. catch { name = GetType().FullName; }
  151. }
  152. var message = $"The {nameof(Root)} {nameof(AnimancerPlayable)} of '{name}'" +
  153. $" is null during finalization (garbage collection)." +
  154. $" This probably means that it was never used for anything and should not have been created.";
  155. if (_ConstructorStackTrace != null)
  156. message += "\n\nThis node was created at:\n" + _ConstructorStackTrace;
  157. else
  158. message += $"\n\nEnable {nameof(AnimancerNode)}.{nameof(TraceConstructor)} on startup to allow" +
  159. $" this warning to include the {nameof(System.Diagnostics.StackTrace)} of when the node was constructed.";
  160. OptionalWarning.UnusedNode.Log(message);
  161. }
  162. /************************************************************************************************************************/
  163. #endif
  164. /************************************************************************************************************************/
  165. /// <summary>[Internal] Connects the <see cref="Playable"/> to the <see cref="Parent"/>.</summary>
  166. internal void ConnectToGraph()
  167. {
  168. var parent = Parent;
  169. if (parent == null)
  170. return;
  171. #if UNITY_ASSERTIONS
  172. if (Index < 0)
  173. throw new InvalidOperationException(
  174. $"Invalid {nameof(AnimancerNode)}.{nameof(Index)}" +
  175. " when attempting to connect to its parent:" +
  176. "\n Node: " + this +
  177. "\n Parent: " + parent);
  178. Validate.AssertPlayable(this);
  179. #endif
  180. var parentPlayable = parent.Playable;
  181. Root._Graph.Connect(_Playable, 0, parentPlayable, Index);
  182. parentPlayable.SetInputWeight(Index, _Weight);
  183. _IsWeightDirty = false;
  184. }
  185. /// <summary>[Internal] Disconnects the <see cref="Playable"/> from the <see cref="Parent"/>.</summary>
  186. internal void DisconnectFromGraph()
  187. {
  188. var parent = Parent;
  189. if (parent == null)
  190. return;
  191. var parentPlayable = parent.Playable;
  192. if (parentPlayable.GetInput(Index).IsValid())
  193. Root._Graph.Disconnect(parentPlayable, Index);
  194. }
  195. /************************************************************************************************************************/
  196. private void ApplyConnectedState(IPlayableWrapper parent)
  197. {
  198. #if UNITY_ASSERTIONS
  199. if (Index < 0)
  200. throw new InvalidOperationException(
  201. $"Invalid {nameof(AnimancerNode)}.{nameof(Index)}" +
  202. " when attempting to connect to its parent:" +
  203. "\n Node: " + this +
  204. "\n Parent: " + parent);
  205. #endif
  206. _IsWeightDirty = true;
  207. if (_Weight != 0 || parent.KeepChildrenConnected)
  208. {
  209. ConnectToGraph();
  210. }
  211. else
  212. {
  213. Root.RequirePreUpdate(this);
  214. }
  215. }
  216. /************************************************************************************************************************/
  217. /// <summary>Calls <see cref="AnimancerPlayable.RequirePreUpdate"/> if the <see cref="Root"/> is not null.</summary>
  218. protected void RequireUpdate()
  219. {
  220. Root?.RequirePreUpdate(this);
  221. }
  222. /************************************************************************************************************************/
  223. /// <inheritdoc/>
  224. void IUpdatable.Update()
  225. {
  226. if (_Playable.IsValid())
  227. {
  228. Update(out var needsMoreUpdates);
  229. if (needsMoreUpdates)
  230. return;
  231. }
  232. Root.CancelPreUpdate(this);
  233. }
  234. /// <summary>
  235. /// Updates the <see cref="Weight"/> for fading, applies it to this state's port on the parent mixer, and plays
  236. /// or pauses the <see cref="Playable"/> if its state is dirty.
  237. /// <para></para>
  238. /// If the <see cref="Parent"/>'s <see cref="KeepChildrenConnected"/> is set to false, this method will
  239. /// also connect/disconnect this node from the <see cref="Parent"/> in the playable graph.
  240. /// </summary>
  241. protected internal virtual void Update(out bool needsMoreUpdates)
  242. {
  243. UpdateFade(out needsMoreUpdates);
  244. ApplyWeight();
  245. }
  246. /************************************************************************************************************************/
  247. // IEnumerator for yielding in a coroutine to wait until animations have stopped.
  248. /************************************************************************************************************************/
  249. /// <summary>Is this node playing and not yet at its end?</summary>
  250. /// <remarks>
  251. /// This method is called by <see cref="IEnumerator.MoveNext"/> so this object can be used as a custom yield
  252. /// instruction to wait until it finishes.
  253. /// </remarks>
  254. protected internal abstract bool IsPlayingAndNotEnding();
  255. bool IEnumerator.MoveNext() => IsPlayingAndNotEnding();
  256. object IEnumerator.Current => null;
  257. void IEnumerator.Reset() { }
  258. /************************************************************************************************************************/
  259. #endregion
  260. /************************************************************************************************************************/
  261. #region Children
  262. /************************************************************************************************************************/
  263. /// <summary>[<see cref="IPlayableWrapper"/>]
  264. /// The number of states using this node as their <see cref="AnimancerState.Parent"/>.
  265. /// </summary>
  266. public virtual int ChildCount => 0;
  267. /// <summary>Returns the state connected to the specified `index` as a child of this node.</summary>
  268. /// <exception cref="NotSupportedException">This node can't have children.</exception>
  269. AnimancerNode IPlayableWrapper.GetChild(int index) => GetChild(index);
  270. /// <summary>[<see cref="IPlayableWrapper"/>]
  271. /// Returns the state connected to the specified `index` as a child of this node.
  272. /// </summary>
  273. /// <exception cref="NotSupportedException">This node can't have children.</exception>
  274. public virtual AnimancerState GetChild(int index)
  275. => throw new NotSupportedException(this + " can't have children.");
  276. /// <summary>Called when a child is connected with this node as its <see cref="AnimancerState.Parent"/>.</summary>
  277. /// <exception cref="NotSupportedException">This node can't have children.</exception>
  278. protected internal virtual void OnAddChild(AnimancerState state)
  279. {
  280. state.ClearParent();
  281. throw new NotSupportedException(this + " can't have children.");
  282. }
  283. /// <summary>Called when a child's <see cref="AnimancerState.Parent"/> is changed from this node.</summary>
  284. /// <exception cref="NotSupportedException">This node can't have children.</exception>
  285. protected internal virtual void OnRemoveChild(AnimancerState state)
  286. {
  287. state.ClearParent();
  288. throw new NotSupportedException(this + " can't have children.");
  289. }
  290. /************************************************************************************************************************/
  291. /// <summary>Connects the `state` to this node at its <see cref="Index"/>.</summary>
  292. /// <exception cref="InvalidOperationException">The <see cref="Index"/> was already occupied.</exception>
  293. protected void OnAddChild(IList<AnimancerState> states, AnimancerState state)
  294. {
  295. var index = state.Index;
  296. if (states[index] != null)
  297. {
  298. state.ClearParent();
  299. throw new InvalidOperationException(
  300. $"Tried to add a state to an already occupied port on {this}:" +
  301. $"\n {nameof(Index)}: {index}" +
  302. $"\n Old State: {states[index]} " +
  303. $"\n New State: {state}");
  304. }
  305. #if UNITY_ASSERTIONS
  306. if (state.Root != Root)
  307. Debug.LogError(
  308. $"{nameof(AnimancerNode)}.{nameof(Root)} mismatch:" +
  309. $"\n {nameof(state)}: {state}" +
  310. $"\n {nameof(state)}.{nameof(state.Root)}: {state.Root}" +
  311. $"\n {nameof(Parent)}.{nameof(Root)}: {Root}", Root?.Component as Object);
  312. #endif
  313. states[index] = state;
  314. if (Root != null)
  315. state.ApplyConnectedState(this);
  316. }
  317. /************************************************************************************************************************/
  318. /// <summary>
  319. /// Indicates whether child playables should stay connected to this mixer at all times (default false).
  320. /// </summary>
  321. public virtual bool KeepChildrenConnected => false;
  322. /// <summary>
  323. /// Ensures that all children of this node are connected to the <see cref="_Playable"/>.
  324. /// </summary>
  325. internal void ConnectAllChildrenToGraph()
  326. {
  327. if (!Parent.Playable.GetInput(Index).IsValid())
  328. ConnectToGraph();
  329. for (int i = ChildCount - 1; i >= 0; i--)
  330. GetChild(i)?.ConnectAllChildrenToGraph();
  331. }
  332. /// <summary>
  333. /// Ensures that all children of this node which have zero weight are disconnected from the
  334. /// <see cref="_Playable"/>.
  335. /// </summary>
  336. internal void DisconnectWeightlessChildrenFromGraph()
  337. {
  338. if (Weight == 0)
  339. DisconnectFromGraph();
  340. for (int i = ChildCount - 1; i >= 0; i--)
  341. GetChild(i)?.DisconnectWeightlessChildrenFromGraph();
  342. }
  343. /************************************************************************************************************************/
  344. // IEnumerable for 'foreach' statements.
  345. /************************************************************************************************************************/
  346. /// <summary>Gets an enumerator for all of this node's child states.</summary>
  347. public virtual FastEnumerator<AnimancerState> GetEnumerator() => default;
  348. IEnumerator<AnimancerState> IEnumerable<AnimancerState>.GetEnumerator() => GetEnumerator();
  349. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  350. /************************************************************************************************************************/
  351. #endregion
  352. /************************************************************************************************************************/
  353. #region Weight
  354. /************************************************************************************************************************/
  355. /// <summary>The current blend weight of this node. Accessed via <see cref="Weight"/>.</summary>
  356. private float _Weight;
  357. /// <summary>Indicates whether the weight has changed and should be applied to the parent mixer.</summary>
  358. private bool _IsWeightDirty = true;
  359. /************************************************************************************************************************/
  360. /// <summary>The current blend weight of this node which determines how much it affects the final output.</summary>
  361. /// <remarks>
  362. /// 0 has no effect while 1 applies the full effect and values inbetween apply a proportional effect.
  363. /// <para></para>
  364. /// Setting this property cancels any fade currently in progress. If you don't wish to do that, you can use
  365. /// <see cref="SetWeight"/> instead.
  366. /// <para></para>
  367. /// <em>Animancer Lite only allows this value to be set to 0 or 1 in runtime builds.</em>
  368. /// </remarks>
  369. ///
  370. /// <example>
  371. /// Calling <see cref="AnimancerPlayable.Play(AnimationClip)"/> immediately sets the weight of all states to 0
  372. /// and the new state to 1. Note that this is separate from other values like
  373. /// <see cref="AnimancerState.IsPlaying"/> so a state can be paused at any point and still show its pose on the
  374. /// character or it could be still playing at 0 weight if you want it to still trigger events (though states
  375. /// are normally stopped when they reach 0 weight so you would need to explicitly set it to playing again).
  376. /// <para></para>
  377. /// Calling <see cref="AnimancerPlayable.Play(AnimationClip, float, FadeMode)"/> does not immediately change
  378. /// the weights, but instead calls <see cref="StartFade(float, float)"/> on every state to set their
  379. /// <see cref="TargetWeight"/> and <see cref="FadeSpeed"/>. Then every update each state's weight will move
  380. /// towards that target value at that speed.
  381. /// </example>
  382. public float Weight
  383. {
  384. get => _Weight;
  385. set
  386. {
  387. SetWeight(value);
  388. TargetWeight = value;
  389. FadeSpeed = 0;
  390. }
  391. }
  392. /// <summary>
  393. /// Sets the current blend weight of this node which determines how much it affects the final output.
  394. /// 0 has no effect while 1 applies the full effect of this node.
  395. /// <para></para>
  396. /// This method allows any fade currently in progress to continue. If you don't wish to do that, you can set
  397. /// the <see cref="Weight"/> property instead.
  398. /// <para></para>
  399. /// <em>Animancer Lite only allows this value to be set to 0 or 1 in runtime builds.</em>
  400. /// </summary>
  401. public void SetWeight(float value)
  402. {
  403. if (_Weight == value)
  404. return;
  405. #if UNITY_ASSERTIONS
  406. if (!(value >= 0) || value == float.PositiveInfinity)// Reversed comparison includes NaN.
  407. throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Weight)} must be a finite positive value");
  408. #endif
  409. _Weight = value;
  410. SetWeightDirty();
  411. }
  412. /// <summary>Flags this node as having a changed <see cref="Weight"/> that needs to be applied next update.</summary>
  413. protected internal void SetWeightDirty()
  414. {
  415. _IsWeightDirty = true;
  416. RequireUpdate();
  417. }
  418. /************************************************************************************************************************/
  419. /// <summary>
  420. /// Applies the <see cref="Weight"/> to the connection between this node and its <see cref="Parent"/>.
  421. /// </summary>
  422. public void ApplyWeight()
  423. {
  424. if (!_IsWeightDirty)
  425. return;
  426. _IsWeightDirty = false;
  427. var parent = Parent;
  428. if (parent == null)
  429. return;
  430. Playable parentPlayable;
  431. if (!parent.KeepChildrenConnected)
  432. {
  433. if (_Weight == 0)
  434. {
  435. DisconnectFromGraph();
  436. return;
  437. }
  438. parentPlayable = parent.Playable;
  439. if (!parentPlayable.GetInput(Index).IsValid())
  440. ConnectToGraph();
  441. }
  442. else parentPlayable = parent.Playable;
  443. parentPlayable.SetInputWeight(Index, _Weight);
  444. }
  445. /************************************************************************************************************************/
  446. /// <summary>
  447. /// The <see cref="Weight"/> of this state multiplied by the <see cref="Weight"/> of each of its parents down
  448. /// the hierarchy to determine how much this state affects the final output.
  449. /// </summary>
  450. public float EffectiveWeight
  451. {
  452. get
  453. {
  454. var weight = Weight;
  455. var parent = Parent;
  456. while (parent != null)
  457. {
  458. weight *= parent.Weight;
  459. parent = parent.Parent;
  460. }
  461. return weight;
  462. }
  463. }
  464. /************************************************************************************************************************/
  465. #endregion
  466. /************************************************************************************************************************/
  467. #region Fading
  468. /************************************************************************************************************************/
  469. /// <summary>
  470. /// The desired <see cref="Weight"/> which this node is fading towards according to the
  471. /// <see cref="FadeSpeed"/>.
  472. /// </summary>
  473. public float TargetWeight { get; set; }
  474. /// <summary>The speed at which this node is fading towards the <see cref="TargetWeight"/>.</summary>
  475. /// <remarks>This value isn't affected by this node's <see cref="Speed"/>, but is affected by its parents.</remarks>
  476. public float FadeSpeed { get; set; }
  477. /************************************************************************************************************************/
  478. /// <summary>
  479. /// Calls <see cref="OnStartFade"/> and starts fading the <see cref="Weight"/> over the course
  480. /// of the <see cref="AnimancerPlayable.DefaultFadeDuration"/> (in seconds).
  481. /// </summary>
  482. /// <remarks>
  483. /// If the `targetWeight` is 0 then <see cref="Stop"/> will be called when the fade is complete.
  484. /// <para></para>
  485. /// If the <see cref="Weight"/> is already equal to the `targetWeight` then the fade will end
  486. /// immediately.
  487. /// </remarks>
  488. public void StartFade(float targetWeight)
  489. => StartFade(targetWeight, AnimancerPlayable.DefaultFadeDuration);
  490. /// <summary>
  491. /// Calls <see cref="OnStartFade"/> and starts fading the <see cref="Weight"/> over the course
  492. /// of the `fadeDuration` (in seconds).
  493. /// </summary>
  494. /// <remarks>
  495. /// If the `targetWeight` is 0 then <see cref="Stop"/> will be called when the fade is complete.
  496. /// <para></para>
  497. /// If the <see cref="Weight"/> is already equal to the `targetWeight` then the fade will end
  498. /// immediately.
  499. /// <para></para>
  500. /// <em>Animancer Lite only allows a `targetWeight` of 0 or 1 and the default `fadeDuration` (0.25 seconds) in
  501. /// runtime builds.</em>
  502. /// </remarks>
  503. public void StartFade(float targetWeight, float fadeDuration)
  504. {
  505. TargetWeight = targetWeight;
  506. if (targetWeight == Weight)
  507. {
  508. if (targetWeight == 0)
  509. {
  510. Stop();
  511. }
  512. else
  513. {
  514. FadeSpeed = 0;
  515. OnStartFade();
  516. }
  517. return;
  518. }
  519. // Duration 0 = Instant.
  520. if (fadeDuration <= 0)
  521. {
  522. FadeSpeed = float.PositiveInfinity;
  523. }
  524. else// Otherwise determine how fast we need to go to cover the distance in the specified time.
  525. {
  526. FadeSpeed = Math.Abs(Weight - targetWeight) / fadeDuration;
  527. }
  528. OnStartFade();
  529. RequireUpdate();
  530. }
  531. /************************************************************************************************************************/
  532. /// <summary>Called by <see cref="StartFade(float, float)"/>.</summary>
  533. protected internal abstract void OnStartFade();
  534. /************************************************************************************************************************/
  535. /// <summary>
  536. /// Stops the animation and makes it inactive immediately so it no longer affects the output.
  537. /// Sets <see cref="Weight"/> = 0 by default.
  538. /// </summary>
  539. public virtual void Stop()
  540. {
  541. Weight = 0;
  542. }
  543. /************************************************************************************************************************/
  544. /// <summary>
  545. /// Moves the <see cref="Weight"/> towards the <see cref="TargetWeight"/> according to the
  546. /// <see cref="FadeSpeed"/>.
  547. /// </summary>
  548. private void UpdateFade(out bool needsMoreUpdates)
  549. {
  550. var fadeSpeed = FadeSpeed;
  551. if (fadeSpeed == 0)
  552. {
  553. needsMoreUpdates = false;
  554. return;
  555. }
  556. _IsWeightDirty = true;
  557. fadeSpeed *= ParentEffectiveSpeed * AnimancerPlayable.DeltaTime;
  558. if (fadeSpeed < 0)
  559. fadeSpeed = -fadeSpeed;
  560. var target = TargetWeight;
  561. var current = _Weight;
  562. var delta = target - current;
  563. if (delta > 0)
  564. {
  565. if (delta > fadeSpeed)
  566. {
  567. _Weight = current + fadeSpeed;
  568. needsMoreUpdates = true;
  569. return;
  570. }
  571. }
  572. else
  573. {
  574. if (-delta > fadeSpeed)
  575. {
  576. _Weight = current - fadeSpeed;
  577. needsMoreUpdates = true;
  578. return;
  579. }
  580. }
  581. _Weight = target;
  582. needsMoreUpdates = false;
  583. if (target == 0)
  584. {
  585. Stop();
  586. }
  587. else
  588. {
  589. FadeSpeed = 0;
  590. }
  591. }
  592. /************************************************************************************************************************/
  593. #endregion
  594. /************************************************************************************************************************/
  595. #region Inverse Kinematics
  596. /************************************************************************************************************************/
  597. /// <summary>
  598. /// Should setting the <see cref="Parent"/> also set this node's <see cref="ApplyAnimatorIK"/> to match it?
  599. /// Default is true.
  600. /// </summary>
  601. public static bool ApplyParentAnimatorIK { get; set; } = true;
  602. /// <summary>
  603. /// Should setting the <see cref="Parent"/> also set this node's <see cref="ApplyFootIK"/> to match it?
  604. /// Default is true.
  605. /// </summary>
  606. public static bool ApplyParentFootIK { get; set; } = true;
  607. /************************************************************************************************************************/
  608. /// <summary>
  609. /// Copies the IK settings from the <see cref="Parent"/>:
  610. /// <list type="bullet">
  611. /// <item>If <see cref="ApplyParentAnimatorIK"/> is true, copy <see cref="ApplyAnimatorIK"/>.</item>
  612. /// <item>If <see cref="ApplyParentFootIK"/> is true, copy <see cref="ApplyFootIK"/>.</item>
  613. /// </list>
  614. /// </summary>
  615. public virtual void CopyIKFlags(AnimancerNode node)
  616. {
  617. if (Root == null)
  618. return;
  619. if (ApplyParentAnimatorIK)
  620. {
  621. ApplyAnimatorIK = node.ApplyAnimatorIK;
  622. if (ApplyParentFootIK)
  623. ApplyFootIK = node.ApplyFootIK;
  624. }
  625. else if (ApplyParentFootIK)
  626. {
  627. ApplyFootIK = node.ApplyFootIK;
  628. }
  629. }
  630. /************************************************************************************************************************/
  631. /// <inheritdoc/>
  632. public virtual bool ApplyAnimatorIK
  633. {
  634. get
  635. {
  636. for (int i = ChildCount - 1; i >= 0; i--)
  637. {
  638. var state = GetChild(i);
  639. if (state == null)
  640. continue;
  641. if (state.ApplyAnimatorIK)
  642. return true;
  643. }
  644. return false;
  645. }
  646. set
  647. {
  648. for (int i = ChildCount - 1; i >= 0; i--)
  649. {
  650. var state = GetChild(i);
  651. if (state == null)
  652. continue;
  653. state.ApplyAnimatorIK = value;
  654. }
  655. }
  656. }
  657. /************************************************************************************************************************/
  658. /// <inheritdoc/>
  659. public virtual bool ApplyFootIK
  660. {
  661. get
  662. {
  663. for (int i = ChildCount - 1; i >= 0; i--)
  664. {
  665. var state = GetChild(i);
  666. if (state == null)
  667. continue;
  668. if (state.ApplyFootIK)
  669. return true;
  670. }
  671. return false;
  672. }
  673. set
  674. {
  675. for (int i = ChildCount - 1; i >= 0; i--)
  676. {
  677. var state = GetChild(i);
  678. if (state == null)
  679. continue;
  680. state.ApplyFootIK = value;
  681. }
  682. }
  683. }
  684. /************************************************************************************************************************/
  685. #endregion
  686. /************************************************************************************************************************/
  687. #region Speed
  688. /************************************************************************************************************************/
  689. private float _Speed = 1;
  690. /// <summary>[Pro-Only] How fast the <see cref="AnimancerState.Time"/> is advancing every frame (default 1).</summary>
  691. ///
  692. /// <remarks>
  693. /// A negative value will play the animation backwards.
  694. /// <para></para>
  695. /// To pause an animation, consider setting <see cref="AnimancerState.IsPlaying"/> to false instead of setting
  696. /// this value to 0.
  697. /// <para></para>
  698. /// <em>Animancer Lite does not allow this value to be changed in runtime builds.</em>
  699. /// </remarks>
  700. ///
  701. /// <example><code>
  702. /// void PlayAnimation(AnimancerComponent animancer, AnimationClip clip)
  703. /// {
  704. /// var state = animancer.Play(clip);
  705. ///
  706. /// state.Speed = 1;// Normal speed.
  707. /// state.Speed = 2;// Double speed.
  708. /// state.Speed = 0.5f;// Half speed.
  709. /// state.Speed = -1;// Normal speed playing backwards.
  710. /// }
  711. /// </code></example>
  712. ///
  713. /// <exception cref="ArgumentOutOfRangeException">The value is not finite.</exception>
  714. public float Speed
  715. {
  716. get => _Speed;
  717. set
  718. {
  719. #if UNITY_ASSERTIONS
  720. if (!value.IsFinite())
  721. throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(Speed)} {Strings.MustBeFinite}");
  722. OptionalWarning.UnsupportedSpeed.Log(UnsupportedSpeedMessage, Root?.Component);
  723. #endif
  724. _Speed = value;
  725. if (_Playable.IsValid())
  726. _Playable.SetSpeed(value);
  727. }
  728. }
  729. #if UNITY_ASSERTIONS
  730. /// <summary>[Assert-Only]
  731. /// Returns null if the <see cref="Speed"/> property will work properly on this type of node, or a message
  732. /// explaining why it won't work.
  733. /// </summary>
  734. protected virtual string UnsupportedSpeedMessage => null;
  735. #endif
  736. /************************************************************************************************************************/
  737. /// <summary>
  738. /// The multiplied <see cref="Speed"/> of each of this node's parents down the hierarchy, excluding the root
  739. /// <see cref="AnimancerPlayable.Speed"/>.
  740. /// </summary>
  741. private float ParentEffectiveSpeed
  742. {
  743. get
  744. {
  745. var parent = Parent;
  746. if (parent == null)
  747. return 1;
  748. var speed = parent.Speed;
  749. while ((parent = parent.Parent) != null)
  750. {
  751. speed *= parent.Speed;
  752. }
  753. return speed;
  754. }
  755. }
  756. /// <summary>
  757. /// The <see cref="Speed"/> of this node multiplied by the <see cref="Speed"/> of each of its parents to
  758. /// determine the actual speed it's playing at.
  759. /// </summary>
  760. public float EffectiveSpeed
  761. {
  762. get => Speed * ParentEffectiveSpeed;
  763. set => Speed = value / ParentEffectiveSpeed;
  764. }
  765. /************************************************************************************************************************/
  766. #endregion
  767. /************************************************************************************************************************/
  768. #region Descriptions
  769. /************************************************************************************************************************/
  770. #if UNITY_ASSERTIONS
  771. /// <summary>[Assert-Only] The Inspector display name of this node.</summary>
  772. /// <remarks>Set using <see cref="SetDebugName"/>.</remarks>
  773. public string DebugName { get; private set; }
  774. #endif
  775. /// <summary>The Inspector display name of this node.</summary>
  776. public override string ToString()
  777. {
  778. #if UNITY_ASSERTIONS
  779. if (!string.IsNullOrEmpty(DebugName))
  780. return DebugName;
  781. #endif
  782. return base.ToString();
  783. }
  784. /// <summary>[Assert-Conditional]
  785. /// Sets the Inspector display name of this node. <see cref="ToString"/> returns the name.
  786. /// </summary>
  787. [System.Diagnostics.Conditional(Strings.Assertions)]
  788. public void SetDebugName(string name)
  789. {
  790. #if UNITY_ASSERTIONS
  791. DebugName = name;
  792. #endif
  793. }
  794. /************************************************************************************************************************/
  795. /// <summary>Returns a detailed descrption of the current details of this node.</summary>
  796. public string GetDescription(string separator = "\n")
  797. {
  798. var text = ObjectPool.AcquireStringBuilder();
  799. AppendDescription(text, separator);
  800. return text.ReleaseToString();
  801. }
  802. /************************************************************************************************************************/
  803. /// <summary>Appends a detailed descrption of the current details of this node.</summary>
  804. public void AppendDescription(StringBuilder text, string separator = "\n")
  805. {
  806. text.Append(ToString());
  807. AppendDetails(text, separator);
  808. if (ChildCount > 0)
  809. {
  810. text.Append(separator).Append($"{nameof(ChildCount)}: ").Append(ChildCount);
  811. var indentedSeparator = separator + Strings.Indent;
  812. var i = 0;
  813. foreach (var child in this)
  814. {
  815. text.Append(separator).Append('[').Append(i++).Append("] ");
  816. child.AppendDescription(text, indentedSeparator);
  817. }
  818. }
  819. }
  820. /************************************************************************************************************************/
  821. /// <summary>Called by <see cref="AppendDescription"/> to append the details of this node.</summary>
  822. protected virtual void AppendDetails(StringBuilder text, string separator)
  823. {
  824. text.Append(separator).Append("Playable: ");
  825. if (_Playable.IsValid())
  826. text.Append(_Playable.GetPlayableType());
  827. else
  828. text.Append("Invalid");
  829. text.Append(separator).Append($"{nameof(Index)}: ").Append(Index);
  830. var realSpeed = _Playable.IsValid() ? _Playable.GetSpeed() : _Speed;
  831. if (realSpeed == _Speed)
  832. {
  833. text.Append(separator).Append($"{nameof(Speed)}: ").Append(_Speed);
  834. }
  835. else
  836. {
  837. text.Append(separator).Append($"{nameof(Speed)} (Real): ").Append(_Speed)
  838. .Append(" (").Append(realSpeed).Append(')');
  839. }
  840. text.Append(separator).Append($"{nameof(Weight)}: ").Append(Weight);
  841. if (Weight != TargetWeight)
  842. {
  843. text.Append(separator).Append($"{nameof(TargetWeight)}: ").Append(TargetWeight);
  844. text.Append(separator).Append($"{nameof(FadeSpeed)}: ").Append(FadeSpeed);
  845. }
  846. AppendIKDetails(text, separator, this);
  847. }
  848. /************************************************************************************************************************/
  849. /// <summary>
  850. /// Appends the details of <see cref="IPlayableWrapper.ApplyAnimatorIK"/> and
  851. /// <see cref="IPlayableWrapper.ApplyFootIK"/>.
  852. /// </summary>
  853. public static void AppendIKDetails(StringBuilder text, string separator, IPlayableWrapper node)
  854. {
  855. text.Append(separator).Append("InverseKinematics: ");
  856. if (node.ApplyAnimatorIK)
  857. {
  858. text.Append("OnAnimatorIK");
  859. if (node.ApplyFootIK)
  860. text.Append(", FootIK");
  861. }
  862. else if (node.ApplyFootIK)
  863. {
  864. text.Append("FootIK");
  865. }
  866. else
  867. {
  868. text.Append("None");
  869. }
  870. }
  871. /************************************************************************************************************************/
  872. #endregion
  873. /************************************************************************************************************************/
  874. }
  875. }