SkeletonAnimation.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated July 28, 2023. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2023, Esoteric Software LLC
  6. *
  7. * Integration of the Spine Runtimes into software or otherwise creating
  8. * derivative works of the Spine Runtimes is permitted under the terms and
  9. * conditions of Section 2 of the Spine Editor License Agreement:
  10. * http://esotericsoftware.com/spine-editor-license
  11. *
  12. * Otherwise, it is permitted to integrate the Spine Runtimes into software or
  13. * otherwise create derivative works of the Spine Runtimes (collectively,
  14. * "Products"), provided that each user of the Products must obtain their own
  15. * Spine Editor license and redistribution of the Products in any form must
  16. * include this license and copyright notice.
  17. *
  18. * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
  19. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
  24. * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE
  27. * SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #if UNITY_2018_3 || UNITY_2019 || UNITY_2018_3_OR_NEWER
  30. #define NEW_PREFAB_SYSTEM
  31. #endif
  32. using UnityEngine;
  33. namespace Spine.Unity {
  34. #if NEW_PREFAB_SYSTEM
  35. [ExecuteAlways]
  36. #else
  37. [ExecuteInEditMode]
  38. #endif
  39. [AddComponentMenu("Spine/SkeletonAnimation")]
  40. [HelpURL("http://esotericsoftware.com/spine-unity#SkeletonAnimation-Component")]
  41. public class SkeletonAnimation : SkeletonRenderer, ISkeletonAnimation, IAnimationStateComponent {
  42. #region IAnimationStateComponent
  43. /// <summary>
  44. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  45. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  46. public Spine.AnimationState state;
  47. /// <summary>
  48. /// This is the Spine.AnimationState object of this SkeletonAnimation. You can control animations through it.
  49. /// Note that this object, like .skeleton, is not guaranteed to exist in Awake. Do all accesses and caching to it in Start</summary>
  50. public Spine.AnimationState AnimationState {
  51. get {
  52. Initialize(false);
  53. return this.state;
  54. }
  55. }
  56. private bool wasUpdatedAfterInit = true;
  57. #endregion
  58. #region Bone and Initialization Callbacks ISkeletonAnimation
  59. protected event ISkeletonAnimationDelegate _OnAnimationRebuild;
  60. protected event UpdateBonesDelegate _BeforeApply;
  61. protected event UpdateBonesDelegate _UpdateLocal;
  62. protected event UpdateBonesDelegate _UpdateWorld;
  63. protected event UpdateBonesDelegate _UpdateComplete;
  64. /// <summary>OnAnimationRebuild is raised after the SkeletonAnimation component is successfully initialized.</summary>
  65. public event ISkeletonAnimationDelegate OnAnimationRebuild { add { _OnAnimationRebuild += value; } remove { _OnAnimationRebuild -= value; } }
  66. /// <summary>
  67. /// Occurs before the animations are applied.
  68. /// Use this callback when you want to change the skeleton state before animations are applied on top.
  69. /// </summary>
  70. public event UpdateBonesDelegate BeforeApply { add { _BeforeApply += value; } remove { _BeforeApply -= value; } }
  71. /// <summary>
  72. /// Occurs after the animations are applied and before world space values are resolved.
  73. /// Use this callback when you want to set bone local values.
  74. /// </summary>
  75. public event UpdateBonesDelegate UpdateLocal { add { _UpdateLocal += value; } remove { _UpdateLocal -= value; } }
  76. /// <summary>
  77. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  78. /// Using this callback will cause the world space values to be solved an extra time.
  79. /// Use this callback if want to use bone world space values, and also set bone local values.
  80. /// </summary>
  81. public event UpdateBonesDelegate UpdateWorld { add { _UpdateWorld += value; } remove { _UpdateWorld -= value; } }
  82. /// <summary>
  83. /// Occurs after the Skeleton's bone world space values are resolved (including all constraints).
  84. /// Use this callback if you want to use bone world space values, but don't intend to modify bone local values.
  85. /// This callback can also be used when setting world position and the bone matrix.</summary>
  86. public event UpdateBonesDelegate UpdateComplete { add { _UpdateComplete += value; } remove { _UpdateComplete -= value; } }
  87. [SerializeField] protected UpdateTiming updateTiming = UpdateTiming.InUpdate;
  88. public UpdateTiming UpdateTiming { get { return updateTiming; } set { updateTiming = value; } }
  89. /// <summary>If enabled, AnimationState uses unscaled game time
  90. /// (<c>Time.unscaledDeltaTime</c> instead of normal game time(<c>Time.deltaTime</c>),
  91. /// running animations independent of e.g. game pause (<c>Time.timeScale</c>).
  92. /// Instance SkeletonAnimation.timeScale will still be applied.</summary>
  93. [SerializeField] protected bool unscaledTime;
  94. public bool UnscaledTime { get { return unscaledTime; } set { unscaledTime = value; } }
  95. #endregion
  96. #region Serialized state and Beginner API
  97. [SerializeField]
  98. [SpineAnimation]
  99. private string _animationName;
  100. /// <summary>
  101. /// Setting this property sets the animation of the skeleton. If invalid, it will store the animation name for the next time the skeleton is properly initialized.
  102. /// Getting this property gets the name of the currently playing animation. If invalid, it will return the last stored animation name set through this property.</summary>
  103. public string AnimationName {
  104. get {
  105. if (!valid) {
  106. return _animationName;
  107. } else {
  108. TrackEntry entry = state.GetCurrent(0);
  109. return entry == null ? null : entry.Animation.Name;
  110. }
  111. }
  112. set {
  113. Initialize(false);
  114. if (_animationName == value) {
  115. TrackEntry entry = state.GetCurrent(0);
  116. if (entry != null && entry.Loop == loop)
  117. return;
  118. }
  119. _animationName = value;
  120. if (string.IsNullOrEmpty(value)) {
  121. state.ClearTrack(0);
  122. } else {
  123. Spine.Animation animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(value);
  124. if (animationObject != null)
  125. state.SetAnimation(0, animationObject, loop);
  126. }
  127. }
  128. }
  129. /// <summary>Whether or not <see cref="AnimationName"/> should loop. This only applies to the initial animation specified in the inspector, or any subsequent Animations played through .AnimationName. Animations set through state.SetAnimation are unaffected.</summary>
  130. public bool loop;
  131. /// <summary>
  132. /// The rate at which animations progress over time. 1 means 100%. 0.5 means 50%.</summary>
  133. /// <remarks>AnimationState and TrackEntry also have their own timeScale. These are combined multiplicatively.</remarks>
  134. public float timeScale = 1;
  135. #endregion
  136. #region Runtime Instantiation
  137. /// <summary>Adds and prepares a SkeletonAnimation component to a GameObject at runtime.</summary>
  138. /// <returns>The newly instantiated SkeletonAnimation</returns>
  139. public static SkeletonAnimation AddToGameObject (GameObject gameObject, SkeletonDataAsset skeletonDataAsset,
  140. bool quiet = false) {
  141. return SkeletonRenderer.AddSpineComponent<SkeletonAnimation>(gameObject, skeletonDataAsset, quiet);
  142. }
  143. /// <summary>Instantiates a new UnityEngine.GameObject and adds a prepared SkeletonAnimation component to it.</summary>
  144. /// <returns>The newly instantiated SkeletonAnimation component.</returns>
  145. public static SkeletonAnimation NewSkeletonAnimationGameObject (SkeletonDataAsset skeletonDataAsset,
  146. bool quiet = false) {
  147. return SkeletonRenderer.NewSpineGameObject<SkeletonAnimation>(skeletonDataAsset, quiet);
  148. }
  149. #endregion
  150. /// <summary>
  151. /// Clears the previously generated mesh, resets the skeleton's pose, and clears all previously active animations.</summary>
  152. public override void ClearState () {
  153. base.ClearState();
  154. if (state != null) state.ClearTracks();
  155. }
  156. /// <summary>
  157. /// Initialize this component. Attempts to load the SkeletonData and creates the internal Spine objects and buffers.</summary>
  158. /// <param name="overwrite">If set to <c>true</c>, force overwrite an already initialized object.</param>
  159. public override void Initialize (bool overwrite, bool quiet = false) {
  160. if (valid && !overwrite)
  161. return;
  162. #if UNITY_EDITOR
  163. if (BuildUtilities.IsInSkeletonAssetBuildPreProcessing)
  164. return;
  165. #endif
  166. state = null; // prevent applying leftover AnimationState
  167. base.Initialize(overwrite, quiet);
  168. if (!valid)
  169. return;
  170. state = new Spine.AnimationState(skeletonDataAsset.GetAnimationStateData());
  171. wasUpdatedAfterInit = false;
  172. if (!string.IsNullOrEmpty(_animationName)) {
  173. Spine.Animation animationObject = skeletonDataAsset.GetSkeletonData(false).FindAnimation(_animationName);
  174. if (animationObject != null) {
  175. state.SetAnimation(0, animationObject, loop);
  176. #if UNITY_EDITOR
  177. if (!Application.isPlaying)
  178. Update(0f);
  179. #endif
  180. }
  181. }
  182. if (_OnAnimationRebuild != null)
  183. _OnAnimationRebuild(this);
  184. }
  185. virtual protected void Update () {
  186. #if UNITY_EDITOR
  187. if (!Application.isPlaying) {
  188. Update(0f);
  189. return;
  190. }
  191. #endif
  192. if (updateTiming != UpdateTiming.InUpdate) return;
  193. Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime);
  194. }
  195. virtual protected void FixedUpdate () {
  196. if (updateTiming != UpdateTiming.InFixedUpdate) return;
  197. Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime);
  198. }
  199. /// <summary>Progresses the AnimationState according to the given deltaTime, and applies it to the Skeleton. Use Time.deltaTime to update manually. Use deltaTime 0 to update without progressing the time.</summary>
  200. public void Update (float deltaTime) {
  201. if (!valid || state == null)
  202. return;
  203. wasUpdatedAfterInit = true;
  204. if (updateMode < UpdateMode.OnlyAnimationStatus)
  205. return;
  206. UpdateAnimationStatus(deltaTime);
  207. if (updateMode == UpdateMode.OnlyAnimationStatus)
  208. return;
  209. ApplyAnimation();
  210. }
  211. protected void UpdateAnimationStatus (float deltaTime) {
  212. deltaTime *= timeScale;
  213. state.Update(deltaTime);
  214. skeleton.Update(deltaTime);
  215. ApplyTransformMovementToPhysics();
  216. if (updateMode == UpdateMode.OnlyAnimationStatus) {
  217. state.ApplyEventTimelinesOnly(skeleton, issueEvents: false);
  218. return;
  219. }
  220. }
  221. public virtual void ApplyAnimation () {
  222. if (_BeforeApply != null)
  223. _BeforeApply(this);
  224. if (updateMode != UpdateMode.OnlyEventTimelines)
  225. state.Apply(skeleton);
  226. else
  227. state.ApplyEventTimelinesOnly(skeleton, issueEvents: true);
  228. AfterAnimationApplied();
  229. }
  230. public void AfterAnimationApplied () {
  231. if (_UpdateLocal != null)
  232. _UpdateLocal(this);
  233. if (_UpdateWorld == null) {
  234. UpdateWorldTransform(Skeleton.Physics.Update);
  235. } else {
  236. UpdateWorldTransform(Skeleton.Physics.Pose);
  237. _UpdateWorld(this);
  238. UpdateWorldTransform(Skeleton.Physics.Update);
  239. }
  240. if (_UpdateComplete != null) {
  241. _UpdateComplete(this);
  242. }
  243. }
  244. public override void LateUpdate () {
  245. if (updateTiming == UpdateTiming.InLateUpdate && valid)
  246. Update(unscaledTime ? Time.unscaledDeltaTime : Time.deltaTime);
  247. // instantiation can happen from Update() after this component, leading to a missing Update() call.
  248. if (!wasUpdatedAfterInit) Update(0);
  249. base.LateUpdate();
  250. }
  251. public override void OnBecameVisible () {
  252. UpdateMode previousUpdateMode = updateMode;
  253. updateMode = UpdateMode.FullUpdate;
  254. // OnBecameVisible is called after LateUpdate()
  255. if (previousUpdateMode != UpdateMode.FullUpdate &&
  256. previousUpdateMode != UpdateMode.EverythingExceptMesh)
  257. Update(0);
  258. if (previousUpdateMode != UpdateMode.FullUpdate)
  259. LateUpdate();
  260. }
  261. }
  262. }