MotionBuilder.cs
Runtime/Builders/MotionBuilder.cs
1 using System;
2 using MeatMotion.Adapters;
3 using Unity.Collections.LowLevel.Unsafe;
4 using UnityEngine;
5
6 namespace MeatMotion
7 {
8 #if UNITY_6000_7_OR_NEWER
9 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // A pool of cleared buffers.
10 #endif
11 public struct MotionBuilder<TValue, TOptions, TAdapter> : IDisposable
12 where TValue : unmanaged
13 where TOptions : unmanaged, IMotionOptions
14 where TAdapter : unmanaged, IMotionAdapter<TValue, TOptions>
15 {
16 struct Settings
17 {
18 internal FloatMotionBuilder Clock;
19 internal TValue From, To;
20 internal TOptions Options;
21 internal IMotionScheduler Scheduler;
22 }
23
24 sealed class Buffer
25 {
26 internal Settings Settings;
27 internal Buffer Next;
28 internal Func<MotionWorld, MotionTimeKind, MotionHandle> Pending;
29 internal ulong Generation;
30 }
31
32 [ThreadStatic] static Buffer pool;
33 Buffer buffer;
34 readonly ulong generation;
35 Buffer Active => buffer != null && buffer.Generation == generation ? buffer :
36 throw new InvalidOperationException("Motion builder is uninitialized, disposed or already bound.");
37 ref FloatMotionBuilder Clock => ref Active.Settings.Clock;
38 internal TOptions Options => Active.Settings.Options;
39 internal void ImportEase(Ease ease, AnimationCurve curve) => Clock.ImportEase(ease, curve);
40 public MotionSettings<TValue, TOptions> ToMotionSettings()
41 {
42 ref var settings = ref Active.Settings;
43 return settings.Clock.Export(settings.From, settings.To, settings.Options, settings.Scheduler);
44 }
45 static readonly bool NativeFloat = typeof(TAdapter) == typeof(FloatMotionAdapter);
46 #if !UNITY_EDITOR
47 // A scheduler keeps the world of this motion type until that world is disposed.
48 static WorldScheduler resolvedScheduler;
49 static MotionWorld resolvedWorld;
50 #endif
51
52 // A pooled buffer has a zeroed clock and no scheduler.
53 internal MotionBuilder(in TValue start, in TValue end, float duration)
54 {
55 MotionWorld.CheckTime(duration, nameof(duration));
56 var taken = pool ?? new Buffer();
57 pool = taken.Next;
58 taken.Next = null;
59 buffer = taken;
60 generation = taken.Generation;
61 ref var settings = ref taken.Settings;
62 settings.From = start;
63 settings.To = end;
64 settings.Options = default;
65 settings.Clock.Start(duration);
66 }
67
68 internal MotionBuilder(in TValue start, in TValue end, in FloatMotionBuilder clock, IMotionScheduler scheduler)
69 {
70 var taken = pool ?? new Buffer();
71 pool = taken.Next;
72 taken.Next = null;
73 buffer = taken;
74 generation = taken.Generation;
75 ref var settings = ref taken.Settings;
76 settings.From = start;
77 settings.To = end;
78 settings.Options = default;
79 settings.Clock = clock;
80 settings.Scheduler = scheduler;
81 }
82
83 // All struct copies share one configuration and are invalidated together.
84 public void Dispose()
85 {
86 if (buffer != null && buffer.Generation == generation)
87 {
88 buffer.Generation++;
89 Recycle(buffer);
90 }
91 buffer = null;
92 }
93
94 static void Recycle(Buffer buffer)
95 {
96 buffer.Settings.Clock = default;
97 buffer.Settings.Scheduler = null;
98 buffer.Pending = null;
99 buffer.Next = pool;
100 pool = buffer;
101 }
102
103 Settings Take()
104 {
105 var settings = Active.Settings;
106 Dispose();
107 return settings;
108 }
109
110 FloatMotionBuilder TakeFloatClock(MotionWorld world, MotionTimeKind kind)
111 {
112 var settings = Take();
113 settings.Clock.TimeKind = kind;
114 return settings.Clock.WithRange(UnsafeUtility.As<TValue, float>(ref settings.From),
115 UnsafeUtility.As<TValue, float>(ref settings.To)).ResolveScheduler(world, settings.Scheduler);
116 }
117
118 public MotionBuilder<TValue, TOptions, TAdapter> WithScheduler(MotionWorld world)
119 {
120 Active.Settings.Scheduler = world;
121 return this;
122 }
123
124 public MotionBuilder<TValue, TOptions, TAdapter> WithScheduler(IMotionScheduler scheduler)
125 {
126 Active.Settings.Scheduler = scheduler;
127 return this;
128 }
129
130 public MotionBuilder<TValue, TOptions, TAdapter> WithEase(Easing easing)
131 {
132 Clock.WithEase(easing);
133 return this;
134 }
135
136 public MotionBuilder<TValue, TOptions, TAdapter> WithEase(Ease ease)
137 {
138 Clock.WithEase(ease);
139 return this;
140 }
141
142 public MotionBuilder<TValue, TOptions, TAdapter> WithEase(AnimationCurve animationCurve)
143 {
144 Clock.WithEase(animationCurve);
145 return this;
146 }
147
148 public MotionBuilder<TValue, TOptions, TAdapter> WithLoops(int loops, LoopType loopType = LoopType.Restart)
149 {
150 Clock.WithLoops(loops, loopType);
151 return this;
152 }
153
154 public MotionBuilder<TValue, TOptions, TAdapter> WithDelay(float delay, DelayType delayType = DelayType.FirstLoop, bool skipValuesDuringDelay = true)
155 {
156 Clock.WithDelay(delay, delayType, skipValuesDuringDelay);
157 return this;
158 }
159
160 public MotionBuilder<TValue, TOptions, TAdapter> WithImmediateBind(bool immediateBind = true)
161 {
162 Clock.WithImmediateBind(immediateBind);
163 return this;
164 }
165
166 public MotionBuilder<TValue, TOptions, TAdapter> WithOnCancel(Action callback)
167 {
168 Clock.WithOnCancel(callback);
169 return this;
170 }
171
172 public MotionBuilder<TValue, TOptions, TAdapter> WithDebugName(string debugName)
173 {
174 Clock.WithDebugName(debugName);
175 return this;
176 }
177
178 public MotionBuilder<TValue, TOptions, TAdapter> WithOnComplete(Action callback)
179 {
180 Clock.WithOnComplete(callback);
181 return this;
182 }
183
184 public MotionBuilder<TValue, TOptions, TAdapter> WithOnLoopComplete(Action<int> callback)
185 {
186 Clock.WithOnLoopComplete(callback);
187 return this;
188 }
189
190 public MotionBuilder<TValue, TOptions, TAdapter> WithOptions(TOptions options)
191 {
192 Active.Settings.Options = options;
193 return this;
194 }
195
196 public MotionBuilder<TValue, TOptions, TAdapter> WithCancelOnError(bool cancelOnError = true)
197 {
198 Clock.WithCancelOnError(cancelOnError);
199 return this;
200 }
201
202 public MotionHandle Bind(Action<TValue> action)
203 {
204 if (action == null) throw new ArgumentNullException(nameof(action));
205 if (NativeFloat && TryResolve(out var world, out var kind))
206 return TakeFloatClock(world, kind).Bind((Action<float>)(object)action);
207 return Schedule(new Sink0<TValue> { Setter = action }, true);
208 }
209
210 public MotionHandle Bind<T1>(T1 state, Action<TValue, T1> action)
211 where T1 : class
212 {
213 if (action == null) throw new ArgumentNullException(nameof(action));
214 if (NativeFloat && TryResolve(out var world, out var kind))
215 return TakeFloatClock(world, kind).Bind(state, (Action<float, T1>)(object)action);
216 return Schedule(new Sink1<TValue, T1> { State1 = state, Setter = action }, true);
217 }
218
219 internal MotionHandle BindValueState<TState>(TState state, Action<TValue, TState> action) where TState : struct
220 {
221 if (action == null) throw new ArgumentNullException(nameof(action));
222 return Schedule(new Sink1<TValue, TState> { State1 = state, Setter = action }, true);
223 }
224
225 public MotionHandle Bind<T1, T2>(T1 state0, T2 state1, Action<TValue, T1, T2> action)
226 where T1 : class
227 where T2 : class
228 {
229 if (action == null) throw new ArgumentNullException(nameof(action));
230 return Schedule(new Sink2<TValue, T1, T2> { State1 = state0, State2 = state1, Setter = action }, true);
231 }
232
233 public MotionHandle Bind<T1, T2, T3>(T1 state0, T2 state1, T3 state2, Action<TValue, T1, T2, T3> action)
234 where T1 : class
235 where T2 : class
236 where T3 : class
237 {
238 if (action == null) throw new ArgumentNullException(nameof(action));
239 return Schedule(new Sink3<TValue, T1, T2, T3> { State1 = state0, State2 = state1, State3 = state2, Setter = action }, true);
240 }
241
242 public MotionHandle RunWithoutBinding()
243 {
244 if (NativeFloat && TryResolve(out var world, out var kind))
245 return TakeFloatClock(world, kind).RunWithoutBinding();
246 return Schedule(new EmptySink<TValue>(), false);
247 }
248
249 bool TryResolve(out MotionWorld world, out MotionTimeKind kind)
250 {
251 var scheduler = Active.Settings.Scheduler;
252 #if UNITY_EDITOR
253 if (scheduler == null && !Application.isPlaying) scheduler = MotionScheduler.Update;
254 #endif
255 scheduler ??= MotionScheduler.DefaultScheduler;
256 kind = MotionTimeKind.Time;
257 if (scheduler is WorldScheduler clock)
258 {
259 kind = clock.Kind;
260 #if UNITY_EDITOR
261 // Edit Mode and Play Mode resolve to different worlds.
262 world = clock.Resolve(typeof(MotionBuilder<TValue, TOptions, TAdapter>));
263 #else
264 world = resolvedWorld;
265 if (!ReferenceEquals(clock, resolvedScheduler) || world.IsDisposed)
266 {
267 world = clock.Resolve(typeof(MotionBuilder<TValue, TOptions, TAdapter>));
268 resolvedScheduler = world == null ? null : clock;
269 resolvedWorld = world;
270 }
271 #endif
272 }
273 else world = scheduler as MotionWorld;
274 return world != null;
275 }
276
277 internal MotionHandle SchedulePending(MotionWorld world, MotionTimeKind kind)
278 {
279 var active = Active;
280 return active.Pending != null ? active.Pending(world, kind) :
281 ScheduleIn(ref active.Settings, world, kind, new EmptySink<TValue>(), false);
282 }
283
284 MotionHandle Schedule<TSink>(TSink sink, bool bound) where TSink : struct, IValueSink<TValue>
285 {
286 if (TryResolve(out var world, out var kind)) return ScheduleIn(world, kind, sink, bound);
287 return ScheduleCustom(sink, bound);
288 }
289
290 MotionHandle ScheduleCustom<TSink>(TSink sink, bool bound) where TSink : struct, IValueSink<TValue>
291 {
292 var scheduler = Active.Settings.Scheduler ?? MotionScheduler.DefaultScheduler ??
293 throw new InvalidOperationException("No default motion scheduler.");
294 var copy = this;
295 Active.Pending = (world, kind) => copy.ScheduleIn(world, kind, sink, bound);
296 try { return scheduler.Schedule(ref this); }
297 finally { copy.Dispose(); }
298 }
299
300 MotionHandle ScheduleIn<TSink>(MotionWorld world, MotionTimeKind kind, TSink sink, bool bound) where TSink : struct, IValueSink<TValue>
301 {
302 // The settings leave the builder before any callback runs and are read in place.
303 var taken = Active;
304 taken.Generation++;
305 buffer = null;
306 var handle = ScheduleIn(ref taken.Settings, world, kind, sink, bound);
307 Recycle(taken);
308 return handle;
309 }
310
311 static MotionHandle ScheduleIn<TSink>(ref Settings settings, MotionWorld world, MotionTimeKind kind, TSink sink, bool bound)
312 where TSink : struct, IValueSink<TValue>
313 {
314 ref var clock = ref settings.Clock;
315 clock.TimeKind = kind;
316 if (world.IsDisposed) throw new ObjectDisposedException(nameof(MotionWorld));
317 var snapshot = clock.SnapshotCurve();
318 if (clock.Immediate && bound)
319 {
320 // Adapters may change the endpoints they are given.
321 TValue start = settings.From, end = settings.To;
322 TOptions parameters = settings.Options;
323 var context = new MotionEvaluationContext { Progress = snapshot == null ? 0f : snapshot.ImmediateProgress };
324 sink.Write(default(TAdapter).Evaluate(ref start, ref end, ref parameters, in context));
325 settings.From = start;
326 settings.To = end;
327 settings.Options = parameters;
328 }
329 var node = clock.CreateNode(world, snapshot);
330 var track = node.CachedTrack as ValueTrack<TValue, TOptions, TAdapter, TSink>;
331 if (track == null)
332 node.CachedTrack = track = new ValueTrack<TValue, TOptions, TAdapter, TSink>();
333 track.Node = node;
334 track.From = settings.From;
335 track.To = settings.To;
336 track.Options = settings.Options;
337 track.Sink = sink;
338 ref var data = ref node.Data;
339 data.State = track;
340 data.Setter = ValueTrack<TValue, TOptions, TAdapter, TSink>.Write;
341 // Stateful custom adapters must also evaluate during skipped delay intervals.
342 if (!data.Timed || ValueTrack<TValue, TOptions, TAdapter, TSink>.Pure)
343 data.Advance = ValueTrack<TValue, TOptions, TAdapter, TSink>.Paged ? MotionAdvance.Page : MotionAdvance.Float;
344 return MotionDebugger.Scheduled(node, settings.Scheduler);
345 }
346 }
347 }