StateMachine2.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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.FSM
  7. {
  8. /// <summary>Interface for accessing <see cref="StateMachine{TKey, TState}"/> without the <c>TState</c>.</summary>
  9. /// <remarks>
  10. /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/fsm/keys">Keyed State Machines</see>
  11. /// </remarks>
  12. /// https://kybernetik.com.au/animancer/api/Animancer.FSM/IKeyedStateMachine_1
  13. ///
  14. public interface IKeyedStateMachine<TKey>
  15. {
  16. /************************************************************************************************************************/
  17. /// <summary>The key which identifies the <see cref="StateMachine{TState}.CurrentState"/>.</summary>
  18. TKey CurrentKey { get; }
  19. /// <summary>The <see cref="KeyChange{TKey}.PreviousKey"/>.</summary>
  20. TKey PreviousKey { get; }
  21. /// <summary>The <see cref="KeyChange{TKey}.NextKey"/>.</summary>
  22. TKey NextKey { get; }
  23. /// <summary>Attempts to enter the state registered with the specified `key` and returns it if successful.</summary>
  24. /// <remarks>
  25. /// This method returns true immediately if the specified `key` is already the <see cref="CurrentKey"/>. To
  26. /// allow directly re-entering the same state, use <see cref="TryResetState(TKey)"/> instead.
  27. /// </remarks>
  28. object TrySetState(TKey key);
  29. /// <summary>Attempts to enter the state registered with the specified `key` and returns it if successful.</summary>
  30. /// <remarks>
  31. /// This method does not check if the `key` is already the <see cref="CurrentKey"/>. To do so, use
  32. /// <see cref="TrySetState(TKey)"/> instead.
  33. /// </remarks>
  34. object TryResetState(TKey key);
  35. /// <summary>
  36. /// Uses <see cref="StateMachine{TKey, TState}.ForceSetState(TKey, TState)"/> to change to the state registered
  37. /// with the `key`. If nothing is registered, it changes to <c>default(TState)</c>.
  38. /// </summary>
  39. object ForceSetState(TKey key);
  40. /************************************************************************************************************************/
  41. }
  42. /// <summary>A simple Finite State Machine system that registers each state with a particular key.</summary>
  43. /// <remarks>
  44. /// This class allows states to be registered with a particular key upfront and then accessed later using that key.
  45. /// See <see cref="StateMachine{TState}"/> for a system that does not bother keeping track of any states other than
  46. /// the active one.
  47. /// <para></para>
  48. /// See <see cref="InitializeAfterDeserialize"/> if using this class in a serialized field.
  49. /// <para></para>
  50. /// Documentation: <see href="https://kybernetik.com.au/animancer/docs/manual/fsm/keys">Keyed State Machines</see>
  51. /// </remarks>
  52. /// https://kybernetik.com.au/animancer/api/Animancer.FSM/StateMachine_2
  53. ///
  54. [HelpURL(StateExtensions.APIDocumentationURL + nameof(StateMachine<TState>) + "_2")]
  55. [Serializable]
  56. public partial class StateMachine<TKey, TState> : StateMachine<TState>, IKeyedStateMachine<TKey>, IDictionary<TKey, TState>
  57. where TState : class, IState
  58. {
  59. /************************************************************************************************************************/
  60. /// <summary>The collection of states mapped to a particular key.</summary>
  61. public IDictionary<TKey, TState> Dictionary { get; set; }
  62. /************************************************************************************************************************/
  63. [SerializeField]
  64. private TKey _CurrentKey;
  65. /// <summary>The key which identifies the <see cref="StateMachine{TState}.CurrentState"/>.</summary>
  66. public TKey CurrentKey => _CurrentKey;
  67. /************************************************************************************************************************/
  68. /// <summary>The <see cref="KeyChange{TKey}.PreviousKey"/>.</summary>
  69. public TKey PreviousKey => KeyChange<TKey>.PreviousKey;
  70. /// <summary>The <see cref="KeyChange{TKey}.NextKey"/>.</summary>
  71. public TKey NextKey => KeyChange<TKey>.NextKey;
  72. /************************************************************************************************************************/
  73. /// <summary>
  74. /// Creates a new <see cref="StateMachine{TKey, TState}"/> with a new <see cref="Dictionary"/>, leaving the
  75. /// <see cref="CurrentState"/> null.
  76. /// </summary>
  77. public StateMachine()
  78. {
  79. Dictionary = new Dictionary<TKey, TState>();
  80. }
  81. /// <summary>
  82. /// Creates a new <see cref="StateMachine{TKey, TState}"/> which uses the specified `dictionary`, leaving the
  83. /// <see cref="CurrentState"/> null.
  84. /// </summary>
  85. public StateMachine(IDictionary<TKey, TState> dictionary)
  86. {
  87. Dictionary = dictionary;
  88. }
  89. /// <summary>
  90. /// Constructs a new <see cref="StateMachine{TKey, TState}"/> with a new <see cref="Dictionary"/> and
  91. /// immediately uses the `defaultKey` to enter the `defaultState`.
  92. /// </summary>
  93. /// <remarks>This calls <see cref="IState.OnEnterState"/> but not <see cref="IState.CanEnterState"/>.</remarks>
  94. public StateMachine(TKey defaultKey, TState defaultState)
  95. {
  96. Dictionary = new Dictionary<TKey, TState>
  97. {
  98. { defaultKey, defaultState }
  99. };
  100. ForceSetState(defaultKey, defaultState);
  101. }
  102. /// <summary>
  103. /// Constructs a new <see cref="StateMachine{TKey, TState}"/> which uses the specified `dictionary` and
  104. /// immediately uses the `defaultKey` to enter the `defaultState`.
  105. /// </summary>
  106. /// <remarks>This calls <see cref="IState.OnEnterState"/> but not <see cref="IState.CanEnterState"/>.</remarks>
  107. public StateMachine(IDictionary<TKey, TState> dictionary, TKey defaultKey, TState defaultState)
  108. {
  109. Dictionary = dictionary;
  110. dictionary.Add(defaultKey, defaultState);
  111. ForceSetState(defaultKey, defaultState);
  112. }
  113. /************************************************************************************************************************/
  114. /// <inheritdoc/>
  115. public override void InitializeAfterDeserialize()
  116. {
  117. if (CurrentState != null)
  118. {
  119. using (new KeyChange<TKey>(this, default, _CurrentKey))
  120. using (new StateChange<TState>(this, null, CurrentState))
  121. CurrentState.OnEnterState();
  122. }
  123. else if (Dictionary.TryGetValue(_CurrentKey, out var state))
  124. {
  125. ForceSetState(_CurrentKey, state);
  126. }
  127. // Don't call the base method.
  128. }
  129. /************************************************************************************************************************/
  130. /// <summary>Attempts to enter the specified `state` and returns true if successful.</summary>
  131. /// <remarks>
  132. /// This method returns true immediately if the specified `state` is already the
  133. /// <see cref="StateMachine{TState}.CurrentState"/>. To allow directly re-entering the same state, use
  134. /// <see cref="TryResetState(TKey, TState)"/> instead.
  135. /// </remarks>
  136. public bool TrySetState(TKey key, TState state)
  137. {
  138. if (CurrentState == state)
  139. return true;
  140. else
  141. return TryResetState(key, state);
  142. }
  143. /// <summary>Attempts to enter the state registered with the specified `key` and returns it if successful.</summary>
  144. /// <remarks>
  145. /// This method returns true immediately if the specified `key` is already the <see cref="CurrentKey"/>. To
  146. /// allow directly re-entering the same state, use <see cref="TryResetState(TKey)"/> instead.
  147. /// </remarks>
  148. public TState TrySetState(TKey key)
  149. {
  150. if (EqualityComparer<TKey>.Default.Equals(_CurrentKey, key))
  151. return CurrentState;
  152. else
  153. return TryResetState(key);
  154. }
  155. /// <inheritdoc/>
  156. object IKeyedStateMachine<TKey>.TrySetState(TKey key) => TrySetState(key);
  157. /************************************************************************************************************************/
  158. /// <summary>Attempts to enter the specified `state` and returns true if successful.</summary>
  159. /// <remarks>
  160. /// This method does not check if the `state` is already the <see cref="StateMachine{TState}.CurrentState"/>.
  161. /// To do so, use <see cref="TrySetState(TKey, TState)"/> instead.
  162. /// </remarks>
  163. public bool TryResetState(TKey key, TState state)
  164. {
  165. using (new KeyChange<TKey>(this, _CurrentKey, key))
  166. {
  167. if (!CanSetState(state))
  168. return false;
  169. _CurrentKey = key;
  170. ForceSetState(state);
  171. return true;
  172. }
  173. }
  174. /// <summary>Attempts to enter the state registered with the specified `key` and returns it if successful.</summary>
  175. /// <remarks>
  176. /// This method does not check if the `key` is already the <see cref="CurrentKey"/>. To do so, use
  177. /// <see cref="TrySetState(TKey)"/> instead.
  178. /// </remarks>
  179. public TState TryResetState(TKey key)
  180. {
  181. if (Dictionary.TryGetValue(key, out var state) &&
  182. TryResetState(key, state))
  183. return state;
  184. else
  185. return null;
  186. }
  187. /// <inheritdoc/>
  188. object IKeyedStateMachine<TKey>.TryResetState(TKey key) => TryResetState(key);
  189. /************************************************************************************************************************/
  190. /// <summary>
  191. /// Calls <see cref="IState.OnExitState"/> on the <see cref="StateMachine{TState}.CurrentState"/> then changes
  192. /// to the specified `key` and `state` and calls <see cref="IState.OnEnterState"/> on it.
  193. /// </summary>
  194. /// <remarks>
  195. /// This method does not check <see cref="IState.CanExitState"/> or <see cref="IState.CanEnterState"/>. To do
  196. /// that, you should use <see cref="TrySetState(TKey, TState)"/> instead.
  197. /// </remarks>
  198. public void ForceSetState(TKey key, TState state)
  199. {
  200. using (new KeyChange<TKey>(this, _CurrentKey, key))
  201. {
  202. _CurrentKey = key;
  203. ForceSetState(state);
  204. }
  205. }
  206. /// <summary>
  207. /// Uses <see cref="ForceSetState(TKey, TState)"/> to change to the state registered with the `key`. If nothing
  208. /// is registered, it use <c>null</c> and will throw an exception unless
  209. /// <see cref="StateMachine{TState}.AllowNullStates"/> is enabled.
  210. /// </summary>
  211. public TState ForceSetState(TKey key)
  212. {
  213. Dictionary.TryGetValue(key, out var state);
  214. ForceSetState(key, state);
  215. return state;
  216. }
  217. /// <inheritdoc/>
  218. object IKeyedStateMachine<TKey>.ForceSetState(TKey key) => ForceSetState(key);
  219. /************************************************************************************************************************/
  220. #region Dictionary Wrappers
  221. /************************************************************************************************************************/
  222. /// <summary>The state registered with the `key` in the <see cref="Dictionary"/>.</summary>
  223. public TState this[TKey key] { get => Dictionary[key]; set => Dictionary[key] = value; }
  224. /// <summary>Gets the state registered with the specified `key` in the <see cref="Dictionary"/>.</summary>
  225. public bool TryGetValue(TKey key, out TState state) => Dictionary.TryGetValue(key, out state);
  226. /************************************************************************************************************************/
  227. /// <summary>Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="Dictionary"/>.</summary>
  228. public ICollection<TKey> Keys => Dictionary.Keys;
  229. /// <summary>Gets an <see cref="ICollection{T}"/> containing the state of the <see cref="Dictionary"/>.</summary>
  230. public ICollection<TState> Values => Dictionary.Values;
  231. /************************************************************************************************************************/
  232. /// <summary>Gets the number of states contained in the <see cref="Dictionary"/>.</summary>
  233. public int Count => Dictionary.Count;
  234. /************************************************************************************************************************/
  235. /// <summary>Adds a state to the <see cref="Dictionary"/>.</summary>
  236. public void Add(TKey key, TState state) => Dictionary.Add(key, state);
  237. /// <summary>Adds a state to the <see cref="Dictionary"/>.</summary>
  238. public void Add(KeyValuePair<TKey, TState> item) => Dictionary.Add(item);
  239. /************************************************************************************************************************/
  240. /// <summary>Removes a state from the <see cref="Dictionary"/>.</summary>
  241. public bool Remove(TKey key) => Dictionary.Remove(key);
  242. /// <summary>Removes a state from the <see cref="Dictionary"/>.</summary>
  243. public bool Remove(KeyValuePair<TKey, TState> item) => Dictionary.Remove(item);
  244. /************************************************************************************************************************/
  245. /// <summary>Removes all state from the <see cref="Dictionary"/>.</summary>
  246. public void Clear() => Dictionary.Clear();
  247. /************************************************************************************************************************/
  248. /// <summary>Determines whether the <see cref="Dictionary"/> contains a specific value.</summary>
  249. public bool Contains(KeyValuePair<TKey, TState> item) => Dictionary.Contains(item);
  250. /// <summary>Determines whether the <see cref="Dictionary"/> contains a state with the specified `key`.</summary>
  251. public bool ContainsKey(TKey key) => Dictionary.ContainsKey(key);
  252. /************************************************************************************************************************/
  253. /// <summary>Returns an enumerator that iterates through the <see cref="Dictionary"/>.</summary>
  254. public IEnumerator<KeyValuePair<TKey, TState>> GetEnumerator() => Dictionary.GetEnumerator();
  255. /// <summary>Returns an enumerator that iterates through the <see cref="Dictionary"/>.</summary>
  256. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  257. /************************************************************************************************************************/
  258. /// <summary>Copies the contents of the <see cref="Dictionary"/> to the `array` starting at the `arrayIndex`.</summary>
  259. public void CopyTo(KeyValuePair<TKey, TState>[] array, int arrayIndex) => Dictionary.CopyTo(array, arrayIndex);
  260. /************************************************************************************************************************/
  261. /// <summary>Indicates whether the <see cref="Dictionary"/> is read-only.</summary>
  262. bool ICollection<KeyValuePair<TKey, TState>>.IsReadOnly => Dictionary.IsReadOnly;
  263. /************************************************************************************************************************/
  264. #endregion
  265. /************************************************************************************************************************/
  266. /// <summary>Returns the state registered with the specified `key`, or null if none is present.</summary>
  267. public TState GetState(TKey key)
  268. {
  269. TryGetValue(key, out var state);
  270. return state;
  271. }
  272. /************************************************************************************************************************/
  273. /// <summary>Adds the specified `keys` and `states`. Both arrays must be the same size.</summary>
  274. public void AddRange(TKey[] keys, TState[] states)
  275. {
  276. Debug.Assert(keys.Length == states.Length,
  277. $"The '{nameof(keys)}' and '{nameof(states)}' arrays must be the same size.");
  278. for (int i = 0; i < keys.Length; i++)
  279. {
  280. Dictionary.Add(keys[i], states[i]);
  281. }
  282. }
  283. /************************************************************************************************************************/
  284. /// <summary>
  285. /// Sets the <see cref="CurrentKey"/> without changing the <see cref="StateMachine{TState}.CurrentState"/>.
  286. /// </summary>
  287. public void SetFakeKey(TKey key) => _CurrentKey = key;
  288. /************************************************************************************************************************/
  289. /// <summary>
  290. /// Returns a string describing the type of this state machine and its <see cref="CurrentKey"/> and
  291. /// <see cref="StateMachine{TState}.CurrentState"/>.
  292. /// </summary>
  293. public override string ToString()
  294. => $"{GetType().FullName} -> {_CurrentKey} -> {(CurrentState != null ? CurrentState.ToString() : "null")}";
  295. /************************************************************************************************************************/
  296. #if UNITY_EDITOR
  297. /************************************************************************************************************************/
  298. /// <inheritdoc/>
  299. public override int GUILineCount => 2;
  300. /************************************************************************************************************************/
  301. /// <inheritdoc/>
  302. public override void DoGUI(ref Rect area)
  303. {
  304. area.height = UnityEditor.EditorGUIUtility.singleLineHeight;
  305. UnityEditor.EditorGUI.BeginChangeCheck();
  306. var key = StateMachineUtilities.DoGenericField(area, "Current Key", _CurrentKey);
  307. if (UnityEditor.EditorGUI.EndChangeCheck())
  308. SetFakeKey(key);
  309. StateMachineUtilities.NextVerticalArea(ref area);
  310. base.DoGUI(ref area);
  311. }
  312. /************************************************************************************************************************/
  313. #endif
  314. /************************************************************************************************************************/
  315. }
  316. }