AnimancerPlayable.StateDictionary.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2022 Kybernetik //
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. namespace Animancer
  7. {
  8. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerPlayable
  9. ///
  10. partial class AnimancerPlayable
  11. {
  12. /// <summary>A dictionary of <see cref="AnimancerState"/>s mapped to their <see cref="AnimancerState.Key"/>.</summary>
  13. /// <remarks>
  14. /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/playing/states">States</see>
  15. /// </remarks>
  16. /// https://kybernetik.com.au/animancer/api/Animancer/StateDictionary
  17. ///
  18. public class StateDictionary : IEnumerable<AnimancerState>, IAnimationClipCollection
  19. {
  20. /************************************************************************************************************************/
  21. /// <summary>The <see cref="AnimancerPlayable"/> at the root of the graph.</summary>
  22. private readonly AnimancerPlayable Root;
  23. /************************************************************************************************************************/
  24. /// <summary>The <see cref="IEqualityComparer{T}"/> used by every new <see cref="StateDictionary"/>.</summary>
  25. /// <remarks>
  26. /// By default, this will use <see cref="FastComparer.Instance"/>.
  27. /// <para></para>
  28. /// Setting it to <see cref="FastReferenceComparer.Instance"/> would make it slightly faster, but would
  29. /// not work for value types such as enums.
  30. /// <para></para>
  31. /// Changing this value will not affect existing instances.
  32. /// </remarks>
  33. public static IEqualityComparer<object> EqualityComparer { get; set; } = FastComparer.Instance;
  34. /// <summary><see cref="AnimancerState.Key"/> mapped to <see cref="AnimancerState"/>.</summary>
  35. private readonly Dictionary<object, AnimancerState>
  36. States = new Dictionary<object, AnimancerState>(EqualityComparer);
  37. /************************************************************************************************************************/
  38. /// <summary>[Internal] Creates a new <see cref="StateDictionary"/>.</summary>
  39. internal StateDictionary(AnimancerPlayable root) => Root = root;
  40. /************************************************************************************************************************/
  41. /// <summary>The number of states that have been registered with a <see cref="AnimancerState.Key"/>.</summary>
  42. public int Count => States.Count;
  43. /************************************************************************************************************************/
  44. #region Create
  45. /************************************************************************************************************************/
  46. /// <summary>Creates and returns a new <see cref="ClipState"/> to play the `clip`.</summary>
  47. /// <remarks>
  48. /// To create a state on a specific layer, use <c>animancer.Layers[x].CreateState(clip)</c> instead.
  49. /// <para></para>
  50. /// <see cref="GetKey"/> is used to determine the <see cref="AnimancerState.Key"/>.
  51. /// </remarks>
  52. public ClipState Create(AnimationClip clip)
  53. => Create(Root.GetKey(clip), clip);
  54. /// <summary>
  55. /// Creates and returns a new <see cref="ClipState"/> to play the `clip` and registers it with the `key`.
  56. /// </summary>
  57. /// <remarks>
  58. /// To create a state on a specific layer, use <c>animancer.Layers[x].CreateState(key, clip)</c> instead.
  59. /// </remarks>
  60. public ClipState Create(object key, AnimationClip clip)
  61. {
  62. var state = new ClipState(clip);
  63. state.SetRoot(Root);
  64. state._Key = key;
  65. Register(state);
  66. return state;
  67. }
  68. /************************************************************************************************************************/
  69. /// <summary>Calls <see cref="GetOrCreate(AnimationClip, bool)"/> for each of the specified clips.</summary>
  70. public void CreateIfNew(AnimationClip clip0, AnimationClip clip1)
  71. {
  72. GetOrCreate(clip0);
  73. GetOrCreate(clip1);
  74. }
  75. /// <summary>Calls <see cref="GetOrCreate(AnimationClip, bool)"/> for each of the specified clips.</summary>
  76. public void CreateIfNew(AnimationClip clip0, AnimationClip clip1, AnimationClip clip2)
  77. {
  78. GetOrCreate(clip0);
  79. GetOrCreate(clip1);
  80. GetOrCreate(clip2);
  81. }
  82. /// <summary>Calls <see cref="GetOrCreate(AnimationClip, bool)"/> for each of the specified clips.</summary>
  83. public void CreateIfNew(AnimationClip clip0, AnimationClip clip1, AnimationClip clip2, AnimationClip clip3)
  84. {
  85. GetOrCreate(clip0);
  86. GetOrCreate(clip1);
  87. GetOrCreate(clip2);
  88. GetOrCreate(clip3);
  89. }
  90. /// <summary>Calls <see cref="GetOrCreate(AnimationClip, bool)"/> for each of the specified `clips`.</summary>
  91. public void CreateIfNew(params AnimationClip[] clips)
  92. {
  93. if (clips == null)
  94. return;
  95. var count = clips.Length;
  96. for (int i = 0; i < count; i++)
  97. {
  98. var clip = clips[i];
  99. if (clip != null)
  100. GetOrCreate(clip);
  101. }
  102. }
  103. /************************************************************************************************************************/
  104. #endregion
  105. /************************************************************************************************************************/
  106. #region Access
  107. /************************************************************************************************************************/
  108. /// <summary>
  109. /// The <see cref="AnimancerLayer.CurrentState"/> on layer 0.
  110. /// <para></para>
  111. /// Specifically, this is the state that was most recently started using any of the Play methods on that layer.
  112. /// States controlled individually via methods in the <see cref="AnimancerState"/> itself will not register in
  113. /// this property.
  114. /// </summary>
  115. public AnimancerState Current => Root.Layers[0].CurrentState;
  116. /************************************************************************************************************************/
  117. /// <summary>Calls <see cref="GetKey"/> then returns the state registered with that key.</summary>
  118. /// <exception cref="ArgumentNullException">The key is null.</exception>
  119. /// <exception cref="KeyNotFoundException">No state is registered with the key.</exception>
  120. public AnimancerState this[AnimationClip clip] => States[Root.GetKey(clip)];
  121. /// <summary>Returns the state registered with the <see cref="IHasKey.Key"/>.</summary>
  122. /// <exception cref="ArgumentNullException">The `key` is null.</exception>
  123. /// <exception cref="KeyNotFoundException">No state is registered with the `key`.</exception>
  124. public AnimancerState this[IHasKey hasKey] => States[hasKey.Key];
  125. /// <summary>Returns the state registered with the `key`.</summary>
  126. /// <exception cref="ArgumentNullException">The `key` is null.</exception>
  127. /// <exception cref="KeyNotFoundException">No state is registered with the `key`.</exception>
  128. public AnimancerState this[object key] => States[key];
  129. /************************************************************************************************************************/
  130. /// <summary>
  131. /// Calls <see cref="GetKey"/> then passes the key to
  132. /// <see cref="TryGet(object, out AnimancerState)"/> and returns the result.
  133. /// </summary>
  134. public bool TryGet(AnimationClip clip, out AnimancerState state)
  135. {
  136. if (clip == null)
  137. {
  138. state = null;
  139. return false;
  140. }
  141. return TryGet(Root.GetKey(clip), out state);
  142. }
  143. /// <summary>
  144. /// Passes the <see cref="IHasKey.Key"/> into <see cref="TryGet(object, out AnimancerState)"/>
  145. /// and returns the result.
  146. /// </summary>
  147. public bool TryGet(IHasKey hasKey, out AnimancerState state)
  148. {
  149. if (hasKey == null)
  150. {
  151. state = null;
  152. return false;
  153. }
  154. return TryGet(hasKey.Key, out state);
  155. }
  156. /// <summary>
  157. /// If a `state` is registered with the `key`, this method outputs it and returns true. Otherwise the
  158. /// `state` is set to null and this method returns false.
  159. /// </summary>
  160. public bool TryGet(object key, out AnimancerState state)
  161. {
  162. if (key == null)
  163. {
  164. state = null;
  165. return false;
  166. }
  167. return States.TryGetValue(key, out state);
  168. }
  169. /************************************************************************************************************************/
  170. /// <summary>
  171. /// Calls <see cref="GetKey"/> and returns the state which registered with that key or creates one if it
  172. /// doesn't exist.
  173. /// <para></para>
  174. /// If the state already exists but has the wrong <see cref="AnimancerState.Clip"/>, the `allowSetClip`
  175. /// parameter determines what will happen. False causes it to throw an <see cref="ArgumentException"/> while
  176. /// true allows it to change the <see cref="AnimancerState.Clip"/>. Note that the change is somewhat costly to
  177. /// performance so use with caution.
  178. /// </summary>
  179. /// <exception cref="ArgumentException"/>
  180. public AnimancerState GetOrCreate(AnimationClip clip, bool allowSetClip = false)
  181. => GetOrCreate(Root.GetKey(clip), clip, allowSetClip);
  182. /// <summary>
  183. /// Returns the state registered with the `transition`s <see cref="IHasKey.Key"/> if there is one. Otherwise
  184. /// this method uses <see cref="ITransition.CreateState"/> to create a new one and registers it with
  185. /// that key before returning it.
  186. /// </summary>
  187. public AnimancerState GetOrCreate(ITransition transition)
  188. {
  189. var key = transition.Key;
  190. if (!TryGet(key, out var state))
  191. {
  192. state = transition.CreateState();
  193. state.SetRoot(Root);
  194. state._Key = key;
  195. Register(state);
  196. }
  197. return state;
  198. }
  199. /// <summary>
  200. /// Returns the state which registered with the `key` or creates one if it doesn't exist.
  201. /// <para></para>
  202. /// If the state already exists but has the wrong <see cref="AnimancerState.Clip"/>, the `allowSetClip`
  203. /// parameter determines what will happen. False causes it to throw an <see cref="ArgumentException"/> while
  204. /// true allows it to change the <see cref="AnimancerState.Clip"/>. Note that the change is somewhat costly to
  205. /// performance to use with caution.
  206. /// </summary>
  207. /// <exception cref="ArgumentException"/>
  208. /// <remarks>See also: <see cref="AnimancerLayer.GetOrCreateState(object, AnimationClip, bool)"/></remarks>
  209. public AnimancerState GetOrCreate(object key, AnimationClip clip, bool allowSetClip = false)
  210. {
  211. if (TryGet(key, out var state))
  212. {
  213. // If a state exists with the 'key' but has the wrong clip, either change it or complain.
  214. if (!ReferenceEquals(state.Clip, clip))
  215. {
  216. if (allowSetClip)
  217. {
  218. state.Clip = clip;
  219. }
  220. else
  221. {
  222. throw new ArgumentException(GetClipMismatchError(key, state.Clip, clip));
  223. }
  224. }
  225. }
  226. else
  227. {
  228. state = Create(key, clip);
  229. }
  230. return state;
  231. }
  232. /************************************************************************************************************************/
  233. /// <summary>Returns an error message explaining that a state already exists with the specified `key`.</summary>
  234. public static string GetClipMismatchError(object key, AnimationClip oldClip, AnimationClip newClip)
  235. => $"A state already exists using the specified '{nameof(key)}', but has a different {nameof(AnimationClip)}:" +
  236. $"\n - Key: {key}" +
  237. $"\n - Old Clip: {oldClip}" +
  238. $"\n - New Clip: {newClip}";
  239. /************************************************************************************************************************/
  240. /// <summary>[Internal]
  241. /// Registers the `state` in this dictionary so the <see cref="AnimancerState.Key"/> can be used to get it
  242. /// later on using any of the lookup methods such as <see cref="this[object]"/> or
  243. /// <see cref="TryGet(object, out AnimancerState)"/>.
  244. /// </summary>
  245. /// <remarks>Does nothing if the <see cref="AnimancerState.Key"/> is <c>null</c>.</remarks>
  246. internal void Register(AnimancerState state)
  247. {
  248. var key = state._Key;
  249. if (key != null)
  250. {
  251. #if UNITY_ASSERTIONS
  252. if (state.Root != Root)
  253. throw new ArgumentException(
  254. $"{nameof(StateDictionary)} cannot register a state with a different {nameof(Root)}: " + state);
  255. #endif
  256. States.Add(key, state);
  257. }
  258. }
  259. /// <summary>[Internal] Removes the `state` from this dictionary (the opposite of <see cref="Register"/>).</summary>
  260. internal void Unregister(AnimancerState state)
  261. {
  262. var key = state._Key;
  263. if (key != null)
  264. States.Remove(key);
  265. }
  266. /************************************************************************************************************************/
  267. #region Enumeration
  268. /************************************************************************************************************************/
  269. // IEnumerable for 'foreach' statements.
  270. /************************************************************************************************************************/
  271. /// <summary>Returns an enumerator that will iterate through all registered states.</summary>
  272. public Dictionary<object, AnimancerState>.ValueCollection.Enumerator GetEnumerator()
  273. => States.Values.GetEnumerator();
  274. /// <inheritdoc/>
  275. IEnumerator<AnimancerState> IEnumerable<AnimancerState>.GetEnumerator()
  276. => GetEnumerator();
  277. /// <inheritdoc/>
  278. IEnumerator IEnumerable.GetEnumerator()
  279. => GetEnumerator();
  280. /************************************************************************************************************************/
  281. /// <summary>[<see cref="IAnimationClipCollection"/>]
  282. /// Adds all the animations of states with a <see cref="AnimancerState.Key"/> to the `clips`.
  283. /// </summary>
  284. public void GatherAnimationClips(ICollection<AnimationClip> clips)
  285. {
  286. foreach (var state in States.Values)
  287. clips.GatherFromSource(state);
  288. }
  289. /************************************************************************************************************************/
  290. #endregion
  291. /************************************************************************************************************************/
  292. #endregion
  293. /************************************************************************************************************************/
  294. #region Destroy
  295. /************************************************************************************************************************/
  296. /// <summary>
  297. /// Calls <see cref="AnimancerState.Destroy"/> on the state associated with the `clip` (if any).
  298. /// Returns true if the state existed.
  299. /// </summary>
  300. public bool Destroy(AnimationClip clip)
  301. {
  302. if (clip == null)
  303. return false;
  304. return Destroy(Root.GetKey(clip));
  305. }
  306. /// <summary>
  307. /// Calls <see cref="AnimancerState.Destroy"/> on the state associated with the <see cref="IHasKey.Key"/>
  308. /// (if any). Returns true if the state existed.
  309. /// </summary>
  310. public bool Destroy(IHasKey hasKey)
  311. {
  312. if (hasKey == null)
  313. return false;
  314. return Destroy(hasKey.Key);
  315. }
  316. /// <summary>
  317. /// Calls <see cref="AnimancerState.Destroy"/> on the state associated with the `key` (if any).
  318. /// Returns true if the state existed.
  319. /// </summary>
  320. public bool Destroy(object key)
  321. {
  322. if (!TryGet(key, out var state))
  323. return false;
  324. state.Destroy();
  325. return true;
  326. }
  327. /************************************************************************************************************************/
  328. /// <summary>Calls <see cref="Destroy(AnimationClip)"/> on each of the `clips`.</summary>
  329. public void DestroyAll(IList<AnimationClip> clips)
  330. {
  331. if (clips == null)
  332. return;
  333. for (int i = clips.Count - 1; i >= 0; i--)
  334. Destroy(clips[i]);
  335. }
  336. /// <summary>Calls <see cref="Destroy(AnimationClip)"/> on each of the `clips`.</summary>
  337. public void DestroyAll(IEnumerable<AnimationClip> clips)
  338. {
  339. if (clips == null)
  340. return;
  341. foreach (var clip in clips)
  342. Destroy(clip);
  343. }
  344. /************************************************************************************************************************/
  345. /// <summary>
  346. /// Calls <see cref="Destroy(AnimationClip)"/> on all states gathered by
  347. /// <see cref="IAnimationClipSource.GetAnimationClips"/>.
  348. /// </summary>
  349. public void DestroyAll(IAnimationClipSource source)
  350. {
  351. if (source == null)
  352. return;
  353. var clips = ObjectPool.AcquireList<AnimationClip>();
  354. source.GetAnimationClips(clips);
  355. DestroyAll(clips);
  356. ObjectPool.Release(clips);
  357. }
  358. /// <summary>
  359. /// Calls <see cref="Destroy(AnimationClip)"/> on all states gathered by
  360. /// <see cref="IAnimationClipCollection.GatherAnimationClips"/>.
  361. /// </summary>
  362. public void DestroyAll(IAnimationClipCollection source)
  363. {
  364. if (source == null)
  365. return;
  366. var clips = ObjectPool.AcquireSet<AnimationClip>();
  367. source.GatherAnimationClips(clips);
  368. DestroyAll(clips);
  369. ObjectPool.Release(clips);
  370. }
  371. /************************************************************************************************************************/
  372. #endregion
  373. /************************************************************************************************************************/
  374. #region Key Error Methods
  375. #if UNITY_EDITOR
  376. /************************************************************************************************************************/
  377. // These are overloads of other methods that take a System.Object key to ensure the user doesn't try to use an
  378. // AnimancerState as a key, since the whole point of a key is to identify a state in the first place.
  379. /************************************************************************************************************************/
  380. /// <summary>[Warning]
  381. /// You should not use an <see cref="AnimancerState"/> as a key.
  382. /// The whole point of a key is to identify a state in the first place.
  383. /// </summary>
  384. [Obsolete("You should not use an AnimancerState as a key. The whole point of a key is to identify a state in the first place.", true)]
  385. public AnimancerState this[AnimancerState key] => key;
  386. /// <summary>[Warning]
  387. /// You should not use an <see cref="AnimancerState"/> as a key.
  388. /// The whole point of a key is to identify a state in the first place.
  389. /// </summary>
  390. [Obsolete("You should not use an AnimancerState as a key. The whole point of a key is to identify a state in the first place.", true)]
  391. public bool TryGet(AnimancerState key, out AnimancerState state)
  392. {
  393. state = key;
  394. return true;
  395. }
  396. /// <summary>[Warning]
  397. /// You should not use an <see cref="AnimancerState"/> as a key.
  398. /// The whole point of a key is to identify a state in the first place.
  399. /// </summary>
  400. [Obsolete("You should not use an AnimancerState as a key. The whole point of a key is to identify a state in the first place.", true)]
  401. public AnimancerState GetOrCreate(AnimancerState key, AnimationClip clip) => key;
  402. /// <summary>[Warning]
  403. /// You should not use an <see cref="AnimancerState"/> as a key.
  404. /// Just call <see cref="AnimancerState.Destroy"/>.
  405. /// </summary>
  406. [Obsolete("You should not use an AnimancerState as a key. Just call AnimancerState.Destroy.", true)]
  407. public bool Destroy(AnimancerState key)
  408. {
  409. key.Destroy();
  410. return true;
  411. }
  412. /************************************************************************************************************************/
  413. #endif
  414. #endregion
  415. /************************************************************************************************************************/
  416. }
  417. }
  418. }