AnimationState.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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. using System;
  30. using System.Collections.Generic;
  31. namespace Spine {
  32. /// <summary>
  33. /// <para>
  34. /// Applies animations over time, queues animations for later playback, mixes (crossfading) between animations, and applies
  35. /// multiple animations on top of each other (layering).</para>
  36. /// <para>
  37. /// See <a href='http://esotericsoftware.com/spine-applying-animations/'>Applying Animations</a> in the Spine Runtimes Guide.</para>
  38. /// </summary>
  39. public class AnimationState {
  40. static readonly Animation EmptyAnimation = new Animation("<empty>", new ExposedList<Timeline>(), 0);
  41. /// 1) A previously applied timeline has set this property.<para />
  42. /// Result: Mix from the current pose to the timeline pose.
  43. internal const int Subsequent = 0;
  44. /// 1) This is the first timeline to set this property.<para />
  45. /// 2) The next track entry applied after this one does not have a timeline to set this property.<para />
  46. /// Result: Mix from the setup pose to the timeline pose.
  47. internal const int First = 1;
  48. /// 1) A previously applied timeline has set this property.<br>
  49. /// 2) The next track entry to be applied does have a timeline to set this property.<br>
  50. /// 3) The next track entry after that one does not have a timeline to set this property.<br>
  51. /// Result: Mix from the current pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading
  52. /// animations that key the same property. A subsequent timeline will set this property using a mix.
  53. internal const int HoldSubsequent = 2;
  54. /// 1) This is the first timeline to set this property.<para />
  55. /// 2) The next track entry to be applied does have a timeline to set this property.<para />
  56. /// 3) The next track entry after that one does not have a timeline to set this property.<para />
  57. /// Result: Mix from the setup pose to the timeline pose, but do not mix out. This avoids "dipping" when crossfading animations
  58. /// that key the same property. A subsequent timeline will set this property using a mix.
  59. internal const int HoldFirst = 3;
  60. /// 1) This is the first timeline to set this property.<para />
  61. /// 2) The next track entry to be applied does have a timeline to set this property.<para />
  62. /// 3) The next track entry after that one does have a timeline to set this property.<para />
  63. /// 4) timelineHoldMix stores the first subsequent track entry that does not have a timeline to set this property.<para />
  64. /// Result: The same as HOLD except the mix percentage from the timelineHoldMix track entry is used. This handles when more than
  65. /// 2 track entries in a row have a timeline that sets the same property.<para />
  66. /// Eg, A -> B -> C -> D where A, B, and C have a timeline setting same property, but D does not. When A is applied, to avoid
  67. /// "dipping" A is not mixed out, however D (the first entry that doesn't set the property) mixing in is used to mix out A
  68. /// (which affects B and C). Without using D to mix out, A would be applied fully until mixing completes, then snap to the mixed
  69. /// out position.
  70. internal const int HoldMix = 4;
  71. internal const int Setup = 1, Current = 2;
  72. protected AnimationStateData data;
  73. private readonly ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>();
  74. private readonly ExposedList<Event> events = new ExposedList<Event>();
  75. // difference to libgdx reference: delegates are used for event callbacks instead of 'final SnapshotArray<AnimationStateListener> listeners'.
  76. internal void OnStart (TrackEntry entry) { if (Start != null) Start(entry); }
  77. internal void OnInterrupt (TrackEntry entry) { if (Interrupt != null) Interrupt(entry); }
  78. internal void OnEnd (TrackEntry entry) { if (End != null) End(entry); }
  79. internal void OnDispose (TrackEntry entry) { if (Dispose != null) Dispose(entry); }
  80. internal void OnComplete (TrackEntry entry) { if (Complete != null) Complete(entry); }
  81. internal void OnEvent (TrackEntry entry, Event e) { if (Event != null) Event(entry, e); }
  82. public delegate void TrackEntryDelegate (TrackEntry trackEntry);
  83. public event TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  84. public delegate void TrackEntryEventDelegate (TrackEntry trackEntry, Event e);
  85. public event TrackEntryEventDelegate Event;
  86. public void AssignEventSubscribersFrom (AnimationState src) {
  87. Event = src.Event;
  88. Start = src.Start;
  89. Interrupt = src.Interrupt;
  90. End = src.End;
  91. Dispose = src.Dispose;
  92. Complete = src.Complete;
  93. }
  94. public void AddEventSubscribersFrom (AnimationState src) {
  95. Event += src.Event;
  96. Start += src.Start;
  97. Interrupt += src.Interrupt;
  98. End += src.End;
  99. Dispose += src.Dispose;
  100. Complete += src.Complete;
  101. }
  102. // end of difference
  103. private readonly EventQueue queue; // Initialized by constructor.
  104. private readonly HashSet<int> propertyIDs = new HashSet<int>();
  105. private bool animationsChanged;
  106. private float timeScale = 1;
  107. private int unkeyedState;
  108. private readonly Pool<TrackEntry> trackEntryPool = new Pool<TrackEntry>();
  109. public AnimationState (AnimationStateData data) {
  110. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  111. this.data = data;
  112. this.queue = new EventQueue(
  113. this,
  114. delegate { this.animationsChanged = true; },
  115. trackEntryPool
  116. );
  117. }
  118. /// <summary>
  119. /// Increments the track entry <see cref="TrackEntry.TrackTime"/>, setting queued animations as current if needed.</summary>
  120. /// <param name="delta">delta time</param>
  121. public void Update (float delta) {
  122. delta *= timeScale;
  123. var tracksItems = tracks.Items;
  124. for (int i = 0, n = tracks.Count; i < n; i++) {
  125. TrackEntry current = tracksItems[i];
  126. if (current == null) continue;
  127. current.animationLast = current.nextAnimationLast;
  128. current.trackLast = current.nextTrackLast;
  129. float currentDelta = delta * current.timeScale;
  130. if (current.delay > 0) {
  131. current.delay -= currentDelta;
  132. if (current.delay > 0) continue;
  133. currentDelta = -current.delay;
  134. current.delay = 0;
  135. }
  136. TrackEntry next = current.next;
  137. if (next != null) {
  138. // When the next entry's delay is passed, change to the next entry, preserving leftover time.
  139. float nextTime = current.trackLast - next.delay;
  140. if (nextTime >= 0) {
  141. next.delay = 0;
  142. next.trackTime += current.timeScale == 0 ? 0 : (nextTime / current.timeScale + delta) * next.timeScale;
  143. current.trackTime += currentDelta;
  144. SetCurrent(i, next, true);
  145. while (next.mixingFrom != null) {
  146. next.mixTime += delta;
  147. next = next.mixingFrom;
  148. }
  149. continue;
  150. }
  151. } else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
  152. // Clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom.
  153. tracksItems[i] = null;
  154. queue.End(current);
  155. DisposeNext(current);
  156. continue;
  157. }
  158. if (current.mixingFrom != null && UpdateMixingFrom(current, delta)) {
  159. // End mixing from entries once all have completed.
  160. TrackEntry from = current.mixingFrom;
  161. current.mixingFrom = null;
  162. if (from != null) from.mixingTo = null;
  163. while (from != null) {
  164. queue.End(from);
  165. from = from.mixingFrom;
  166. }
  167. }
  168. current.trackTime += currentDelta;
  169. }
  170. queue.Drain();
  171. }
  172. /// <summary>Returns true when all mixing from entries are complete.</summary>
  173. private bool UpdateMixingFrom (TrackEntry to, float delta) {
  174. TrackEntry from = to.mixingFrom;
  175. if (from == null) return true;
  176. bool finished = UpdateMixingFrom(from, delta);
  177. from.animationLast = from.nextAnimationLast;
  178. from.trackLast = from.nextTrackLast;
  179. // Require mixTime > 0 to ensure the mixing from entry was applied at least once.
  180. if (to.mixTime > 0 && to.mixTime >= to.mixDuration) {
  181. // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame).
  182. if (from.totalAlpha == 0 || to.mixDuration == 0) {
  183. to.mixingFrom = from.mixingFrom;
  184. if (from.mixingFrom != null) from.mixingFrom.mixingTo = to;
  185. to.interruptAlpha = from.interruptAlpha;
  186. queue.End(from);
  187. }
  188. return finished;
  189. }
  190. from.trackTime += delta * from.timeScale;
  191. to.mixTime += delta;
  192. return false;
  193. }
  194. /// <summary>
  195. /// Poses the skeleton using the track entry animations. The animation state is not changed, so can be applied to multiple
  196. /// skeletons to pose them identically.</summary>
  197. /// <returns>True if any animations were applied.</returns>
  198. public bool Apply (Skeleton skeleton) {
  199. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  200. if (animationsChanged) AnimationsChanged();
  201. var events = this.events;
  202. bool applied = false;
  203. var tracksItems = tracks.Items;
  204. for (int i = 0, n = tracks.Count; i < n; i++) {
  205. TrackEntry current = tracksItems[i];
  206. if (current == null || current.delay > 0) continue;
  207. applied = true;
  208. // Track 0 animations aren't for layering, so do not show the previously applied animations before the first key.
  209. MixBlend blend = i == 0 ? MixBlend.First : current.mixBlend;
  210. // Apply mixing from entries first.
  211. float mix = current.alpha;
  212. if (current.mixingFrom != null)
  213. mix *= ApplyMixingFrom(current, skeleton, blend);
  214. else if (current.trackTime >= current.trackEnd && current.next == null) //
  215. mix = 0; // Set to setup pose the last time the entry will be applied.
  216. // Apply current entry.
  217. float animationLast = current.animationLast, animationTime = current.AnimationTime;
  218. int timelineCount = current.animation.timelines.Count;
  219. var timelines = current.animation.timelines;
  220. var timelinesItems = timelines.Items;
  221. if ((i == 0 && mix == 1) || blend == MixBlend.Add) {
  222. for (int ii = 0; ii < timelineCount; ii++) {
  223. var timeline = timelinesItems[ii];
  224. if (timeline is AttachmentTimeline)
  225. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true);
  226. else
  227. timeline.Apply(skeleton, animationLast, animationTime, events, mix, blend, MixDirection.In);
  228. }
  229. } else {
  230. var timelineMode = current.timelineMode.Items;
  231. bool firstFrame = current.timelinesRotation.Count != timelineCount << 1;
  232. if (firstFrame) current.timelinesRotation.Resize(timelines.Count << 1);
  233. var timelinesRotation = current.timelinesRotation.Items;
  234. for (int ii = 0; ii < timelineCount; ii++) {
  235. Timeline timeline = timelinesItems[ii];
  236. MixBlend timelineBlend = timelineMode[ii] == AnimationState.Subsequent ? blend : MixBlend.Setup;
  237. var rotateTimeline = timeline as RotateTimeline;
  238. if (rotateTimeline != null)
  239. ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation,
  240. ii << 1, firstFrame);
  241. else if (timeline is AttachmentTimeline)
  242. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, blend, true);
  243. else
  244. timeline.Apply(skeleton, animationLast, animationTime, events, mix, timelineBlend, MixDirection.In);
  245. }
  246. }
  247. QueueEvents(current, animationTime);
  248. events.Clear(false);
  249. current.nextAnimationLast = animationTime;
  250. current.nextTrackLast = current.trackTime;
  251. }
  252. // Set slots attachments to the setup pose, if needed. This occurs if an animation that is mixing out sets attachments so
  253. // subsequent timelines see any deform, but the subsequent timelines don't set an attachment (eg they are also mixing out or
  254. // the time is before the first key).
  255. int setupState = unkeyedState + Setup;
  256. var slots = skeleton.slots.Items;
  257. for (int i = 0, n = skeleton.slots.Count; i < n; i++) {
  258. Slot slot = (Slot)slots[i];
  259. if (slot.attachmentState == setupState) {
  260. string attachmentName = slot.data.attachmentName;
  261. slot.Attachment = (attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName));
  262. }
  263. }
  264. unkeyedState += 2; // Increasing after each use avoids the need to reset attachmentState for every slot.
  265. queue.Drain();
  266. return applied;
  267. }
  268. /// <summary>Version of <see cref="Apply"/> only applying EventTimelines for lightweight off-screen updates.</summary>
  269. // Note: This method is not part of the libgdx reference implementation.
  270. public bool ApplyEventTimelinesOnly (Skeleton skeleton) {
  271. if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null.");
  272. var events = this.events;
  273. bool applied = false;
  274. var tracksItems = tracks.Items;
  275. for (int i = 0, n = tracks.Count; i < n; i++) {
  276. TrackEntry current = tracksItems[i];
  277. if (current == null || current.delay > 0) continue;
  278. applied = true;
  279. // Apply mixing from entries first.
  280. if (current.mixingFrom != null)
  281. ApplyMixingFromEventTimelinesOnly(current, skeleton);
  282. // Apply current entry.
  283. float animationLast = current.animationLast, animationTime = current.AnimationTime;
  284. int timelineCount = current.animation.timelines.Count;
  285. var timelines = current.animation.timelines;
  286. var timelinesItems = timelines.Items;
  287. for (int ii = 0; ii < timelineCount; ii++) {
  288. Timeline timeline = timelinesItems[ii];
  289. if (timeline is EventTimeline)
  290. timeline.Apply(skeleton, animationLast, animationTime, events, 1.0f, MixBlend.Setup, MixDirection.In);
  291. }
  292. QueueEvents(current, animationTime);
  293. events.Clear(false);
  294. current.nextAnimationLast = animationTime;
  295. current.nextTrackLast = current.trackTime;
  296. }
  297. queue.Drain();
  298. return applied;
  299. }
  300. private float ApplyMixingFrom (TrackEntry to, Skeleton skeleton, MixBlend blend) {
  301. TrackEntry from = to.mixingFrom;
  302. if (from.mixingFrom != null) ApplyMixingFrom(from, skeleton, blend);
  303. float mix;
  304. if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
  305. mix = 1;
  306. if (blend == MixBlend.First) blend = MixBlend.Setup; // Tracks > 0 are transparent and can't reset to setup pose.
  307. } else {
  308. mix = to.mixTime / to.mixDuration;
  309. if (mix > 1) mix = 1;
  310. if (blend != MixBlend.First) blend = from.mixBlend; // Track 0 ignores track mix blend.
  311. }
  312. var eventBuffer = mix < from.eventThreshold ? this.events : null;
  313. bool attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
  314. float animationLast = from.animationLast, animationTime = from.AnimationTime;
  315. var timelines = from.animation.timelines;
  316. int timelineCount = timelines.Count;
  317. var timelinesItems = timelines.Items;
  318. float alphaHold = from.alpha * to.interruptAlpha, alphaMix = alphaHold * (1 - mix);
  319. if (blend == MixBlend.Add) {
  320. for (int i = 0; i < timelineCount; i++)
  321. timelinesItems[i].Apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection.Out);
  322. } else {
  323. var timelineMode = from.timelineMode.Items;
  324. var timelineHoldMix = from.timelineHoldMix.Items;
  325. bool firstFrame = from.timelinesRotation.Count != timelineCount << 1;
  326. if (firstFrame) from.timelinesRotation.Resize(timelines.Count << 1); // from.timelinesRotation.setSize
  327. var timelinesRotation = from.timelinesRotation.Items;
  328. from.totalAlpha = 0;
  329. for (int i = 0; i < timelineCount; i++) {
  330. Timeline timeline = timelinesItems[i];
  331. MixDirection direction = MixDirection.Out;
  332. MixBlend timelineBlend;
  333. float alpha;
  334. switch (timelineMode[i]) {
  335. case AnimationState.Subsequent:
  336. if (!drawOrder && timeline is DrawOrderTimeline) continue;
  337. timelineBlend = blend;
  338. alpha = alphaMix;
  339. break;
  340. case AnimationState.First:
  341. timelineBlend = MixBlend.Setup;
  342. alpha = alphaMix;
  343. break;
  344. case AnimationState.HoldSubsequent:
  345. timelineBlend = blend;
  346. alpha = alphaHold;
  347. break;
  348. case AnimationState.HoldFirst:
  349. timelineBlend = MixBlend.Setup;
  350. alpha = alphaHold;
  351. break;
  352. default: // HoldMix
  353. timelineBlend = MixBlend.Setup;
  354. TrackEntry holdMix = timelineHoldMix[i];
  355. alpha = alphaHold * Math.Max(0, 1 - holdMix.mixTime / holdMix.mixDuration);
  356. break;
  357. }
  358. from.totalAlpha += alpha;
  359. var rotateTimeline = timeline as RotateTimeline;
  360. if (rotateTimeline != null) {
  361. ApplyRotateTimeline(rotateTimeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation,
  362. i << 1, firstFrame);
  363. } else if (timeline is AttachmentTimeline) {
  364. ApplyAttachmentTimeline((AttachmentTimeline)timeline, skeleton, animationTime, timelineBlend, attachments);
  365. } else {
  366. if (drawOrder && timeline is DrawOrderTimeline && timelineBlend == MixBlend.Setup)
  367. direction = MixDirection.In;
  368. timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction);
  369. }
  370. }
  371. }
  372. if (to.mixDuration > 0) QueueEvents(from, animationTime);
  373. this.events.Clear(false);
  374. from.nextAnimationLast = animationTime;
  375. from.nextTrackLast = from.trackTime;
  376. return mix;
  377. }
  378. /// <summary>Version of <see cref="ApplyMixingFrom"/> only applying EventTimelines for lightweight off-screen updates.</summary>
  379. // Note: This method is not part of the libgdx reference implementation.
  380. private float ApplyMixingFromEventTimelinesOnly (TrackEntry to, Skeleton skeleton) {
  381. TrackEntry from = to.mixingFrom;
  382. if (from.mixingFrom != null) ApplyMixingFromEventTimelinesOnly(from, skeleton);
  383. float mix;
  384. if (to.mixDuration == 0) { // Single frame mix to undo mixingFrom changes.
  385. mix = 1;
  386. }
  387. else {
  388. mix = to.mixTime / to.mixDuration;
  389. if (mix > 1) mix = 1;
  390. }
  391. var eventBuffer = mix < from.eventThreshold ? this.events : null;
  392. if (eventBuffer == null)
  393. return mix;
  394. float animationLast = from.animationLast, animationTime = from.AnimationTime;
  395. var timelines = from.animation.timelines;
  396. int timelineCount = timelines.Count;
  397. var timelinesItems = timelines.Items;
  398. for (int i = 0; i < timelineCount; i++) {
  399. var timeline = timelinesItems[i];
  400. if (timeline is EventTimeline)
  401. timeline.Apply(skeleton, animationLast, animationTime, eventBuffer, 0, MixBlend.Setup, MixDirection.Out);
  402. }
  403. if (to.mixDuration > 0) QueueEvents(from, animationTime);
  404. this.events.Clear(false);
  405. from.nextAnimationLast = animationTime;
  406. from.nextTrackLast = from.trackTime;
  407. return mix;
  408. }
  409. /// <summary> Applies the attachment timeline and sets <see cref="Slot.attachmentState"/>.</summary>
  410. /// <param name="attachments">False when: 1) the attachment timeline is mixing out, 2) mix < attachmentThreshold, and 3) the timeline
  411. /// is not the last timeline to set the slot's attachment. In that case the timeline is applied only so subsequent
  412. /// timelines see any deform.</param>
  413. private void ApplyAttachmentTimeline (AttachmentTimeline timeline, Skeleton skeleton, float time, MixBlend blend,
  414. bool attachments) {
  415. Slot slot = skeleton.slots.Items[timeline.slotIndex];
  416. if (!slot.bone.active) return;
  417. float[] frames = timeline.frames;
  418. if (time < frames[0]) { // Time is before first frame.
  419. if (blend == MixBlend.Setup || blend == MixBlend.First)
  420. SetAttachment(skeleton, slot, slot.data.attachmentName, attachments);
  421. }
  422. else {
  423. int frameIndex;
  424. if (time >= frames[frames.Length - 1]) // Time is after last frame.
  425. frameIndex = frames.Length - 1;
  426. else
  427. frameIndex = Animation.BinarySearch(frames, time) - 1;
  428. SetAttachment(skeleton, slot, timeline.attachmentNames[frameIndex], attachments);
  429. }
  430. // If an attachment wasn't set (ie before the first frame or attachments is false), set the setup attachment later.
  431. if (slot.attachmentState <= unkeyedState) slot.attachmentState = unkeyedState + Setup;
  432. }
  433. private void SetAttachment (Skeleton skeleton, Slot slot, String attachmentName, bool attachments) {
  434. slot.Attachment = attachmentName == null ? null : skeleton.GetAttachment(slot.data.index, attachmentName);
  435. if (attachments) slot.attachmentState = unkeyedState + Current;
  436. }
  437. /// <summary>
  438. /// Applies the rotate timeline, mixing with the current pose while keeping the same rotation direction chosen as the shortest
  439. /// the first time the mixing was applied.</summary>
  440. static private void ApplyRotateTimeline (RotateTimeline timeline, Skeleton skeleton, float time, float alpha, MixBlend blend,
  441. float[] timelinesRotation, int i, bool firstFrame) {
  442. if (firstFrame) timelinesRotation[i] = 0;
  443. if (alpha == 1) {
  444. timeline.Apply(skeleton, 0, time, null, 1, blend, MixDirection.In);
  445. return;
  446. }
  447. Bone bone = skeleton.bones.Items[timeline.boneIndex];
  448. if (!bone.active) return;
  449. float[] frames = timeline.frames;
  450. float r1, r2;
  451. if (time < frames[0]) { // Time is before first frame.
  452. switch (blend) {
  453. case MixBlend.Setup:
  454. bone.rotation = bone.data.rotation;
  455. return;
  456. default:
  457. return;
  458. case MixBlend.First:
  459. r1 = bone.rotation;
  460. r2 = bone.data.rotation;
  461. break;
  462. }
  463. } else {
  464. r1 = blend == MixBlend.Setup ? bone.data.rotation : bone.rotation;
  465. if (time >= frames[frames.Length - RotateTimeline.ENTRIES]) // Time is after last frame.
  466. r2 = bone.data.rotation + frames[frames.Length + RotateTimeline.PREV_ROTATION];
  467. else {
  468. // Interpolate between the previous frame and the current frame.
  469. int frame = Animation.BinarySearch(frames, time, RotateTimeline.ENTRIES);
  470. float prevRotation = frames[frame + RotateTimeline.PREV_ROTATION];
  471. float frameTime = frames[frame];
  472. float percent = timeline.GetCurvePercent((frame >> 1) - 1,
  473. 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
  474. r2 = frames[frame + RotateTimeline.ROTATION] - prevRotation;
  475. r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
  476. r2 = prevRotation + r2 * percent + bone.data.rotation;
  477. r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360;
  478. }
  479. }
  480. // Mix between rotations using the direction of the shortest route on the first frame.
  481. float total, diff = r2 - r1;
  482. diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360;
  483. if (diff == 0) {
  484. total = timelinesRotation[i];
  485. } else {
  486. float lastTotal, lastDiff;
  487. if (firstFrame) {
  488. lastTotal = 0;
  489. lastDiff = diff;
  490. } else {
  491. lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops.
  492. lastDiff = timelinesRotation[i + 1]; // Difference between bones.
  493. }
  494. bool current = diff > 0, dir = lastTotal >= 0;
  495. // Detect cross at 0 (not 180).
  496. if (Math.Sign(lastDiff) != Math.Sign(diff) && Math.Abs(lastDiff) <= 90) {
  497. // A cross after a 360 rotation is a loop.
  498. if (Math.Abs(lastTotal) > 180) lastTotal += 360 * Math.Sign(lastTotal);
  499. dir = current;
  500. }
  501. total = diff + lastTotal - lastTotal % 360; // Store loops as part of lastTotal.
  502. if (dir != current) total += 360 * Math.Sign(lastTotal);
  503. timelinesRotation[i] = total;
  504. }
  505. timelinesRotation[i + 1] = diff;
  506. r1 += total * alpha;
  507. bone.rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360;
  508. }
  509. private void QueueEvents (TrackEntry entry, float animationTime) {
  510. float animationStart = entry.animationStart, animationEnd = entry.animationEnd;
  511. float duration = animationEnd - animationStart;
  512. float trackLastWrapped = entry.trackLast % duration;
  513. // Queue events before complete.
  514. var events = this.events;
  515. var eventsItems = events.Items;
  516. int i = 0, n = events.Count;
  517. for (; i < n; i++) {
  518. Event e = eventsItems[i];
  519. if (e.time < trackLastWrapped) break;
  520. if (e.time > animationEnd) continue; // Discard events outside animation start/end.
  521. queue.Event(entry, e);
  522. }
  523. // Queue complete if completed a loop iteration or the animation.
  524. bool complete = false;
  525. if (entry.loop)
  526. complete = duration == 0 || (trackLastWrapped > entry.trackTime % duration);
  527. else
  528. complete = animationTime >= animationEnd && entry.animationLast < animationEnd;
  529. if (complete) queue.Complete(entry);
  530. // Queue events after complete.
  531. for (; i < n; i++) {
  532. Event e = eventsItems[i];
  533. if (e.time < animationStart) continue; // Discard events outside animation start/end.
  534. queue.Event(entry, eventsItems[i]);
  535. }
  536. }
  537. /// <summary>
  538. /// <para>Removes all animations from all tracks, leaving skeletons in their current pose.</para>
  539. /// <para>
  540. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimations(float)"/> to mix the skeletons back to the setup pose,
  541. /// rather than leaving them in their current pose.</para>
  542. /// </summary>
  543. public void ClearTracks () {
  544. bool oldDrainDisabled = queue.drainDisabled;
  545. queue.drainDisabled = true;
  546. for (int i = 0, n = tracks.Count; i < n; i++) {
  547. ClearTrack(i);
  548. }
  549. tracks.Clear();
  550. queue.drainDisabled = oldDrainDisabled;
  551. queue.Drain();
  552. }
  553. /// <summary>
  554. /// <para>Removes all animations from the track, leaving skeletons in their current pose.</para>
  555. /// <para>
  556. /// It may be desired to use <see cref="AnimationState.SetEmptyAnimation(int, float)"/> to mix the skeletons back to the setup pose,
  557. /// rather than leaving them in their current pose.</para>
  558. /// </summary>
  559. public void ClearTrack (int trackIndex) {
  560. if (trackIndex >= tracks.Count) return;
  561. TrackEntry current = tracks.Items[trackIndex];
  562. if (current == null) return;
  563. queue.End(current);
  564. DisposeNext(current);
  565. TrackEntry entry = current;
  566. while (true) {
  567. TrackEntry from = entry.mixingFrom;
  568. if (from == null) break;
  569. queue.End(from);
  570. entry.mixingFrom = null;
  571. entry.mixingTo = null;
  572. entry = from;
  573. }
  574. tracks.Items[current.trackIndex] = null;
  575. queue.Drain();
  576. }
  577. /// <summary>Sets the active TrackEntry for a given track number.</summary>
  578. private void SetCurrent (int index, TrackEntry current, bool interrupt) {
  579. TrackEntry from = ExpandToIndex(index);
  580. tracks.Items[index] = current;
  581. if (from != null) {
  582. if (interrupt) queue.Interrupt(from);
  583. current.mixingFrom = from;
  584. from.mixingTo = current;
  585. current.mixTime = 0;
  586. // Store the interrupted mix percentage.
  587. if (from.mixingFrom != null && from.mixDuration > 0)
  588. current.interruptAlpha *= Math.Min(1, from.mixTime / from.mixDuration);
  589. from.timelinesRotation.Clear(); // Reset rotation for mixing out, in case entry was mixed in.
  590. }
  591. queue.Start(current); // triggers AnimationsChanged
  592. }
  593. /// <summary>Sets an animation by name. <seealso cref="SetAnimation(int, Animation, bool)" /></summary>
  594. public TrackEntry SetAnimation (int trackIndex, string animationName, bool loop) {
  595. Animation animation = data.skeletonData.FindAnimation(animationName);
  596. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  597. return SetAnimation(trackIndex, animation, loop);
  598. }
  599. /// <summary>Sets the current animation for a track, discarding any queued animations. If the formerly current track entry was never
  600. /// applied to a skeleton, it is replaced (not mixed from).</summary>
  601. /// <param name="loop">If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
  602. /// duration. In either case<see cref="TrackEntry.TrackEnd"/> determines when the track is cleared.</param>
  603. /// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
  604. /// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
  605. public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) {
  606. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  607. bool interrupt = true;
  608. TrackEntry current = ExpandToIndex(trackIndex);
  609. if (current != null) {
  610. if (current.nextTrackLast == -1) {
  611. // Don't mix from an entry that was never applied.
  612. tracks.Items[trackIndex] = current.mixingFrom;
  613. queue.Interrupt(current);
  614. queue.End(current);
  615. DisposeNext(current);
  616. current = current.mixingFrom;
  617. interrupt = false; // mixingFrom is current again, but don't interrupt it twice.
  618. } else {
  619. DisposeNext(current);
  620. }
  621. }
  622. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, current);
  623. SetCurrent(trackIndex, entry, interrupt);
  624. queue.Drain();
  625. return entry;
  626. }
  627. /// <summary>Queues an animation by name.</summary>
  628. /// <seealso cref="AddAnimation(int, Animation, bool, float)" />
  629. public TrackEntry AddAnimation (int trackIndex, string animationName, bool loop, float delay) {
  630. Animation animation = data.skeletonData.FindAnimation(animationName);
  631. if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName");
  632. return AddAnimation(trackIndex, animation, loop, delay);
  633. }
  634. /// <summary>Adds an animation to be played after the current or last queued animation for a track. If the track is empty, it is
  635. /// equivalent to calling <see cref="SetAnimation(int, Animation, bool)"/>.</summary>
  636. /// <param name="delay">
  637. /// If &gt; 0, sets <see cref="TrackEntry.Delay"/>. If &lt;= 0, the delay set is the duration of the previous track entry
  638. /// minus any mix duration (from the {@link AnimationStateData}) plus the specified <code>Delay</code> (ie the mix
  639. /// ends at (<code>Delay</code> = 0) or before (<code>Delay</code> &lt; 0) the previous track entry duration). If the
  640. /// previous entry is looping, its next loop completion is used instead of its duration.
  641. /// </param>
  642. /// <returns>A track entry to allow further customization of animation playback. References to the track entry must not be kept
  643. /// after the <see cref="AnimationState.Dispose"/> event occurs.</returns>
  644. public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) {
  645. if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null.");
  646. TrackEntry last = ExpandToIndex(trackIndex);
  647. if (last != null) {
  648. while (last.next != null)
  649. last = last.next;
  650. }
  651. TrackEntry entry = NewTrackEntry(trackIndex, animation, loop, last);
  652. if (last == null) {
  653. SetCurrent(trackIndex, entry, true);
  654. queue.Drain();
  655. } else {
  656. last.next = entry;
  657. if (delay <= 0) {
  658. float duration = last.animationEnd - last.animationStart;
  659. if (duration != 0) {
  660. if (last.loop) {
  661. delay += duration * (1 + (int)(last.trackTime / duration)); // Completion of next loop.
  662. } else {
  663. delay += Math.Max(duration, last.trackTime); // After duration, else next update.
  664. }
  665. delay -= data.GetMix(last.animation, animation);
  666. } else
  667. delay = last.trackTime; // Next update.
  668. }
  669. }
  670. entry.delay = delay;
  671. return entry;
  672. }
  673. /// <summary>
  674. /// <para>Sets an empty animation for a track, discarding any queued animations, and sets the track entry's
  675. /// <see cref="TrackEntry.getMixDuration()"/>. An empty animation has no timelines and serves as a placeholder for mixing in or out.</para>
  676. /// <para>
  677. /// Mixing out is done by setting an empty animation with a mix duration using either <see cref="AnimationState.SetEmptyAnimation(int, float)"/>,
  678. /// <see cref="AnimationState.SetEmptyAnimations(float)"/>, or <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/>. Mixing to an empty animation causes
  679. /// the previous animation to be applied less and less over the mix duration. Properties keyed in the previous animation
  680. /// transition to the value from lower tracks or to the setup pose value if no lower tracks key the property. A mix duration of
  681. /// 0 still mixes out over one frame.</para>
  682. /// <para>
  683. /// Mixing in is done by first setting an empty animation, then adding an animation using
  684. /// <see cref="AnimationState.AddAnimation(int, Animation, boolean, float)"/> and on the returned track entry, set the
  685. /// <see cref="TrackEntry.SetMixDuration(float)"/>. Mixing from an empty animation causes the new animation to be applied more and
  686. /// more over the mix duration. Properties keyed in the new animation transition from the value from lower tracks or from the
  687. /// setup pose value if no lower tracks key the property to the value keyed in the new animation.</para>
  688. /// </summary>
  689. public TrackEntry SetEmptyAnimation (int trackIndex, float mixDuration) {
  690. TrackEntry entry = SetAnimation(trackIndex, AnimationState.EmptyAnimation, false);
  691. entry.mixDuration = mixDuration;
  692. entry.trackEnd = mixDuration;
  693. return entry;
  694. }
  695. /// <summary>
  696. /// Adds an empty animation to be played after the current or last queued animation for a track, and sets the track entry's
  697. /// <see cref="TrackEntry.MixDuration"/>. If the track is empty, it is equivalent to calling
  698. /// <see cref="AnimationState.SetEmptyAnimation(int, float)"/>.</summary>
  699. /// <seealso cref="AnimationState.SetEmptyAnimation(int, float)"/>
  700. /// <param name="trackIndex">Track number.</param>
  701. /// <param name="mixDuration">Mix duration.</param>
  702. /// <param name="delay">If &gt; 0, sets <see cref="TrackEntry.Delay"/>. If &lt;= 0, the delay set is the duration of the previous track entry
  703. /// minus any mix duration plus the specified <code>Delay</code> (ie the mix ends at (<code>Delay</code> = 0) or
  704. /// before (<code>Delay</code> &lt; 0) the previous track entry duration). If the previous entry is looping, its next
  705. /// loop completion is used instead of its duration.</param>
  706. /// <returns> A track entry to allow further customization of animation playback. References to the track entry must not be kept
  707. /// after the <see cref="AnimationState.Dispose"/> event occurs.
  708. /// </returns>
  709. public TrackEntry AddEmptyAnimation (int trackIndex, float mixDuration, float delay) {
  710. if (delay <= 0) delay -= mixDuration;
  711. TrackEntry entry = AddAnimation(trackIndex, AnimationState.EmptyAnimation, false, delay);
  712. entry.mixDuration = mixDuration;
  713. entry.trackEnd = mixDuration;
  714. return entry;
  715. }
  716. /// <summary>
  717. /// Sets an empty animation for every track, discarding any queued animations, and mixes to it over the specified mix
  718. /// duration.</summary>
  719. public void SetEmptyAnimations (float mixDuration) {
  720. bool oldDrainDisabled = queue.drainDisabled;
  721. queue.drainDisabled = true;
  722. for (int i = 0, n = tracks.Count; i < n; i++) {
  723. TrackEntry current = tracks.Items[i];
  724. if (current != null) SetEmptyAnimation(current.trackIndex, mixDuration);
  725. }
  726. queue.drainDisabled = oldDrainDisabled;
  727. queue.Drain();
  728. }
  729. private TrackEntry ExpandToIndex (int index) {
  730. if (index < tracks.Count) return tracks.Items[index];
  731. tracks.Resize(index + 1);
  732. return null;
  733. }
  734. /// <summary>Object-pooling version of new TrackEntry. Obtain an unused TrackEntry from the pool and clear/initialize its values.</summary>
  735. /// <param name="last">May be null.</param>
  736. private TrackEntry NewTrackEntry (int trackIndex, Animation animation, bool loop, TrackEntry last) {
  737. TrackEntry entry = trackEntryPool.Obtain(); // Pooling
  738. entry.trackIndex = trackIndex;
  739. entry.animation = animation;
  740. entry.loop = loop;
  741. entry.holdPrevious = false;
  742. entry.eventThreshold = 0;
  743. entry.attachmentThreshold = 0;
  744. entry.drawOrderThreshold = 0;
  745. entry.animationStart = 0;
  746. entry.animationEnd = animation.Duration;
  747. entry.animationLast = -1;
  748. entry.nextAnimationLast = -1;
  749. entry.delay = 0;
  750. entry.trackTime = 0;
  751. entry.trackLast = -1;
  752. entry.nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet.
  753. entry.trackEnd = float.MaxValue; // loop ? float.MaxValue : animation.Duration;
  754. entry.timeScale = 1;
  755. entry.alpha = 1;
  756. entry.interruptAlpha = 1;
  757. entry.mixTime = 0;
  758. entry.mixDuration = (last == null) ? 0 : data.GetMix(last.animation, animation);
  759. return entry;
  760. }
  761. /// <summary>Dispose all track entries queued after the given TrackEntry.</summary>
  762. private void DisposeNext (TrackEntry entry) {
  763. TrackEntry next = entry.next;
  764. while (next != null) {
  765. queue.Dispose(next);
  766. next = next.next;
  767. }
  768. entry.next = null;
  769. }
  770. private void AnimationsChanged () {
  771. animationsChanged = false;
  772. // Process in the order that animations are applied.
  773. propertyIDs.Clear();
  774. var tracksItems = tracks.Items;
  775. for (int i = 0, n = tracks.Count; i < n; i++) {
  776. TrackEntry entry = tracksItems[i];
  777. if (entry == null) continue;
  778. while (entry.mixingFrom != null) // Move to last entry, then iterate in reverse.
  779. entry = entry.mixingFrom;
  780. do {
  781. if (entry.mixingTo == null || entry.mixBlend != MixBlend.Add) ComputeHold(entry);
  782. entry = entry.mixingTo;
  783. } while (entry != null);
  784. }
  785. }
  786. private void ComputeHold (TrackEntry entry) {
  787. TrackEntry to = entry.mixingTo;
  788. var timelines = entry.animation.timelines.Items;
  789. int timelinesCount = entry.animation.timelines.Count;
  790. var timelineMode = entry.timelineMode.Resize(timelinesCount).Items; //timelineMode.setSize(timelinesCount);
  791. entry.timelineHoldMix.Clear();
  792. var timelineHoldMix = entry.timelineHoldMix.Resize(timelinesCount).Items; //timelineHoldMix.setSize(timelinesCount);
  793. var propertyIDs = this.propertyIDs;
  794. if (to != null && to.holdPrevious) {
  795. for (int i = 0; i < timelinesCount; i++)
  796. timelineMode[i] = propertyIDs.Add(timelines[i].PropertyId) ? AnimationState.HoldFirst : AnimationState.HoldSubsequent;
  797. return;
  798. }
  799. // outer:
  800. for (int i = 0; i < timelinesCount; i++) {
  801. Timeline timeline = timelines[i];
  802. int id = timeline.PropertyId;
  803. if (!propertyIDs.Add(id))
  804. timelineMode[i] = AnimationState.Subsequent;
  805. else if (to == null || timeline is AttachmentTimeline || timeline is DrawOrderTimeline
  806. || timeline is EventTimeline || !to.animation.HasTimeline(id)) {
  807. timelineMode[i] = AnimationState.First;
  808. } else {
  809. for (TrackEntry next = to.mixingTo; next != null; next = next.mixingTo) {
  810. if (next.animation.HasTimeline(id)) continue;
  811. if (next.mixDuration > 0) {
  812. timelineMode[i] = AnimationState.HoldMix;
  813. timelineHoldMix[i] = next;
  814. goto continue_outer; // continue outer;
  815. }
  816. break;
  817. }
  818. timelineMode[i] = AnimationState.HoldFirst;
  819. }
  820. continue_outer: {}
  821. }
  822. }
  823. /// <returns>The track entry for the animation currently playing on the track, or null if no animation is currently playing.</returns>
  824. public TrackEntry GetCurrent (int trackIndex) {
  825. if (trackIndex >= tracks.Count) return null;
  826. return tracks.Items[trackIndex];
  827. }
  828. /// <summary> Discards all listener notifications that have not yet been delivered. This can be useful to call from an
  829. /// AnimationState event subscriber when it is known that further notifications that may have been already queued for delivery
  830. /// are not wanted because new animations are being set.
  831. public void ClearListenerNotifications () {
  832. queue.Clear();
  833. }
  834. /// <summary>
  835. /// <para>Multiplier for the delta time when the animation state is updated, causing time for all animations and mixes to play slower
  836. /// or faster. Defaults to 1.</para>
  837. /// <para>
  838. /// See TrackEntry <see cref="TrackEntry.TimeScale"/> for affecting a single animation.</para>
  839. /// </summary>
  840. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  841. /// <summary>The AnimationStateData to look up mix durations.</summary>
  842. public AnimationStateData Data {
  843. get {
  844. return data;
  845. }
  846. set {
  847. if (data == null) throw new ArgumentNullException("data", "data cannot be null.");
  848. this.data = value;
  849. }
  850. }
  851. /// <summary>A list of tracks that have animations, which may contain nulls.</summary>
  852. public ExposedList<TrackEntry> Tracks { get { return tracks; } }
  853. override public string ToString () {
  854. var buffer = new System.Text.StringBuilder();
  855. for (int i = 0, n = tracks.Count; i < n; i++) {
  856. TrackEntry entry = tracks.Items[i];
  857. if (entry == null) continue;
  858. if (buffer.Length > 0) buffer.Append(", ");
  859. buffer.Append(entry.ToString());
  860. }
  861. if (buffer.Length == 0) return "<none>";
  862. return buffer.ToString();
  863. }
  864. }
  865. /// <summary>
  866. /// <para>
  867. /// Stores settings and other state for the playback of an animation on an <see cref="AnimationState"/> track.</para>
  868. /// <para>
  869. /// References to a track entry must not be kept after the <see cref="AnimationStateListener.Dispose(TrackEntry)"/> event occurs.</para>
  870. /// </summary>
  871. public class TrackEntry : Pool<TrackEntry>.IPoolable {
  872. internal Animation animation;
  873. internal TrackEntry next, mixingFrom, mixingTo;
  874. // difference to libgdx reference: delegates are used for event callbacks instead of 'AnimationStateListener listener'.
  875. public event AnimationState.TrackEntryDelegate Start, Interrupt, End, Dispose, Complete;
  876. public event AnimationState.TrackEntryEventDelegate Event;
  877. internal void OnStart () { if (Start != null) Start(this); }
  878. internal void OnInterrupt () { if (Interrupt != null) Interrupt(this); }
  879. internal void OnEnd () { if (End != null) End(this); }
  880. internal void OnDispose () { if (Dispose != null) Dispose(this); }
  881. internal void OnComplete () { if (Complete != null) Complete(this); }
  882. internal void OnEvent (Event e) { if (Event != null) Event(this, e); }
  883. internal int trackIndex;
  884. internal bool loop, holdPrevious;
  885. internal float eventThreshold, attachmentThreshold, drawOrderThreshold;
  886. internal float animationStart, animationEnd, animationLast, nextAnimationLast;
  887. internal float delay, trackTime, trackLast, nextTrackLast, trackEnd, timeScale = 1f;
  888. internal float alpha, mixTime, mixDuration, interruptAlpha, totalAlpha;
  889. internal MixBlend mixBlend = MixBlend.Replace;
  890. internal readonly ExposedList<int> timelineMode = new ExposedList<int>();
  891. internal readonly ExposedList<TrackEntry> timelineHoldMix = new ExposedList<TrackEntry>();
  892. internal readonly ExposedList<float> timelinesRotation = new ExposedList<float>();
  893. // IPoolable.Reset()
  894. public void Reset () {
  895. next = null;
  896. mixingFrom = null;
  897. mixingTo = null;
  898. animation = null;
  899. // replaces 'listener = null;' since delegates are used for event callbacks
  900. Start = null;
  901. Interrupt = null;
  902. End = null;
  903. Dispose = null;
  904. Complete = null;
  905. Event = null;
  906. timelineMode.Clear();
  907. timelineHoldMix.Clear();
  908. timelinesRotation.Clear();
  909. }
  910. /// <summary>The index of the track where this entry is either current or queued.</summary>
  911. /// <seealso cref="AnimationState.GetCurrent(int)"/>
  912. public int TrackIndex { get { return trackIndex; } }
  913. /// <summary>The animation to apply for this track entry.</summary>
  914. public Animation Animation { get { return animation; } }
  915. /// <summary>
  916. /// If true, the animation will repeat. If false it will not, instead its last frame is applied if played beyond its
  917. /// duration.</summary>
  918. public bool Loop { get { return loop; } set { loop = value; } }
  919. ///<summary>
  920. /// <para>
  921. /// Seconds to postpone playing the animation. When this track entry is the current track entry, <code>Delay</code>
  922. /// postpones incrementing the <see cref="TrackEntry.TrackTime"/>. When this track entry is queued, <code>Delay</code> is the time from
  923. /// the start of the previous animation to when this track entry will become the current track entry (ie when the previous
  924. /// track entry <see cref="TrackEntry.TrackTime"/> &gt;= this track entry's <code>Delay</code>).</para>
  925. /// <para>
  926. /// <see cref="TrackEntry.TimeScale"/> affects the delay.</para>
  927. /// </summary>
  928. public float Delay { get { return delay; } set { delay = value; } }
  929. /// <summary>
  930. /// Current time in seconds this track entry has been the current track entry. The track time determines
  931. /// <see cref="TrackEntry.AnimationTime"/>. The track time can be set to start the animation at a time other than 0, without affecting
  932. /// looping.</summary>
  933. public float TrackTime { get { return trackTime; } set { trackTime = value; } }
  934. /// <summary>
  935. /// <para>
  936. /// The track time in seconds when this animation will be removed from the track. Defaults to the highest possible float
  937. /// value, meaning the animation will be applied until a new animation is set or the track is cleared. If the track end time
  938. /// is reached, no other animations are queued for playback, and mixing from any previous animations is complete, then the
  939. /// properties keyed by the animation are set to the setup pose and the track is cleared.</para>
  940. /// <para>
  941. /// It may be desired to use <see cref="AnimationState.AddEmptyAnimation(int, float, float)"/> rather than have the animation
  942. /// abruptly cease being applied.</para>
  943. /// </summary>
  944. public float TrackEnd { get { return trackEnd; } set { trackEnd = value; } }
  945. /// <summary>
  946. /// <para>
  947. /// Seconds when this animation starts, both initially and after looping. Defaults to 0.</para>
  948. /// <para>
  949. /// When changing the <code>AnimationStart</code> time, it often makes sense to set <see cref="TrackEntry.AnimationLast"> to the same
  950. /// value to prevent timeline keys before the start time from triggering.</para>
  951. /// </summary>
  952. public float AnimationStart { get { return animationStart; } set { animationStart = value; } }
  953. /// <summary>
  954. /// Seconds for the last frame of this animation. Non-looping animations won't play past this time. Looping animations will
  955. /// loop back to <see cref="TrackEntry.AnimationStart"/> at this time. Defaults to the animation <see cref="Animation.Duration"/>.
  956. ///</summary>
  957. public float AnimationEnd { get { return animationEnd; } set { animationEnd = value; } }
  958. /// <summary>
  959. /// The time in seconds this animation was last applied. Some timelines use this for one-time triggers. Eg, when this
  960. /// animation is applied, event timelines will fire all events between the <code>AnimationLast</code> time (exclusive) and
  961. /// <code>AnimationTime</code> (inclusive). Defaults to -1 to ensure triggers on frame 0 happen the first time this animation
  962. /// is applied.</summary>
  963. public float AnimationLast {
  964. get { return animationLast; }
  965. set {
  966. animationLast = value;
  967. nextAnimationLast = value;
  968. }
  969. }
  970. /// <summary>
  971. /// Uses <see cref="TrackEntry.TrackTime"/> to compute the <code>AnimationTime</code>, which is between <see cref="TrackEntry.AnimationStart"/>
  972. /// and <see cref="TrackEntry.AnimationEnd"/>. When the <code>TrackTime</code> is 0, the <code>AnimationTime</code> is equal to the
  973. /// <code>AnimationStart</code> time.
  974. /// </summary>
  975. public float AnimationTime {
  976. get {
  977. if (loop) {
  978. float duration = animationEnd - animationStart;
  979. if (duration == 0) return animationStart;
  980. return (trackTime % duration) + animationStart;
  981. }
  982. return Math.Min(trackTime + animationStart, animationEnd);
  983. }
  984. }
  985. /// <summary>
  986. /// <para>
  987. /// Multiplier for the delta time when this track entry is updated, causing time for this animation to pass slower or
  988. /// faster. Defaults to 1.</para>
  989. /// <para>
  990. /// <see cref="TrackEntry.MixTime"/> is not affected by track entry time scale, so <see cref="TrackEntry.MixDuration"/> may need to be adjusted to
  991. /// match the animation speed.</para>
  992. /// <para>
  993. /// When using <see cref="AnimationState.AddAnimation(int, Animation, boolean, float)"> with a <code>Delay</code> <= 0, note the
  994. /// {<see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref="AnimationStateData"/>, assuming time scale to be 1. If
  995. /// the time scale is not 1, the delay may need to be adjusted.</para>
  996. /// <para>
  997. /// See AnimationState <see cref="AnimationState.TimeScale"/> for affecting all animations.</para>
  998. /// </summary>
  999. public float TimeScale { get { return timeScale; } set { timeScale = value; } }
  1000. /// <summary>
  1001. /// <para>
  1002. /// Values < 1 mix this animation with the skeleton's current pose (usually the pose resulting from lower tracks). Defaults
  1003. /// to 1, which overwrites the skeleton's current pose with this animation.</para>
  1004. /// <para>
  1005. /// Typically track 0 is used to completely pose the skeleton, then alpha is used on higher tracks. It doesn't make sense to
  1006. /// use alpha on track 0 if the skeleton pose is from the last frame render.</para>
  1007. /// </summary>
  1008. public float Alpha { get { return alpha; } set { alpha = value; } }
  1009. /// <summary>
  1010. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1011. /// <code>EventThreshold</code>, event timelines are applied while this animation is being mixed out. Defaults to 0, so event
  1012. /// timelines are not applied while this animation is being mixed out.
  1013. /// </summary>
  1014. public float EventThreshold { get { return eventThreshold; } set { eventThreshold = value; } }
  1015. /// <summary>
  1016. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1017. /// <code>AttachmentThreshold</code>, attachment timelines are applied while this animation is being mixed out. Defaults to
  1018. /// 0, so attachment timelines are not applied while this animation is being mixed out.
  1019. ///</summary>
  1020. public float AttachmentThreshold { get { return attachmentThreshold; } set { attachmentThreshold = value; } }
  1021. /// <summary>
  1022. /// When the mix percentage (<see cref="TrackEntry.MixTime"/> / <see cref="TrackEntry.MixDuration"/>) is less than the
  1023. /// <code>DrawOrderThreshold</code>, draw order timelines are applied while this animation is being mixed out. Defaults to 0,
  1024. /// so draw order timelines are not applied while this animation is being mixed out.
  1025. /// </summary>
  1026. public float DrawOrderThreshold { get { return drawOrderThreshold; } set { drawOrderThreshold = value; } }
  1027. /// <summary>
  1028. /// The animation queued to start after this animation, or null. <code>Next</code> makes up a linked list. </summary>
  1029. public TrackEntry Next { get { return next; } }
  1030. /// <summary>
  1031. /// Returns true if at least one loop has been completed.</summary>
  1032. /// <seealso cref="TrackEntry.Complete"/>
  1033. public bool IsComplete {
  1034. get { return trackTime >= animationEnd - animationStart; }
  1035. }
  1036. /// <summary>
  1037. /// Seconds from 0 to the <see cref="TrackEntry.MixDuration"/> when mixing from the previous animation to this animation. May be
  1038. /// slightly more than <code>MixDuration</code> when the mix is complete.</summary>
  1039. public float MixTime { get { return mixTime; } set { mixTime = value; } }
  1040. /// <summary>
  1041. /// <para>
  1042. /// Seconds for mixing from the previous animation to this animation. Defaults to the value provided by AnimationStateData
  1043. /// <see cref="AnimationStateData.GetMix(Animation, Animation)"/> based on the animation before this animation (if any).</para>
  1044. /// <para>
  1045. /// The <code>MixDuration</code> can be set manually rather than use the value from
  1046. /// <see cref="AnimationStateData.GetMix(Animation, Animation)"/>. In that case, the <code>MixDuration</code> can be set for a new
  1047. /// track entry only before <see cref="AnimationState.Update(float)"/> is first called.</para>
  1048. /// <para>
  1049. /// When using <seealso cref="AnimationState.AddAnimation(int, Animation, bool, float)"/> with a <code>Delay</code> &lt;= 0, note the
  1050. /// <see cref="TrackEntry.Delay"/> is set using the mix duration from the <see cref=" AnimationStateData"/>, not a mix duration set
  1051. /// afterward.</para>
  1052. /// </summary>
  1053. public float MixDuration { get { return mixDuration; } set { mixDuration = value; } }
  1054. /// <summary>
  1055. /// <para>
  1056. /// Controls how properties keyed in the animation are mixed with lower tracks. Defaults to <see cref="MixBlend.Replace"/>, which
  1057. /// replaces the values from the lower tracks with the animation values. <see cref="MixBlend.Add"/> adds the animation values to
  1058. /// the values from the lower tracks.</para>
  1059. /// <para>
  1060. /// The <code>MixBlend</code> can be set for a new track entry only before <see cref="AnimationState.Apply(Skeleton)"/> is first
  1061. /// called.</para>
  1062. /// </summary>
  1063. public MixBlend MixBlend { get { return mixBlend; } set { mixBlend = value; } }
  1064. /// <summary>
  1065. /// The track entry for the previous animation when mixing from the previous animation to this animation, or null if no
  1066. /// mixing is currently occuring. When mixing from multiple animations, <code>MixingFrom</code> makes up a linked list.</summary>
  1067. public TrackEntry MixingFrom { get { return mixingFrom; } }
  1068. /// <summary>
  1069. /// The track entry for the next animation when mixing from this animation to the next animation, or null if no mixing is
  1070. /// currently occuring. When mixing to multiple animations, <code>MixingTo</code> makes up a linked list.</summary>
  1071. public TrackEntry MixingTo { get { return mixingTo; } }
  1072. /// <summary>
  1073. /// <para>
  1074. /// If true, when mixing from the previous animation to this animation, the previous animation is applied as normal instead
  1075. /// of being mixed out.</para>
  1076. /// <para>
  1077. /// When mixing between animations that key the same property, if a lower track also keys that property then the value will
  1078. /// briefly dip toward the lower track value during the mix. This happens because the first animation mixes from 100% to 0%
  1079. /// while the second animation mixes from 0% to 100%. Setting <code>HoldPrevious</code> to true applies the first animation
  1080. /// at 100% during the mix so the lower track value is overwritten. Such dipping does not occur on the lowest track which
  1081. /// keys the property, only when a higher track also keys the property.</para>
  1082. /// <para>
  1083. /// Snapping will occur if <code>HoldPrevious</code> is true and this animation does not key all the same properties as the
  1084. /// previous animation.</para>
  1085. /// </summary>
  1086. public bool HoldPrevious { get { return holdPrevious; } set { holdPrevious = value; } }
  1087. /// <summary>
  1088. /// <para>
  1089. /// Resets the rotation directions for mixing this entry's rotate timelines. This can be useful to avoid bones rotating the
  1090. /// long way around when using <see cref="alpha"/> and starting animations on other tracks.</para>
  1091. /// <para>
  1092. /// Mixing with <see cref="MixBlend.Replace"/> involves finding a rotation between two others, which has two possible solutions:
  1093. /// the short way or the long way around. The two rotations likely change over time, so which direction is the short or long
  1094. /// way also changes. If the short way was always chosen, bones would flip to the other side when that direction became the
  1095. /// long way. TrackEntry chooses the short way the first time it is applied and remembers that direction.</para>
  1096. /// </summary>
  1097. public void ResetRotationDirections () {
  1098. timelinesRotation.Clear();
  1099. }
  1100. override public string ToString () {
  1101. return animation == null ? "<none>" : animation.name;
  1102. }
  1103. }
  1104. class EventQueue {
  1105. private readonly List<EventQueueEntry> eventQueueEntries = new List<EventQueueEntry>();
  1106. internal bool drainDisabled;
  1107. private readonly AnimationState state;
  1108. private readonly Pool<TrackEntry> trackEntryPool;
  1109. internal event Action AnimationsChanged;
  1110. internal EventQueue (AnimationState state, Action HandleAnimationsChanged, Pool<TrackEntry> trackEntryPool) {
  1111. this.state = state;
  1112. this.AnimationsChanged += HandleAnimationsChanged;
  1113. this.trackEntryPool = trackEntryPool;
  1114. }
  1115. struct EventQueueEntry {
  1116. public EventType type;
  1117. public TrackEntry entry;
  1118. public Event e;
  1119. public EventQueueEntry (EventType eventType, TrackEntry trackEntry, Event e = null) {
  1120. this.type = eventType;
  1121. this.entry = trackEntry;
  1122. this.e = e;
  1123. }
  1124. }
  1125. enum EventType {
  1126. Start, Interrupt, End, Dispose, Complete, Event
  1127. }
  1128. internal void Start (TrackEntry entry) {
  1129. eventQueueEntries.Add(new EventQueueEntry(EventType.Start, entry));
  1130. if (AnimationsChanged != null) AnimationsChanged();
  1131. }
  1132. internal void Interrupt (TrackEntry entry) {
  1133. eventQueueEntries.Add(new EventQueueEntry(EventType.Interrupt, entry));
  1134. }
  1135. internal void End (TrackEntry entry) {
  1136. eventQueueEntries.Add(new EventQueueEntry(EventType.End, entry));
  1137. if (AnimationsChanged != null) AnimationsChanged();
  1138. }
  1139. internal void Dispose (TrackEntry entry) {
  1140. eventQueueEntries.Add(new EventQueueEntry(EventType.Dispose, entry));
  1141. }
  1142. internal void Complete (TrackEntry entry) {
  1143. eventQueueEntries.Add(new EventQueueEntry(EventType.Complete, entry));
  1144. }
  1145. internal void Event (TrackEntry entry, Event e) {
  1146. eventQueueEntries.Add(new EventQueueEntry(EventType.Event, entry, e));
  1147. }
  1148. /// <summary>Raises all events in the queue and drains the queue.</summary>
  1149. internal void Drain () {
  1150. if (drainDisabled) return;
  1151. drainDisabled = true;
  1152. var entries = this.eventQueueEntries;
  1153. AnimationState state = this.state;
  1154. // Don't cache entries.Count so callbacks can queue their own events (eg, call SetAnimation in AnimationState_Complete).
  1155. for (int i = 0; i < entries.Count; i++) {
  1156. var queueEntry = entries[i];
  1157. TrackEntry trackEntry = queueEntry.entry;
  1158. switch (queueEntry.type) {
  1159. case EventType.Start:
  1160. trackEntry.OnStart();
  1161. state.OnStart(trackEntry);
  1162. break;
  1163. case EventType.Interrupt:
  1164. trackEntry.OnInterrupt();
  1165. state.OnInterrupt(trackEntry);
  1166. break;
  1167. case EventType.End:
  1168. trackEntry.OnEnd();
  1169. state.OnEnd(trackEntry);
  1170. goto case EventType.Dispose; // Fall through. (C#)
  1171. case EventType.Dispose:
  1172. trackEntry.OnDispose();
  1173. state.OnDispose(trackEntry);
  1174. trackEntryPool.Free(trackEntry); // Pooling
  1175. break;
  1176. case EventType.Complete:
  1177. trackEntry.OnComplete();
  1178. state.OnComplete(trackEntry);
  1179. break;
  1180. case EventType.Event:
  1181. trackEntry.OnEvent(queueEntry.e);
  1182. state.OnEvent(trackEntry, queueEntry.e);
  1183. break;
  1184. }
  1185. }
  1186. eventQueueEntries.Clear();
  1187. drainDisabled = false;
  1188. }
  1189. internal void Clear () {
  1190. eventQueueEntries.Clear();
  1191. }
  1192. }
  1193. public class Pool<T> where T : class, new() {
  1194. public readonly int max;
  1195. readonly Stack<T> freeObjects;
  1196. public int Count { get { return freeObjects.Count; } }
  1197. public int Peak { get; private set; }
  1198. public Pool (int initialCapacity = 16, int max = int.MaxValue) {
  1199. freeObjects = new Stack<T>(initialCapacity);
  1200. this.max = max;
  1201. }
  1202. public T Obtain () {
  1203. return freeObjects.Count == 0 ? new T() : freeObjects.Pop();
  1204. }
  1205. public void Free (T obj) {
  1206. if (obj == null) throw new ArgumentNullException("obj", "obj cannot be null");
  1207. if (freeObjects.Count < max) {
  1208. freeObjects.Push(obj);
  1209. Peak = Math.Max(Peak, freeObjects.Count);
  1210. }
  1211. Reset(obj);
  1212. }
  1213. // protected void FreeAll (List<T> objects) {
  1214. // if (objects == null) throw new ArgumentNullException("objects", "objects cannot be null.");
  1215. // var freeObjects = this.freeObjects;
  1216. // int max = this.max;
  1217. // for (int i = 0; i < objects.Count; i++) {
  1218. // T obj = objects[i];
  1219. // if (obj == null) continue;
  1220. // if (freeObjects.Count < max) freeObjects.Push(obj);
  1221. // Reset(obj);
  1222. // }
  1223. // Peak = Math.Max(Peak, freeObjects.Count);
  1224. // }
  1225. public void Clear () {
  1226. freeObjects.Clear();
  1227. }
  1228. protected void Reset (T obj) {
  1229. var poolable = obj as IPoolable;
  1230. if (poolable != null) poolable.Reset();
  1231. }
  1232. public interface IPoolable {
  1233. void Reset ();
  1234. }
  1235. }
  1236. }