AnimancerUtilities.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. // Animancer // https://kybernetik.com.au/animancer // Copyright 2018-2024 Kybernetik //
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using System.Text;
  7. using Unity.Collections;
  8. using UnityEngine;
  9. using UnityEngine.Animations;
  10. using UnityEngine.Playables;
  11. using Object = UnityEngine.Object;
  12. namespace Animancer
  13. {
  14. /// <summary>Various extension methods and utilities.</summary>
  15. /// https://kybernetik.com.au/animancer/api/Animancer/AnimancerUtilities
  16. ///
  17. public static partial class AnimancerUtilities
  18. {
  19. /************************************************************************************************************************/
  20. #region Misc
  21. /************************************************************************************************************************/
  22. /// <summary>This is Animancer Pro.</summary>
  23. public const bool IsAnimancerPro = true;
  24. /************************************************************************************************************************/
  25. /// <summary>
  26. /// If `obj` exists, this method returns <see cref="object.ToString"/>.
  27. /// Or if it is <c>null</c>, this method returns <c>"Null"</c>.
  28. /// Or if it is an <see cref="Object"/> that has been destroyed, this method returns <c>"Null (ObjectType)"</c>.
  29. /// </summary>
  30. public static string ToStringOrNull(object obj)
  31. {
  32. if (obj == null)
  33. return "Null";
  34. if (obj is Object unityObject && unityObject == null)
  35. return $"Null ({obj.GetType()})";
  36. return obj.ToString();
  37. }
  38. /************************************************************************************************************************/
  39. /// <summary>[Animancer Extension]
  40. /// Is the `node` is not null and its <see cref="AnimancerNodeBase.Playable"/> valid?
  41. /// </summary>
  42. public static bool IsValid(this AnimancerNode node)
  43. => node != null
  44. && node.Playable.IsValid();
  45. /************************************************************************************************************************/
  46. /// <summary>[Animancer Extension] Calls <see cref="ITransition.CreateState"/> and <see cref="ITransition.Apply"/>.</summary>
  47. public static AnimancerState CreateStateAndApply(this ITransition transition, AnimancerGraph graph = null)
  48. {
  49. var state = transition.CreateState();
  50. state.SetGraph(graph);
  51. transition.Apply(state);
  52. return state;
  53. }
  54. /************************************************************************************************************************/
  55. /// <summary>
  56. /// If the `key` is an <see cref="AnimancerState"/>,
  57. /// this method gets its <see cref="AnimancerState.Key"/>
  58. /// and repeats that check until it finds another kind of key, which it returns.
  59. /// </summary>
  60. public static object GetRootKey(object key)
  61. {
  62. while (key is AnimancerState state)
  63. {
  64. var stateKey = state.Key;
  65. if (stateKey == null)
  66. break;
  67. key = stateKey;
  68. }
  69. return key;
  70. }
  71. /// <summary>
  72. /// If a state is registered with the `key`, this method gets it and repeats that check then returns the last
  73. /// state found.
  74. /// </summary>
  75. public static object GetLastKey(AnimancerStateDictionary states, object key)
  76. {
  77. while (states.TryGet(key, out var state))
  78. key = state;
  79. return key;
  80. }
  81. /************************************************************************************************************************/
  82. /// <summary>
  83. /// Calls <see cref="PlayableGraph.Connect{U, V}(U, int, V, int)"/> using output 0 from the `child` and
  84. /// <see cref="PlayableExtensions.SetInputWeight{U}(U, int, float)"/>.
  85. /// </summary>
  86. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  87. public static void Connect<TParent, TChild>(
  88. this PlayableGraph graph,
  89. TParent parent,
  90. TChild child,
  91. int parentInputIndex,
  92. float weight)
  93. where TParent : struct, IPlayable
  94. where TChild : struct, IPlayable
  95. {
  96. graph.Connect(child, 0, parent, parentInputIndex);
  97. parent.SetInputWeight(parentInputIndex, weight);
  98. }
  99. /************************************************************************************************************************/
  100. /// <summary>Applies the `child`'s current <see cref="AnimancerNode.Weight"/>.</summary>
  101. public static void ApplyChildWeight(this Playable parent, AnimancerNode child)
  102. => parent.SetInputWeight(child.Index, child.Weight);
  103. /// <summary>
  104. /// Sets and applies the `child`'s <see cref="AnimancerNode.Weight"/>
  105. /// and <see cref="AnimancerState.IsActive"/>.
  106. /// </summary>
  107. public static void SetChildWeight(this Playable parent, AnimancerState child, float weight)
  108. {
  109. if (child._Weight == weight)
  110. return;
  111. Validate.AssertSetWeight(child, weight);
  112. child._Weight = weight;
  113. child.ShouldBeActive = weight > 0 || child.IsPlaying;
  114. parent.SetInputWeight(child.Index, weight);
  115. }
  116. /************************************************************************************************************************/
  117. /// <summary>[Pro-Only] Reconnects the input of the specified `playable` to its output.</summary>
  118. public static void RemovePlayable(Playable playable, bool destroy = true)
  119. {
  120. if (!playable.IsValid())
  121. return;
  122. Assert(playable.GetInputCount() == 1,
  123. $"{nameof(RemovePlayable)} can only be used on playables with 1 input.");
  124. Assert(playable.GetOutputCount() == 1,
  125. $"{nameof(RemovePlayable)} can only be used on playables with 1 output.");
  126. var input = playable.GetInput(0);
  127. if (!input.IsValid())
  128. {
  129. if (destroy)
  130. playable.Destroy();
  131. return;
  132. }
  133. var graph = playable.GetGraph();
  134. var output = playable.GetOutput(0);
  135. if (output.IsValid())// Connected to another Playable.
  136. {
  137. if (destroy)
  138. {
  139. playable.Destroy();
  140. }
  141. else
  142. {
  143. Assert(output.GetInputCount() == 1,
  144. $"{nameof(RemovePlayable)} can only be used on playables connected to a playable with 1 input.");
  145. graph.Disconnect(output, 0);
  146. graph.Disconnect(playable, 0);
  147. }
  148. graph.Connect(input, 0, output, 0);
  149. }
  150. else// Connected to the graph output.
  151. {
  152. var playableOutput = graph.FindOutput(playable);
  153. if (playableOutput.IsOutputValid())
  154. playableOutput.SetSourcePlayable(input);
  155. if (destroy)
  156. playable.Destroy();
  157. else
  158. graph.Disconnect(playable, 0);
  159. }
  160. }
  161. /************************************************************************************************************************/
  162. /// <summary>Returns the output connected to the `sourcePlayable` (if any).</summary>
  163. public static PlayableOutput FindOutput(this PlayableGraph graph, Playable sourcePlayable)
  164. {
  165. var handle = sourcePlayable.GetHandle();
  166. var outputCount = graph.GetOutputCount();
  167. for (int i = outputCount - 1; i >= 0; i--)
  168. {
  169. var output = graph.GetOutput(i);
  170. if (output.GetSourcePlayable().GetHandle() == handle)
  171. return output;
  172. }
  173. return default;
  174. }
  175. /************************************************************************************************************************/
  176. /// <summary>
  177. /// Checks if any <see cref="AnimationClip"/> in the `source` has an animation event with the specified
  178. /// `functionName`.
  179. /// </summary>
  180. public static bool HasEvent(IAnimationClipCollection source, string functionName)
  181. {
  182. var clips = SetPool.Acquire<AnimationClip>();
  183. source.GatherAnimationClips(clips);
  184. foreach (var clip in clips)
  185. {
  186. if (HasEvent(clip, functionName))
  187. {
  188. SetPool.Release(clips);
  189. return true;
  190. }
  191. }
  192. SetPool.Release(clips);
  193. return false;
  194. }
  195. /// <summary>Checks if the `clip` has an animation event with the specified `functionName`.</summary>
  196. public static bool HasEvent(AnimationClip clip, string functionName)
  197. {
  198. var events = clip.events;
  199. for (int i = events.Length - 1; i >= 0; i--)
  200. {
  201. if (events[i].functionName == functionName)
  202. return true;
  203. }
  204. return false;
  205. }
  206. /************************************************************************************************************************/
  207. /// <summary>[Animancer Extension] [Pro-Only]
  208. /// Calculates all thresholds in the `mixer` using the <see cref="AnimancerState.AverageVelocity"/> of each
  209. /// state on the X and Z axes.
  210. /// <para></para>
  211. /// Note that this method requires the <c>Root Transform Position (XZ) -> Bake Into Pose</c> toggle to be
  212. /// disabled in the Import Settings of each <see cref="AnimationClip"/> in the mixer.
  213. /// </summary>
  214. public static void CalculateThresholdsFromAverageVelocityXZ(this MixerState<Vector2> mixer)
  215. {
  216. mixer.ValidateThresholdCount();
  217. for (int i = mixer.ChildCount - 1; i >= 0; i--)
  218. {
  219. var state = mixer.GetChild(i);
  220. if (state == null)
  221. continue;
  222. var averageVelocity = state.AverageVelocity;
  223. mixer.SetThreshold(i, new(averageVelocity.x, averageVelocity.z));
  224. }
  225. }
  226. /************************************************************************************************************************/
  227. /// <summary>
  228. /// Creates a <see cref="NativeArray{T}"/> containing a single element so that it can be used like a reference
  229. /// in Unity's C# Job system which does not allow regular reference types.
  230. /// </summary>
  231. /// <remarks>Note that you must call <see cref="NativeArray{T}.Dispose()"/> when you're done with the array.</remarks>
  232. public static NativeArray<T> CreateNativeReference<T>()
  233. where T : struct
  234. => new(1, Allocator.Persistent, NativeArrayOptions.ClearMemory);
  235. /************************************************************************************************************************/
  236. /// <summary>
  237. /// Creates a <see cref="NativeArray{T}"/> of <see cref="TransformStreamHandle"/>s for each of the `transforms`.
  238. /// </summary>
  239. /// <remarks>Note that you must call <see cref="NativeArray{T}.Dispose()"/> when you're done with the array.</remarks>
  240. public static NativeArray<TransformStreamHandle> ConvertToTransformStreamHandles(
  241. IList<Transform> transforms, Animator animator)
  242. {
  243. var count = transforms.Count;
  244. var boneHandles = new NativeArray<TransformStreamHandle>(
  245. count, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
  246. for (int i = 0; i < count; i++)
  247. boneHandles[i] = animator.BindStreamTransform(transforms[i]);
  248. return boneHandles;
  249. }
  250. /************************************************************************************************************************/
  251. /// <summary>Returns a string stating that the `value` is unsupported.</summary>
  252. public static string GetUnsupportedMessage<T>(T value)
  253. => $"Unsupported {typeof(T).FullName}: {value}";
  254. /// <summary>Returns an exception stating that the `value` is unsupported.</summary>
  255. public static ArgumentException CreateUnsupportedArgumentException<T>(T value)
  256. => new(GetUnsupportedMessage(value));
  257. /************************************************************************************************************************/
  258. #endregion
  259. /************************************************************************************************************************/
  260. #region Collections
  261. /************************************************************************************************************************/
  262. /// <summary>
  263. /// If the `index` is within the `list`,
  264. /// this method outputs the `item` at that `index` and returns true.
  265. /// </summary>
  266. public static bool TryGet<T>(this IList<T> list, int index, out T item)
  267. {
  268. if ((uint)index < (uint)list.Count)
  269. {
  270. item = list[index];
  271. return true;
  272. }
  273. else
  274. {
  275. item = default;
  276. return false;
  277. }
  278. }
  279. /************************************************************************************************************************/
  280. /// <summary>
  281. /// If the `index` is within the `list` and that `item` is not null,
  282. /// this method outputs it and returns true.
  283. /// </summary>
  284. public static bool TryGetObject<T>(this IList<T> list, int index, out T item)
  285. where T : Object
  286. {
  287. if (list.TryGet(index, out item) &&
  288. item != null)
  289. return true;
  290. item = default;
  291. return false;
  292. }
  293. /************************************************************************************************************************/
  294. /// <summary>
  295. /// If the `obj` is a <see cref="Component"/> or <see cref="GameObject"/>,
  296. /// this method outputs its `transform` and returns true.
  297. /// </summary>
  298. public static bool TryGetTransform(Object obj, out Transform transform)
  299. {
  300. if (obj is Component component)
  301. {
  302. transform = component.transform;
  303. return true;
  304. }
  305. else if (obj is GameObject gameObject)
  306. {
  307. transform = gameObject.transform;
  308. return true;
  309. }
  310. else
  311. {
  312. transform = null;
  313. return false;
  314. }
  315. }
  316. /************************************************************************************************************************/
  317. /// <summary>Ensures that the length and contents of `copyTo` match `copyFrom`.</summary>
  318. public static void CopyExactArray<T>(T[] copyFrom, ref T[] copyTo)
  319. {
  320. if (copyFrom == null)
  321. {
  322. copyTo = null;
  323. return;
  324. }
  325. var length = copyFrom.Length;
  326. SetLength(ref copyTo, length);
  327. Array.Copy(copyFrom, copyTo, length);
  328. }
  329. /************************************************************************************************************************/
  330. /// <summary>[Animancer Extension] Swaps <c>array[a]</c> with <c>array[b]</c>.</summary>
  331. public static void Swap<T>(this T[] array, int a, int b)
  332. => (array[b], array[a]) = (array[a], array[b]);
  333. /************************************************************************************************************************/
  334. /// <summary>Are both lists the same size with the same items in the same order?</summary>
  335. public static bool ContentsAreEqual<T>(IList<T> a, IList<T> b)
  336. {
  337. if (a == null)
  338. return b == null;
  339. if (b == null)
  340. return false;
  341. var aCount = a.Count;
  342. var bCount = b.Count;
  343. if (aCount != bCount)
  344. return false;
  345. for (int i = 0; i < aCount; i++)
  346. if (!EqualityComparer<T>.Default.Equals(a[i], b[i]))
  347. return false;
  348. return true;
  349. }
  350. /************************************************************************************************************************/
  351. /// <summary>[Animancer Extension]
  352. /// Is the `array` <c>null</c> or its <see cref="Array.Length"/> <c>0</c>?
  353. /// </summary>
  354. public static bool IsNullOrEmpty<T>(this T[] array)
  355. => array == null
  356. || array.Length == 0;
  357. /************************************************************************************************************************/
  358. /// <summary>
  359. /// If the `array` is <c>null</c> or its <see cref="Array.Length"/> isn't equal to the specified `length`, this
  360. /// method creates a new array with that `length` and returns <c>true</c>. Otherwise, it returns <c>false</c>
  361. /// and the array us unchanged.
  362. /// </summary>
  363. /// <remarks>
  364. /// Unlike <see cref="Array.Resize{T}(ref T[], int)"/>, this method doesn't copy over the contents of the old
  365. /// `array` into the new one.
  366. /// </remarks>
  367. public static bool SetLength<T>(ref T[] array, int length)
  368. {
  369. if (array != null && array.Length == length)
  370. return false;
  371. array = new T[length];
  372. return true;
  373. }
  374. /************************************************************************************************************************/
  375. /// <summary>Resizes the `array` to be at least 1 larger and inserts the `item` at the specified `index`.</summary>
  376. /// <remarks>If the `index` is beyond the end of the array, it will be resized large enough to fit.</remarks>
  377. public static void InsertAt<T>(ref T[] array, int index, T item)
  378. {
  379. if (array == null)
  380. {
  381. array = new T[] { item };
  382. }
  383. else if (index >= array.Length)
  384. {
  385. Array.Resize(ref array, index + 1);
  386. array[index] = item;
  387. }
  388. else
  389. {
  390. var newArray = new T[array.Length + 1];
  391. Array.Copy(array, 0, newArray, 0, index);
  392. Array.Copy(array, index, newArray, index + 1, array.Length - index);
  393. newArray[index] = item;
  394. array = newArray;
  395. }
  396. }
  397. /************************************************************************************************************************/
  398. /// <summary>Removes the item at the specified `index` and resizes the `array` to be 1 smaller.</summary>
  399. public static void RemoveAt<T>(ref T[] array, int index)
  400. {
  401. if (array == null ||
  402. array.Length == 0)
  403. return;
  404. var newArray = new T[array.Length - 1];
  405. Array.Copy(array, 0, newArray, 0, index);
  406. Array.Copy(array, index + 1, newArray, index, array.Length - index - 1);
  407. array = newArray;
  408. }
  409. /************************************************************************************************************************/
  410. /// <summary>Returns the `array`, or <see cref="Array.Empty{T}"/> if it was <c>null</c>.</summary>
  411. public static T[] NullIsEmpty<T>(this T[] array)
  412. => array
  413. ?? Array.Empty<T>();
  414. /************************************************************************************************************************/
  415. /// <summary>Returns a string containing the value of each element in `collection`.</summary>
  416. public static string DeepToString(
  417. this IEnumerable collection,
  418. string separator,
  419. Func<object, object> toString = null)
  420. {
  421. if (collection == null)
  422. return "null";
  423. else
  424. return DeepToString(collection.GetEnumerator(), separator, toString);
  425. }
  426. /// <summary>Returns a string containing the value of each element in `collection` (each on a new line).</summary>
  427. public static string DeepToString(
  428. this IEnumerable collection,
  429. Func<object, object> toString = null)
  430. => DeepToString(collection, Environment.NewLine, toString);
  431. /// <summary>Returns a string containing the value of each element in `enumerator`.</summary>
  432. public static string DeepToString(
  433. this IEnumerator enumerator,
  434. string separator,
  435. Func<object, object> toString = null)
  436. {
  437. var text = StringBuilderPool.Instance.Acquire();
  438. AppendDeepToString(text, enumerator, separator, toString);
  439. return text.ReleaseToString();
  440. }
  441. /// <summary>Returns a string containing the value of each element in `enumerator` (each on a new line).</summary>
  442. public static string DeepToString(
  443. this IEnumerator enumerator,
  444. Func<object, object> toString = null)
  445. => DeepToString(enumerator, Environment.NewLine, toString);
  446. /************************************************************************************************************************/
  447. /// <summary>Each element returned by `enumerator` is appended to `text`.</summary>
  448. public static void AppendDeepToString(
  449. StringBuilder text,
  450. IEnumerator enumerator,
  451. string separator,
  452. Func<object, object> toString = null)
  453. {
  454. text.Append("[]");
  455. var countIndex = text.Length - 1;
  456. var count = 0;
  457. while (enumerator.MoveNext())
  458. {
  459. text.Append(separator);
  460. text.Append('[');
  461. text.Append(count);
  462. text.Append("] = ");
  463. var value = enumerator.Current;
  464. if (toString != null)
  465. value = toString(value);
  466. text.Append(ToStringOrNull(value));
  467. count++;
  468. }
  469. text.Insert(countIndex, count);
  470. }
  471. /************************************************************************************************************************/
  472. /// <summary>Returns the value registered in the `dictionary` using the `key`.</summary>
  473. /// <remarks>Returns <c>default</c>(<typeparamref name="TValue"/>) if nothing was registered.</remarks>
  474. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  475. public static TValue Get<TKey, TValue>(
  476. this Dictionary<TKey, TValue> dictionary,
  477. TKey key)
  478. {
  479. dictionary.TryGetValue(key, out var value);
  480. return value;
  481. }
  482. /// <summary>Registers the `value` in the `dictionary` using the `key`, replacing any previous value.</summary>
  483. /// <remarks>
  484. /// This is identical to setting <c>dictionary[key] = value;</c>
  485. /// except the syntax matches <c>dictionary.Add(key, value);</c>.
  486. /// </remarks>
  487. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  488. public static void Set<TKey, TValue>(
  489. this Dictionary<TKey, TValue> dictionary,
  490. TKey key,
  491. TValue value)
  492. => dictionary[key] = value;
  493. /************************************************************************************************************************/
  494. /// <summary>Removes any items from the `dictionary` that use destroyed objects as their key.</summary>
  495. public static void RemoveDestroyedObjects<TKey, TValue>(Dictionary<TKey, TValue> dictionary)
  496. where TKey : Object
  497. {
  498. using (ListPool<TKey>.Instance.Acquire(out var oldObjects))
  499. {
  500. foreach (var obj in dictionary.Keys)
  501. if (obj == null)
  502. oldObjects.Add(obj);
  503. for (int i = 0; i < oldObjects.Count; i++)
  504. dictionary.Remove(oldObjects[i]);
  505. }
  506. }
  507. /// <summary>
  508. /// Creates a new dictionary and returns true if it was null or calls <see cref="RemoveDestroyedObjects"/> and
  509. /// returns false if it wasn't.
  510. /// </summary>
  511. public static bool InitializeCleanDictionary<TKey, TValue>(ref Dictionary<TKey, TValue> dictionary)
  512. where TKey : Object
  513. {
  514. if (dictionary == null)
  515. {
  516. dictionary = new();
  517. return true;
  518. }
  519. else
  520. {
  521. RemoveDestroyedObjects(dictionary);
  522. return false;
  523. }
  524. }
  525. /************************************************************************************************************************/
  526. #endregion
  527. /************************************************************************************************************************/
  528. #region Animator Controllers
  529. /************************************************************************************************************************/
  530. /// <summary>Copies the value of the `parameter` from `copyFrom` to `copyTo`.</summary>
  531. public static void CopyParameterValue(Animator copyFrom, Animator copyTo, AnimatorControllerParameter parameter)
  532. {
  533. switch (parameter.type)
  534. {
  535. case AnimatorControllerParameterType.Float:
  536. copyTo.SetFloat(parameter.nameHash, copyFrom.GetFloat(parameter.nameHash));
  537. break;
  538. case AnimatorControllerParameterType.Int:
  539. copyTo.SetInteger(parameter.nameHash, copyFrom.GetInteger(parameter.nameHash));
  540. break;
  541. case AnimatorControllerParameterType.Bool:
  542. case AnimatorControllerParameterType.Trigger:
  543. copyTo.SetBool(parameter.nameHash, copyFrom.GetBool(parameter.nameHash));
  544. break;
  545. default:
  546. throw CreateUnsupportedArgumentException(parameter.type);
  547. }
  548. }
  549. /// <summary>Copies the value of the `parameter` from `copyFrom` to `copyTo`.</summary>
  550. public static void CopyParameterValue(AnimatorControllerPlayable copyFrom, AnimatorControllerPlayable copyTo, AnimatorControllerParameter parameter)
  551. {
  552. switch (parameter.type)
  553. {
  554. case AnimatorControllerParameterType.Float:
  555. copyTo.SetFloat(parameter.nameHash, copyFrom.GetFloat(parameter.nameHash));
  556. break;
  557. case AnimatorControllerParameterType.Int:
  558. copyTo.SetInteger(parameter.nameHash, copyFrom.GetInteger(parameter.nameHash));
  559. break;
  560. case AnimatorControllerParameterType.Bool:
  561. case AnimatorControllerParameterType.Trigger:
  562. copyTo.SetBool(parameter.nameHash, copyFrom.GetBool(parameter.nameHash));
  563. break;
  564. default:
  565. throw CreateUnsupportedArgumentException(parameter.type);
  566. }
  567. }
  568. /************************************************************************************************************************/
  569. /// <summary>Gets the value of the `parameter` in the `animator`.</summary>
  570. public static object GetParameterValue(Animator animator, AnimatorControllerParameter parameter)
  571. {
  572. return parameter.type switch
  573. {
  574. AnimatorControllerParameterType.Float => animator.GetFloat(parameter.nameHash),
  575. AnimatorControllerParameterType.Int => animator.GetInteger(parameter.nameHash),
  576. AnimatorControllerParameterType.Bool or
  577. AnimatorControllerParameterType.Trigger => animator.GetBool(parameter.nameHash),
  578. _ => throw CreateUnsupportedArgumentException(parameter.type),
  579. };
  580. }
  581. /// <summary>Gets the value of the `parameter` in the `playable`.</summary>
  582. public static object GetParameterValue(AnimatorControllerPlayable playable, AnimatorControllerParameter parameter)
  583. {
  584. return parameter.type switch
  585. {
  586. AnimatorControllerParameterType.Float => playable.GetFloat(parameter.nameHash),
  587. AnimatorControllerParameterType.Int => playable.GetInteger(parameter.nameHash),
  588. AnimatorControllerParameterType.Bool or
  589. AnimatorControllerParameterType.Trigger => playable.GetBool(parameter.nameHash),
  590. _ => throw CreateUnsupportedArgumentException(parameter.type),
  591. };
  592. }
  593. /************************************************************************************************************************/
  594. /// <summary>Sets the `value` of the `parameter` in the `animator`.</summary>
  595. public static void SetParameterValue(Animator animator, AnimatorControllerParameter parameter, object value)
  596. {
  597. switch (parameter.type)
  598. {
  599. case AnimatorControllerParameterType.Float:
  600. animator.SetFloat(parameter.nameHash, (float)value);
  601. break;
  602. case AnimatorControllerParameterType.Int:
  603. animator.SetInteger(parameter.nameHash, (int)value);
  604. break;
  605. case AnimatorControllerParameterType.Bool:
  606. animator.SetBool(parameter.nameHash, (bool)value);
  607. break;
  608. case AnimatorControllerParameterType.Trigger:
  609. if ((bool)value)
  610. animator.SetTrigger(parameter.nameHash);
  611. else
  612. animator.ResetTrigger(parameter.nameHash);
  613. break;
  614. default:
  615. throw CreateUnsupportedArgumentException(parameter.type);
  616. }
  617. }
  618. /// <summary>Sets the `value` of the `parameter` in the `playable`.</summary>
  619. public static void SetParameterValue(AnimatorControllerPlayable playable, AnimatorControllerParameter parameter, object value)
  620. {
  621. switch (parameter.type)
  622. {
  623. case AnimatorControllerParameterType.Float:
  624. playable.SetFloat(parameter.nameHash, (float)value);
  625. break;
  626. case AnimatorControllerParameterType.Int:
  627. playable.SetInteger(parameter.nameHash, (int)value);
  628. break;
  629. case AnimatorControllerParameterType.Bool:
  630. playable.SetBool(parameter.nameHash, (bool)value);
  631. break;
  632. case AnimatorControllerParameterType.Trigger:
  633. if ((bool)value)
  634. playable.SetTrigger(parameter.nameHash);
  635. else
  636. playable.ResetTrigger(parameter.nameHash);
  637. break;
  638. default:
  639. throw CreateUnsupportedArgumentException(parameter.type);
  640. }
  641. }
  642. /************************************************************************************************************************/
  643. #endregion
  644. /************************************************************************************************************************/
  645. #region Math
  646. /************************************************************************************************************************/
  647. /// <summary>Loops the `value` so that <c>0 &lt;= value &lt; 1</c>.</summary>
  648. /// <remarks>This is more efficient than using <see cref="Wrap"/> with a <c>length</c> of 1.</remarks>
  649. public static float Wrap01(float value)
  650. {
  651. var valueAsDouble = (double)value;
  652. value = (float)(valueAsDouble - Math.Floor(valueAsDouble));
  653. return value < 1
  654. ? value
  655. : 0;
  656. }
  657. /// <summary>Loops the `value` so that <c>0 &lt;= value &lt; length</c>.</summary>
  658. /// <remarks>Unike <see cref="Mathf.Repeat"/>, this method will never return the `length`.</remarks>
  659. public static float Wrap(float value, float length)
  660. {
  661. var valueAsDouble = (double)value;
  662. var lengthAsDouble = (double)length;
  663. value = (float)(valueAsDouble - Math.Floor(valueAsDouble / lengthAsDouble) * lengthAsDouble);
  664. return value < length
  665. ? value
  666. : 0;
  667. }
  668. /************************************************************************************************************************/
  669. /// <summary>
  670. /// Rounds the `value` to the nearest integer using <see cref="MidpointRounding.AwayFromZero"/>.
  671. /// </summary>
  672. public static float Round(float value)
  673. => (float)Math.Round(value, MidpointRounding.AwayFromZero);
  674. /// <summary>
  675. /// Rounds the `value` to be a multiple of the `multiple` using <see cref="MidpointRounding.AwayFromZero"/>.
  676. /// </summary>
  677. public static float Round(float value, float multiple)
  678. => Round(value / multiple) * multiple;
  679. /************************************************************************************************************************/
  680. /// <summary>The opposite of <see cref="Mathf.LerpUnclamped(float, float, float)"/>.</summary>
  681. public static float InverseLerpUnclamped(float a, float b, float value)
  682. {
  683. if (a == b)
  684. return 0;
  685. else
  686. return (value - a) / (b - a);
  687. }
  688. /************************************************************************************************************************/
  689. /// <summary>Are the given values equal or both <see cref="float.NaN"/> (which wouldn't normally be equal)?</summary>
  690. public static bool IsEqualOrBothNaN(this float a, float b)
  691. => a == b
  692. || (float.IsNaN(a) && float.IsNaN(b));
  693. /************************************************************************************************************************/
  694. /// <summary>[Animancer Extension] Is the `value` not NaN or Infinity?</summary>
  695. /// <remarks>Newer versions of the .NET framework apparently have a <c>float.IsFinite</c> method.</remarks>
  696. public static bool IsFinite(this float value)
  697. => !float.IsNaN(value)
  698. && !float.IsInfinity(value);
  699. /// <summary>[Animancer Extension] Is the `value` not NaN or Infinity?</summary>
  700. /// <remarks>Newer versions of the .NET framework apparently have a <c>double.IsFinite</c> method.</remarks>
  701. public static bool IsFinite(this double value)
  702. => !double.IsNaN(value)
  703. && !double.IsInfinity(value);
  704. /// <summary>[Animancer Extension] Are all components of the `value` not NaN or Infinity?</summary>
  705. public static bool IsFinite(this Vector2 value)
  706. => value.x.IsFinite()
  707. && value.y.IsFinite();
  708. /************************************************************************************************************************/
  709. #endregion
  710. /************************************************************************************************************************/
  711. #region Hashing
  712. /************************************************************************************************************************/
  713. /// <summary>Returns a hash value from the given parameters.</summary>
  714. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  715. public static int Hash(int seed, int hash1, int hash2)
  716. {
  717. AddHash(ref seed, hash1);
  718. AddHash(ref seed, hash2);
  719. return seed;
  720. }
  721. /// <summary>Returns a hash value from the given parameters.</summary>
  722. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  723. public static int Hash(int seed, int hash1, int hash2, int hash3)
  724. {
  725. AddHash(ref seed, hash1);
  726. AddHash(ref seed, hash2);
  727. AddHash(ref seed, hash3);
  728. return seed;
  729. }
  730. /// <summary>Returns a hash value from the given parameters.</summary>
  731. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  732. public static int Hash(int seed, int hash1, int hash2, int hash3, int hash4)
  733. {
  734. AddHash(ref seed, hash1);
  735. AddHash(ref seed, hash2);
  736. AddHash(ref seed, hash3);
  737. AddHash(ref seed, hash4);
  738. return seed;
  739. }
  740. /************************************************************************************************************************/
  741. /// <summary>Includes `add` in the `hash`.</summary>
  742. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  743. public static void AddHash(ref int hash, int add)
  744. => hash = hash * -1521134295 + add;
  745. /************************************************************************************************************************/
  746. /// <summary>Uses <see cref="EqualityComparer{T}.Default"/> to get a hash code.</summary>
  747. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  748. public static int SafeGetHashCode<T>(this T value)
  749. => EqualityComparer<T>.Default.GetHashCode(value);
  750. /************************************************************************************************************************/
  751. #endregion
  752. /************************************************************************************************************************/
  753. #region Components
  754. /************************************************************************************************************************/
  755. /// <summary>Is the `obj` <c>null</c> or a destroyed <see cref="Object"/>?</summary>
  756. public static bool IsNullOrDestroyed(this object obj)
  757. => obj == null
  758. || (obj is Object unityObject && unityObject == null);
  759. /************************************************************************************************************************/
  760. /// <summary>[Animancer Extension]
  761. /// Adds the specified type of <see cref="IAnimancerComponent"/>, links it to the `animator`, and returns it.
  762. /// </summary>
  763. public static T AddAnimancerComponent<T>(this Animator animator)
  764. where T : Component, IAnimancerComponent
  765. {
  766. var animancer = animator.gameObject.AddComponent<T>();
  767. animancer.Animator = animator;
  768. return animancer;
  769. }
  770. /************************************************************************************************************************/
  771. /// <summary>[Animancer Extension]
  772. /// Returns the <see cref="IAnimancerComponent"/> on the same <see cref="GameObject"/> as the `animator` if
  773. /// there is one. Otherwise this method adds a new one and returns it.
  774. /// </summary>
  775. public static T GetOrAddAnimancerComponent<T>(this Animator animator)
  776. where T : Component, IAnimancerComponent
  777. {
  778. if (animator.TryGetComponent<T>(out var component))
  779. return component;
  780. else
  781. return animator.AddAnimancerComponent<T>();
  782. }
  783. /************************************************************************************************************************/
  784. /// <summary>
  785. /// Returns the first <typeparamref name="T"/> component on the `gameObject` or its parents or children (in
  786. /// that order).
  787. /// </summary>
  788. public static T GetComponentInParentOrChildren<T>(this GameObject gameObject)
  789. where T : class
  790. {
  791. if (gameObject == null)
  792. return null;
  793. var component = gameObject.GetComponentInParent<T>();
  794. if (component != null)
  795. return component;
  796. return gameObject.GetComponentInChildren<T>();
  797. }
  798. /// <summary>
  799. /// If the `component` is <c>null</c>, this method tries to find one on the `gameObject` or its parents or
  800. /// children (in that order).
  801. /// </summary>
  802. public static bool GetComponentInParentOrChildren<T>(this GameObject gameObject, ref T component)
  803. where T : class
  804. {
  805. if (gameObject == null)
  806. return false;
  807. if (component != null &&
  808. (component is not Object obj || obj != null))
  809. return false;
  810. component = gameObject.GetComponentInParentOrChildren<T>();
  811. return component is not null;
  812. }
  813. /************************************************************************************************************************/
  814. /// <summary>Creates a new <see cref="GameObject"/> and `singleton` instance if it was null.</summary>
  815. /// <remarks>Calls <see cref="Object.DontDestroyOnLoad"/> on the instance.</remarks>
  816. public static T InitializeSingleton<T>(ref T singleton)
  817. where T : Behaviour
  818. {
  819. if (singleton != null)
  820. return singleton;
  821. #if UNITY_EDITOR
  822. // In Edit Mode or if we enter Play Mode without a Domain Reload
  823. // there might already be an existing instance.
  824. // Object.FindObjectOfType won't find it for whatever reason.
  825. var instances = Resources.FindObjectsOfTypeAll<T>();
  826. for (int i = 0; i < instances.Length; i++)
  827. {
  828. singleton = instances[i];
  829. // Ignore prefabs if an instance gets saved in one.
  830. if (string.IsNullOrEmpty(singleton.gameObject.scene.path))
  831. continue;
  832. singleton.enabled = true;
  833. return singleton;
  834. }
  835. // In Edit Mode, create a hidden object so we don't dirty the scene.
  836. if (!UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
  837. {
  838. var gameObject = UnityEditor.EditorUtility.CreateGameObjectWithHideFlags(
  839. typeof(T).Name,
  840. HideFlags.HideAndDontSave);
  841. singleton = gameObject.AddComponent<T>();
  842. return singleton;
  843. }
  844. #endif
  845. // Otherwise, just create a regular instance.
  846. {
  847. var gameObject = new GameObject(typeof(T).Name);
  848. singleton = gameObject.AddComponent<T>();
  849. Object.DontDestroyOnLoad(gameObject);
  850. return singleton;
  851. }
  852. }
  853. /************************************************************************************************************************/
  854. #endregion
  855. /************************************************************************************************************************/
  856. #region Editor
  857. /************************************************************************************************************************/
  858. /// <summary>[Assert-Conditional]
  859. /// Throws an <see cref="UnityEngine.Assertions.AssertionException"/> if the `condition` is false.
  860. /// </summary>
  861. /// <remarks>
  862. /// This method is similar to <see cref="Debug.Assert(bool, object)"/>, but it throws an exception instead of
  863. /// just logging the `message`.
  864. /// </remarks>
  865. [System.Diagnostics.Conditional(Strings.Assertions)]
  866. public static void Assert(bool condition, object message)
  867. {
  868. #if UNITY_ASSERTIONS
  869. if (!condition)
  870. throw new UnityEngine.Assertions.AssertionException(
  871. message?.ToString() ?? "Assertion failed.",
  872. null);
  873. #endif
  874. }
  875. /************************************************************************************************************************/
  876. /// <summary>[Editor-Conditional] Indicates that the `target` needs to be re-serialized.</summary>
  877. [System.Diagnostics.Conditional(Strings.UnityEditor)]
  878. public static void SetDirty(Object target)
  879. {
  880. #if UNITY_EDITOR
  881. UnityEditor.EditorUtility.SetDirty(target);
  882. #endif
  883. }
  884. /************************************************************************************************************************/
  885. /// <summary>[Editor-Conditional]
  886. /// Applies the effects of the animation `clip` to the <see cref="Component.gameObject"/>.
  887. /// </summary>
  888. /// <remarks>This method is safe to call during <see cref="MonoBehaviour"/><c>.OnValidate</c>.</remarks>
  889. /// <param name="clip">The animation to apply. If <c>null</c>, this method does nothing.</param>
  890. /// <param name="component">
  891. /// The animation will be applied to an <see cref="Animator"/> or <see cref="Animation"/> component on the same
  892. /// object as this or on any of its parents or children. If <c>null</c>, this method does nothing.
  893. /// </param>
  894. /// <param name="time">Determines which part of the animation to apply (in seconds).</param>
  895. /// <seealso cref="EditModePlay"/>
  896. [System.Diagnostics.Conditional(Strings.UnityEditor)]
  897. public static void EditModeSampleAnimation(this AnimationClip clip, Component component, float time = 0)
  898. {
  899. #if UNITY_EDITOR
  900. if (!ShouldEditModeSample(clip, component))
  901. return;
  902. var gameObject = component.gameObject;
  903. component = gameObject.GetComponentInParentOrChildren<Animator>();
  904. if (component == null)
  905. {
  906. component = gameObject.GetComponentInParentOrChildren<Animation>();
  907. if (component == null)
  908. return;
  909. }
  910. UnityEditor.EditorApplication.delayCall += () =>
  911. {
  912. if (!ShouldEditModeSample(clip, component))
  913. return;
  914. clip.SampleAnimation(component.gameObject, time);
  915. };
  916. }
  917. private static bool ShouldEditModeSample(AnimationClip clip, Component component)
  918. {
  919. return
  920. !UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode &&
  921. clip != null &&
  922. component != null &&
  923. !UnityEditor.EditorUtility.IsPersistent(component);
  924. #endif
  925. }
  926. /************************************************************************************************************************/
  927. /// <summary>[Editor-Conditional] Plays the specified `clip` if called in Edit Mode.</summary>
  928. /// <remarks>This method is safe to call during <see cref="MonoBehaviour"/><c>.OnValidate</c>.</remarks>
  929. /// <param name="clip">The animation to apply. If <c>null</c>, this method does nothing.</param>
  930. /// <param name="component">
  931. /// The animation will be played on an <see cref="IAnimancerComponent"/> on the same object as this or on any
  932. /// of its parents or children. If <c>null</c>, this method does nothing.
  933. /// </param>
  934. /// <seealso cref="EditModeSampleAnimation"/>
  935. [System.Diagnostics.Conditional(Strings.UnityEditor)]
  936. public static void EditModePlay(this AnimationClip clip, Component component)
  937. {
  938. #if UNITY_EDITOR
  939. if (!ShouldEditModeSample(clip, component))
  940. return;
  941. if (component is not IAnimancerComponent animancer)
  942. animancer = component.gameObject.GetComponentInParentOrChildren<IAnimancerComponent>();
  943. if (!ShouldEditModePlay(animancer, clip))
  944. return;
  945. // If it's already initialized, play immediately.
  946. if (animancer.IsGraphInitialized)
  947. {
  948. animancer.Graph.Layers[0].Play(clip);
  949. return;
  950. }
  951. // Otherwise, delay it in case this was called at a bad time (such as during OnValidate).
  952. UnityEditor.EditorApplication.delayCall += () =>
  953. {
  954. if (ShouldEditModePlay(animancer, clip))
  955. animancer.Graph.Layers[0].Play(clip);
  956. };
  957. #endif
  958. }
  959. #if UNITY_EDITOR
  960. private static bool ShouldEditModePlay(IAnimancerComponent animancer, AnimationClip clip)
  961. => ShouldEditModeSample(clip, animancer?.Animator)
  962. && (animancer is not Object obj || obj != null);
  963. #endif
  964. /************************************************************************************************************************/
  965. #endregion
  966. /************************************************************************************************************************/
  967. }
  968. }