FloatMotionBuilder.cs
Runtime/Builders/FloatMotionBuilder.cs
1 using System;
2 using MeatMotion.Collections;
3 using MeatMotion.Adapters;
4 using UnityEngine;
5
6 namespace MeatMotion
7 {
8 #if UNITY_6000_7_OR_NEWER
9 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // Immutable.
10 #endif
11 public struct FloatMotionBuilder
12 {
13 float from, to;
14 float duration => timing.Length;
15 Easing ease;
16 AnimationCurve curve;
17 MotionTiming timing;
18 bool immediate, cancelOnError;
19 Action complete, cancel;
20 MotionWorld scheduler;
21 IMotionScheduler requestedScheduler;
22 string debugName;
23 internal MotionTimeKind TimeKind;
24
25 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
26 internal FloatMotionBuilder(float from, float to, float duration) : this()
27 {
28 MotionWorld.CheckTime(duration, nameof(duration));
29 this.from = from;
30 this.to = to;
31 timing.Length = duration;
32 timing.Loops = 1;
33 immediate = true;
34 }
35
36 // Initializes a builder whose fields are all zero.
37 internal void Start(float duration)
38 {
39 to = 1f;
40 timing.Length = duration;
41 timing.Loops = 1;
42 immediate = true;
43 }
44
45 public FloatMotionBuilder WithScheduler(MotionWorld world)
46 {
47 return ResolveScheduler(world ?? throw new ArgumentNullException(nameof(world)), world);
48 }
49
50 public FloatMotionBuilder WithScheduler(IMotionScheduler scheduler)
51 => ResolveScheduler(scheduler as MotionWorld, scheduler);
52
53 public MotionSettings<float, NoOptions> ToMotionSettings()
54 => Export(from, to, default(NoOptions), requestedScheduler);
55
56 public MotionBuilder<float, NoOptions, FloatMotionAdapter> AsMotionBuilder()
57 => new MotionBuilder<float, NoOptions, FloatMotionAdapter>(from, to, WithRange(0f, 1f), requestedScheduler);
58
59 internal FloatMotionBuilder ResolveScheduler(MotionWorld world, IMotionScheduler requested)
60 {
61 scheduler = world;
62 requestedScheduler = requested;
63 return this;
64 }
65
66 public FloatMotionBuilder WithEase(Easing easing)
67 {
68 EaseUtility.CheckBuiltin(easing);
69 ease = easing;
70 return this;
71 }
72
73 public FloatMotionBuilder WithEase(Ease ease)
74 {
75 if (ease == Ease.CustomAnimationCurve) throw new ArgumentException("Specify the AnimationCurve instance.", nameof(ease));
76 return WithEase(EaseUtility.Builtin(ease));
77 }
78
79 public FloatMotionBuilder WithEase(AnimationCurve animationCurve)
80 {
81 curve = animationCurve ?? throw new ArgumentNullException(nameof(animationCurve));
82 ease = Easing.CustomAnimationCurve;
83 return this;
84 }
85
86 public FloatMotionBuilder WithImmediateBind(bool enabled = true) { immediate = enabled; return this; }
87 public FloatMotionBuilder WithCancelOnError(bool enabled = true) { cancelOnError = enabled; return this; }
88 public FloatMotionBuilder WithDelay(float delay, DelayType delayType = DelayType.FirstLoop, bool skipValuesDuringDelay = true)
89 {
90 MotionWorld.CheckTime(delay, nameof(delay));
91 timing.Delay = delay;
92 timing.DelayType = delayType;
93 timing.SkipDelay = skipValuesDuringDelay;
94 return this;
95 }
96 public FloatMotionBuilder WithLoops(int loops, LoopType loopType = LoopType.Restart)
97 {
98 timing.Loops = loops;
99 timing.LoopType = loopType;
100 return this;
101 }
102 public FloatMotionBuilder WithOnLoopComplete(Action<int> callback) { timing.OnLoop += callback; return this; }
103 public FloatMotionBuilder WithOnComplete(Action action) { complete += action; return this; }
104 public FloatMotionBuilder WithDebugName(string debugName) { this.debugName = debugName; return this; }
105 public FloatMotionBuilder WithOnCancel(Action action) { cancel += action; return this; }
106
107 public MotionHandle RunWithoutBinding()
108 {
109 if (!TryResolveWorld(out var world, out var kind)) return AsMotionBuilder().RunWithoutBinding();
110 var node = CreateNode(world, null, kind);
111 ref var data = ref node.Data;
112 data.ClockOnly = true;
113 if (!data.Timed) data.Advance = MotionAdvance.Clock;
114 return MotionDebugger.Scheduled(node, requestedScheduler);
115 }
116
117 public MotionHandle Bind(Action<float> setter)
118 {
119 if (setter == null) throw new ArgumentNullException(nameof(setter));
120 if (!TryResolveWorld(out var world, out var kind)) return AsMotionBuilder().Bind(setter);
121 var snapshot = SnapshotCurve();
122 if (immediate) setter(snapshot == null ? from : Mathf.LerpUnclamped(from, to, snapshot.ImmediateProgress));
123 return Register(world, kind, snapshot, setter, CallClosure);
124 }
125
126 public MotionHandle Bind<T>(T state, Action<float, T> setter) where T : class
127 {
128 if (setter == null) throw new ArgumentNullException(nameof(setter));
129 if (!TryResolveWorld(out var world, out var kind)) return AsMotionBuilder().Bind(state, setter);
130 var snapshot = SnapshotCurve();
131 if (immediate) setter(snapshot == null ? from : Mathf.LerpUnclamped(from, to, snapshot.ImmediateProgress), state);
132 return Register(world, kind, snapshot, state, setter);
133 }
134
135 public MotionHandle Bind<T1, T2>(T1 state0, T2 state1, Action<float, T1, T2> setter)
136 where T1 : class where T2 : class
137 => AsMotionBuilder().Bind(state0, state1, setter);
138
139 public MotionHandle Bind<T1, T2, T3>(T1 state0, T2 state1, T3 state2, Action<float, T1, T2, T3> setter)
140 where T1 : class where T2 : class where T3 : class
141 => AsMotionBuilder().Bind(state0, state1, state2, setter);
142
143 internal static readonly Type FloatStorage = typeof(MotionBuilder<float, NoOptions, FloatMotionAdapter>);
144
145 bool TryResolveWorld(out MotionWorld world, out MotionTimeKind kind)
146 {
147 kind = TimeKind;
148 world = scheduler;
149 if (world == null)
150 {
151 var requested = requestedScheduler;
152 #if UNITY_EDITOR
153 if (requested == null && !Application.isPlaying) requested = MotionScheduler.Update;
154 #endif
155 requested ??= MotionScheduler.DefaultScheduler;
156 if (requested is WorldScheduler clock)
157 {
158 world = clock.ResolveFloat();
159 kind = clock.Kind;
160 }
161 else if (requested is MotionWorld direct) world = direct;
162 else return false;
163 }
164 if (world.IsDisposed) throw new ObjectDisposedException(nameof(MotionWorld));
165 return true;
166 }
167
168 // A stateless setter becomes the target of one shared trampoline, so it follows
169 // the same paged path as bindings with a target.
170 static readonly Action<float, Action<float>> CallClosure = (value, closure) => closure(value);
171
172 internal CurveSnapshot SnapshotCurve()
173 {
174 if (ease != Easing.CustomAnimationCurve || curve == null) return null;
175 return CurveSnapshot.Capture(curve);
176 }
177
178 internal bool Immediate => immediate;
179 internal void ImportEase(Ease value, AnimationCurve source)
180 {
181 ease = value == Ease.CustomAnimationCurve ? Easing.CustomAnimationCurve : EaseUtility.Builtin(value);
182 curve = source;
183 }
184
185 internal MotionSettings<TValue, TOptions> Export<TValue, TOptions>(TValue start, TValue end, TOptions options, IMotionScheduler clock)
186 where TValue : unmanaged where TOptions : unmanaged, IMotionOptions
187 {
188 var configured = Ease.Linear;
189 while (configured < Ease.CustomAnimationCurve && EaseUtility.Builtin(configured) != ease) configured++;
190 return new MotionSettings<TValue, TOptions>
191 {
192 StartValue = start, EndValue = end, Duration = duration, Options = options,
193 Ease = configured, CustomEaseCurve = curve, Delay = timing.Delay, DelayType = timing.DelayType,
194 Loops = timing.Loops, LoopType = timing.LoopType, CancelOnError = cancelOnError,
195 SkipValuesDuringDelay = timing.SkipDelay, ImmediateBind = immediate, Scheduler = clock
196 };
197 }
198 internal FloatMotionBuilder WithRange(float start, float end)
199 {
200 var copy = this;
201 copy.from = start;
202 copy.to = end;
203 return copy;
204 }
205 internal MotionNode CreateNode(MotionWorld world, CurveSnapshot snapshot)
206 => CreateNode(world, snapshot, TimeKind);
207
208 MotionNode CreateNode(MotionWorld world, CurveSnapshot snapshot, MotionTimeKind kind)
209 {
210 bool timed = timing.NeedsTimeline || duration == 0;
211 var node = world.Rent(timed ? timing.Total : duration);
212 if (timed) node.Timing = timing;
213 ref var data = ref node.Data;
214 data.TimeKind = kind;
215 data.Timed = timed;
216 data.CancelOnError = cancelOnError;
217 data.From = from;
218 data.To = to;
219 data.Ease = ease;
220 if (snapshot != null) data.Curve = snapshot;
221 // New and reclaimed slots have no callbacks or debugger name.
222 if (debugName != null) node.DebugName = debugName;
223 if (complete != null) node.OnComplete = complete;
224 if (cancel != null) node.OnCancel = cancel;
225 return node;
226 }
227
228 MotionHandle Register(MotionWorld world, MotionTimeKind kind, CurveSnapshot snapshot, object state, Delegate setter)
229 {
230 var node = CreateNode(world, snapshot, kind);
231 ref var data = ref node.Data;
232 data.State = state;
233 data.Setter = setter;
234 data.Advance = MotionAdvance.Float;
235 return MotionDebugger.Scheduled(node, requestedScheduler);
236 }
237 }
238 }