MotionTiming.cs
Runtime/Core/MotionTiming.cs
1 using System;
2
3 namespace MeatMotion
4 {
5 public enum DelayType : byte { FirstLoop, EveryLoop }
6 public enum LoopType : byte { Restart, Flip, Incremental, Yoyo }
7
8 internal interface IMotionEase
9 {
10 float EaseAt(float t);
11 }
12
13 internal struct MotionTiming
14 {
15 internal float Length, Delay;
16 internal int Loops;
17 internal DelayType DelayType;
18 internal LoopType LoopType;
19 internal bool SkipDelay;
20 internal Action<int> OnLoop;
21
22 internal bool NeedsTimeline => Delay != 0 || SkipDelay || Loops != 1 || LoopType != LoopType.Restart || OnLoop != null;
23 internal bool SameClock(in MotionTiming other) =>
24 Length == other.Length && Delay == other.Delay && Loops == other.Loops &&
25 LoopType == other.LoopType && DelayType == other.DelayType && SkipDelay == other.SkipDelay;
26 internal double Total => Loops < 0 ? double.PositiveInfinity :
27 Length * Loops + Delay * (DelayType == DelayType.FirstLoop ? 1 : Loops);
28
29 internal float Sample(double time, bool force, ref MotionData data, out int completed, out bool delayed, out bool ended)
30 => TimelineMath.Sample(time, force, Length, Delay, Loops, DelayType, LoopType, ref data, out completed, out delayed, out ended);
31 }
32
33 // Shared by the scheduler and the Burst kernels, so both produce the same samples.
34 internal static class TimelineMath
35 {
36 internal static float Sample<T>(double time, bool force, float length, float delay, int loops,
37 DelayType delayType, LoopType loopType, ref T data, out int completed, out bool delayed, out bool ended)
38 where T : struct, IMotionEase
39 {
40 double period = delayType == DelayType.EveryLoop ? (double)(length + delay) : length;
41 double elapsed = delayType == DelayType.EveryLoop ? Math.Max(0, time) : time - delay;
42 double cycle = period > 0 ? Math.Max(0, Math.Floor(elapsed / period)) : 0;
43 ended = force || (loops >= 0 && (period > 0 ? cycle >= loops : elapsed > 0));
44 completed = ended ? loops : (int)Math.Min(int.MaxValue, cycle);
45 double local = elapsed - cycle * period - (delayType == DelayType.EveryLoop ? delay : 0);
46 delayed = !ended && (time < 0 || local < 0 || (length == 0 && delayType == DelayType.EveryLoop && delay > 0));
47 if (force)
48 {
49 float end = loopType == LoopType.Incremental ? loops :
50 (loopType == LoopType.Flip || loopType == LoopType.Yoyo) ? loops % 2 : 1;
51 return data.EaseAt(end);
52 }
53
54 float t = ended ? 1 : length > 0 ? (float)Math.Max(0, Math.Min(1, local / length)) : 0;
55 bool reverse = ((completed + (int)t) & 1) != 0;
56 switch (loopType)
57 {
58 case LoopType.Flip: return reverse ? 1f - data.EaseAt(t) : data.EaseAt(t);
59 case LoopType.Yoyo: return data.EaseAt(reverse ? 1f - t : t);
60 case LoopType.Incremental: return completed * data.EaseAt(1f) + data.EaseAt(t == 1f ? 0f : t);
61 default: return data.EaseAt(t);
62 }
63 }
64 }
65 }