SpineAnimationStateMixerBehaviour.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /******************************************************************************
  2. * Spine Runtimes License Agreement
  3. * Last updated January 1, 2020. Replaces all prior versions.
  4. *
  5. * Copyright (c) 2013-2020, 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
  13. * or 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
  27. * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *****************************************************************************/
  29. #define SPINE_EDITMODEPOSE
  30. using System;
  31. using UnityEngine;
  32. using UnityEngine.Playables;
  33. using UnityEngine.Timeline;
  34. namespace Spine.Unity.Playables {
  35. public class SpineAnimationStateMixerBehaviour : PlayableBehaviour {
  36. float[] lastInputWeights;
  37. bool lastAnyClipPlaying = false;
  38. public int trackIndex;
  39. ScriptPlayable<SpineAnimationStateBehaviour>[] startingClips
  40. = new ScriptPlayable<SpineAnimationStateBehaviour>[2];
  41. IAnimationStateComponent animationStateComponent;
  42. bool pauseWithDirector = true;
  43. bool endAtClipEnd = true;
  44. float endMixOutDuration = 0.1f;
  45. bool isPaused = false;
  46. TrackEntry pausedTrackEntry;
  47. float previousTimeScale = 1;
  48. TrackEntry timelineStartedTrackEntry;
  49. public override void OnBehaviourPause (Playable playable, FrameData info) {
  50. if (pauseWithDirector) {
  51. if (!isPaused)
  52. HandlePause(playable);
  53. isPaused = true;
  54. }
  55. }
  56. public override void OnGraphStop (Playable playable) {
  57. if (!isPaused && endAtClipEnd)
  58. HandleClipEnd();
  59. }
  60. public override void OnBehaviourPlay (Playable playable, FrameData info) {
  61. if (isPaused)
  62. HandleResume(playable);
  63. isPaused = false;
  64. }
  65. protected void HandlePause (Playable playable) {
  66. if (animationStateComponent.IsNullOrDestroyed()) return;
  67. TrackEntry current = animationStateComponent.AnimationState.GetCurrent(trackIndex);
  68. if (current != null && current == timelineStartedTrackEntry) {
  69. previousTimeScale = current.TimeScale;
  70. current.TimeScale = 0;
  71. pausedTrackEntry = current;
  72. }
  73. }
  74. protected void HandleResume (Playable playable) {
  75. if (animationStateComponent.IsNullOrDestroyed()) return;
  76. TrackEntry current = animationStateComponent.AnimationState.GetCurrent(trackIndex);
  77. if (current != null && current == pausedTrackEntry) {
  78. current.TimeScale = previousTimeScale;
  79. }
  80. }
  81. protected void HandleClipEnd () {
  82. if (animationStateComponent.IsNullOrDestroyed()) return;
  83. var state = animationStateComponent.AnimationState;
  84. if (endAtClipEnd &&
  85. timelineStartedTrackEntry != null &&
  86. timelineStartedTrackEntry == state.GetCurrent(trackIndex)) {
  87. if (endMixOutDuration >= 0)
  88. state.SetEmptyAnimation(trackIndex, endMixOutDuration);
  89. else // pause if endMixOutDuration < 0
  90. timelineStartedTrackEntry.TimeScale = 0;
  91. timelineStartedTrackEntry = null;
  92. }
  93. }
  94. // NOTE: This function is called at runtime and edit time. Keep that in mind when setting the values of properties.
  95. public override void ProcessFrame (Playable playable, FrameData info, object playerData) {
  96. var skeletonAnimation = playerData as SkeletonAnimation;
  97. var skeletonGraphic = playerData as SkeletonGraphic;
  98. animationStateComponent = playerData as IAnimationStateComponent;
  99. var skeletonComponent = playerData as ISkeletonComponent;
  100. if (animationStateComponent.IsNullOrDestroyed() || skeletonComponent == null) return;
  101. var skeleton = skeletonComponent.Skeleton;
  102. var state = animationStateComponent.AnimationState;
  103. if (!Application.isPlaying) {
  104. #if SPINE_EDITMODEPOSE
  105. PreviewEditModePose(playable, skeletonComponent, animationStateComponent,
  106. skeletonAnimation, skeletonGraphic);
  107. #endif
  108. return;
  109. }
  110. int inputCount = playable.GetInputCount();
  111. // Ensure correct buffer size.
  112. if (this.lastInputWeights == null || this.lastInputWeights.Length < inputCount) {
  113. this.lastInputWeights = new float[inputCount];
  114. for (int i = 0; i < inputCount; i++)
  115. this.lastInputWeights[i] = default(float);
  116. }
  117. var lastInputWeights = this.lastInputWeights;
  118. int numStartingClips = 0;
  119. bool anyClipPlaying = false;
  120. // Check all clips. If a clip that was weight 0 turned into weight 1, call SetAnimation.
  121. for (int i = 0; i < inputCount; i++) {
  122. float lastInputWeight = lastInputWeights[i];
  123. float inputWeight = playable.GetInputWeight(i);
  124. bool clipStarted = lastInputWeight == 0 && inputWeight > 0;
  125. if (inputWeight > 0)
  126. anyClipPlaying = true;
  127. lastInputWeights[i] = inputWeight;
  128. if (clipStarted && numStartingClips < 2) {
  129. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable = (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(i);
  130. startingClips[numStartingClips++] = clipPlayable;
  131. }
  132. }
  133. // unfortunately order of clips can be wrong when two start at the same time, we have to sort clips
  134. if (numStartingClips == 2) {
  135. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable0 = startingClips[0];
  136. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable1 = startingClips[1];
  137. if (clipPlayable0.GetDuration() > clipPlayable1.GetDuration()) { // swap, clip 0 ends after clip 1
  138. startingClips[0] = clipPlayable1;
  139. startingClips[1] = clipPlayable0;
  140. }
  141. }
  142. for (int j = 0; j < numStartingClips; ++j) {
  143. ScriptPlayable<SpineAnimationStateBehaviour> clipPlayable = startingClips[j];
  144. SpineAnimationStateBehaviour clipData = clipPlayable.GetBehaviour();
  145. pauseWithDirector = !clipData.dontPauseWithDirector;
  146. endAtClipEnd = !clipData.dontEndWithClip;
  147. endMixOutDuration = clipData.endMixOutDuration;
  148. if (clipData.animationReference == null) {
  149. float mixDuration = clipData.customDuration ? GetCustomMixDuration(clipData) : state.Data.DefaultMix;
  150. state.SetEmptyAnimation(trackIndex, mixDuration);
  151. } else {
  152. if (clipData.animationReference.Animation != null) {
  153. TrackEntry currentEntry = state.GetCurrent(trackIndex);
  154. Spine.TrackEntry trackEntry;
  155. float customMixDuration = clipData.customDuration ? GetCustomMixDuration(clipData) : 0.0f;
  156. if (currentEntry == null && customMixDuration > 0) {
  157. state.SetEmptyAnimation(trackIndex, 0); // ease in requires empty animation
  158. trackEntry = state.AddAnimation(trackIndex, clipData.animationReference.Animation, clipData.loop, 0);
  159. } else
  160. trackEntry = state.SetAnimation(trackIndex, clipData.animationReference.Animation, clipData.loop);
  161. trackEntry.EventThreshold = clipData.eventThreshold;
  162. trackEntry.DrawOrderThreshold = clipData.drawOrderThreshold;
  163. trackEntry.TrackTime = (float)clipPlayable.GetTime() * (float)clipPlayable.GetSpeed();
  164. trackEntry.TimeScale = (float)clipPlayable.GetSpeed();
  165. trackEntry.AttachmentThreshold = clipData.attachmentThreshold;
  166. trackEntry.HoldPrevious = clipData.holdPrevious;
  167. trackEntry.Alpha = clipData.alpha;
  168. if (clipData.customDuration)
  169. trackEntry.MixDuration = customMixDuration;
  170. timelineStartedTrackEntry = trackEntry;
  171. }
  172. //else Debug.LogWarningFormat("Animation named '{0}' not found", clipData.animationName);
  173. }
  174. // Ensure that the first frame ends with an updated mesh.
  175. if (skeletonAnimation) {
  176. skeletonAnimation.Update(0);
  177. skeletonAnimation.LateUpdate();
  178. } else if (skeletonGraphic) {
  179. skeletonGraphic.Update(0);
  180. skeletonGraphic.LateUpdate();
  181. }
  182. }
  183. startingClips[0] = startingClips[1] = ScriptPlayable<SpineAnimationStateBehaviour>.Null;
  184. if (lastAnyClipPlaying && !anyClipPlaying)
  185. HandleClipEnd();
  186. this.lastAnyClipPlaying = anyClipPlaying;
  187. }
  188. #if SPINE_EDITMODEPOSE
  189. AnimationState dummyAnimationState;
  190. public void PreviewEditModePose (Playable playable,
  191. ISkeletonComponent skeletonComponent, IAnimationStateComponent animationStateComponent,
  192. SkeletonAnimation skeletonAnimation, SkeletonGraphic skeletonGraphic) {
  193. if (Application.isPlaying) return;
  194. if (animationStateComponent.IsNullOrDestroyed() || skeletonComponent == null) return;
  195. int inputCount = playable.GetInputCount();
  196. int lastNonZeroWeightTrack = -1;
  197. for (int i = 0; i < inputCount; i++) {
  198. float inputWeight = playable.GetInputWeight(i);
  199. if (inputWeight > 0) lastNonZeroWeightTrack = i;
  200. }
  201. if (lastNonZeroWeightTrack != -1) {
  202. ScriptPlayable<SpineAnimationStateBehaviour> inputPlayableClip =
  203. (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(lastNonZeroWeightTrack);
  204. SpineAnimationStateBehaviour clipData = inputPlayableClip.GetBehaviour();
  205. var skeleton = skeletonComponent.Skeleton;
  206. bool skeletonDataMismatch = clipData.animationReference != null && clipData.animationReference.SkeletonDataAsset &&
  207. skeletonComponent.SkeletonDataAsset.GetSkeletonData(true) != clipData.animationReference.SkeletonDataAsset.GetSkeletonData(true);
  208. if (skeletonDataMismatch) {
  209. Debug.LogWarningFormat("SpineAnimationStateMixerBehaviour tried to apply an animation for the wrong skeleton. Expected {0}. Was {1}",
  210. skeletonComponent.SkeletonDataAsset, clipData.animationReference.SkeletonDataAsset);
  211. }
  212. // Getting the from-animation here because it's required to get the mix information from AnimationStateData.
  213. Animation fromAnimation = null;
  214. float fromClipTime = 0;
  215. bool fromClipLoop = false;
  216. if (lastNonZeroWeightTrack != 0 && inputCount > 1) {
  217. var fromClip = (ScriptPlayable<SpineAnimationStateBehaviour>)playable.GetInput(lastNonZeroWeightTrack - 1);
  218. var fromClipData = fromClip.GetBehaviour();
  219. fromAnimation = fromClipData.animationReference != null ? fromClipData.animationReference.Animation : null;
  220. fromClipTime = (float)fromClip.GetTime() * (float)fromClip.GetSpeed();
  221. fromClipLoop = fromClipData.loop;
  222. }
  223. Animation toAnimation = clipData.animationReference != null ? clipData.animationReference.Animation : null;
  224. float toClipTime = (float)inputPlayableClip.GetTime() * (float)inputPlayableClip.GetSpeed();
  225. float mixDuration = clipData.mixDuration;
  226. if (!clipData.customDuration && fromAnimation != null && toAnimation != null) {
  227. mixDuration = animationStateComponent.AnimationState.Data.GetMix(fromAnimation, toAnimation);
  228. }
  229. if (trackIndex == 0)
  230. skeleton.SetToSetupPose();
  231. // Approximate what AnimationState might do at runtime.
  232. if (fromAnimation != null && mixDuration > 0 && toClipTime < mixDuration) {
  233. dummyAnimationState = dummyAnimationState ?? new AnimationState(skeletonComponent.SkeletonDataAsset.GetAnimationStateData());
  234. var toEntry = dummyAnimationState.GetCurrent(0);
  235. var fromEntry = toEntry != null ? toEntry.MixingFrom : null;
  236. bool isAnimationTransitionMatch = (toEntry != null && toEntry.Animation == toAnimation && fromEntry != null && fromEntry.Animation == fromAnimation);
  237. if (!isAnimationTransitionMatch) {
  238. dummyAnimationState.ClearTracks();
  239. fromEntry = dummyAnimationState.SetAnimation(0, fromAnimation, fromClipLoop);
  240. fromEntry.AllowImmediateQueue();
  241. if (toAnimation != null) {
  242. toEntry = dummyAnimationState.SetAnimation(0, toAnimation, clipData.loop);
  243. toEntry.HoldPrevious = clipData.holdPrevious;
  244. toEntry.Alpha = clipData.alpha;
  245. }
  246. }
  247. // Update track times.
  248. fromEntry.TrackTime = fromClipTime;
  249. if (toEntry != null) {
  250. toEntry.TrackTime = toClipTime;
  251. toEntry.MixTime = toClipTime;
  252. }
  253. // Apply Pose
  254. dummyAnimationState.Update(0);
  255. dummyAnimationState.Apply(skeleton);
  256. } else {
  257. if (toAnimation != null)
  258. toAnimation.Apply(skeleton, 0, toClipTime, clipData.loop, null, clipData.alpha, MixBlend.Setup, MixDirection.In);
  259. }
  260. if (skeletonAnimation) {
  261. skeletonAnimation.Update(0);
  262. skeletonAnimation.LateUpdate();
  263. } else if (skeletonGraphic) {
  264. skeletonGraphic.Update(0);
  265. skeletonGraphic.LateUpdate();
  266. }
  267. }
  268. // Do nothing outside of the first clip and the last clip.
  269. }
  270. #endif
  271. float GetCustomMixDuration (SpineAnimationStateBehaviour clipData) {
  272. if (clipData.useBlendDuration) {
  273. TimelineClip clip = clipData.timelineClip;
  274. return (float)Math.Max(clip.blendInDuration, clip.easeInDuration);
  275. } else {
  276. return clipData.mixDuration;
  277. }
  278. }
  279. }
  280. }