AnimationState.cs 65 KB

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