MotionWorld.cs
Runtime/Core/MotionWorld.cs
1 using System;
2 using System.Collections.Generic;
3 using Unity.Collections.LowLevel.Unsafe;
4 using UnityEngine;
5
6 namespace MeatMotion
7 {
8 /// <summary>Main-thread float and sequence scheduler. Explicit worlds advance only when Tick is called.</summary>
9 #if UNITY_6000_7_OR_NEWER
10 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // The worlds that hold motions. MotionUpdateDriver.EndSession resets them.
11 #endif
12 public sealed class MotionWorld : IDisposable, IMotionScheduler
13 {
14 // A motion lives in a slot: a node, its MotionData and its time. Ended slots are reused.
15 // FloatPages and ValuePages read the internal arrays of this class directly.
16 internal MotionNode[] Slots = Array.Empty<MotionNode>();
17 internal MotionData[] Data = Array.Empty<MotionData>();
18 internal double[] Times = Array.Empty<double>();
19 int slotCount, liveSlots;
20 int[] freeSlots = Array.Empty<int>();
21 int freeCount;
22 int retiredSlot = -1;
23
24 // The slots that Tick advances, in the order they were scheduled. A removed root leaves -1.
25 // Root order is observable when bindings mutate other motions during a tick.
26 internal int[] Roots = Array.Empty<int>();
27 internal int RootCount;
28 // Position of each slot in Roots, or -1. Kept beside the nodes so that moving roots stays in one array.
29 int[] rootOf = Array.Empty<int>();
30 int holes, firstHole = int.MaxValue;
31 // Live roots per page, and how many pages hold only ended roots.
32 int[] pageLive = Array.Empty<int>();
33 int emptyPages;
34
35 // What the page runners have learned about each run of MotionPage.Size roots.
36 internal MotionPage[] Pages = Array.Empty<MotionPage>();
37 // Any mutation interrupts a setter loop. Only the affected page loses its cached bindings.
38 internal long Revision;
39 // Scratch buffers for one page, allocated when a page first needs them.
40 float[] floatSamples;
41 double[] clockSamples;
42 int[] loopSamples;
43 Dictionary<Type, Array> valueSamples;
44
45 // A handle finds its world by StorageId. Only worlds that hold a motion are registered.
46 static readonly Dictionary<int, MotionWorld> liveWorlds = new();
47 static int lastStorageId;
48 static MotionWorld lastResolved;
49 internal readonly int StorageId = checked(++lastStorageId);
50
51 bool updating, disposed;
52 internal bool IsDisposed => disposed;
53 internal object AutomaticPhase;
54 // The public default world also controls typed motions scheduled for its phase.
55 internal MotionWorld[] ScheduledWorlds;
56
57 internal static MotionNode Resolve(MotionHandle handle)
58 {
59 var world = lastResolved;
60 if (world == null || world.StorageId != handle.StorageId)
61 {
62 if (!liveWorlds.TryGetValue(handle.StorageId, out world)) return null;
63 lastResolved = world;
64 }
65 if ((uint)handle.Index >= (uint)world.slotCount) return null;
66 var node = world.Slots[handle.Index];
67 return node.Valid && node.Version == handle.Version ? node : null;
68 }
69
70 // Ends every motion of every world without callbacks.
71 internal static void ResetAll()
72 {
73 if (liveWorlds.Count == 0) return;
74 // A world leaves the registry when its last motion ends.
75 var worlds = new MotionWorld[liveWorlds.Count];
76 liveWorlds.Values.CopyTo(worlds, 0);
77 foreach (var world in worlds) world.ResetWithoutCallbacks();
78 }
79
80 internal ref int RootOf(int slot) => ref rootOf[slot];
81 internal ref MotionData GetData(int slot) => ref Data[slot];
82 internal ref double GetTime(int slot) => ref Times[slot];
83 internal float[] FloatSamples => floatSamples ??= new float[MotionPage.Size];
84 internal double[] ClockSamples => clockSamples ??= new double[MotionPage.Size];
85 internal int[] LoopSamples => loopSamples ??= new int[MotionPage.Size];
86
87 internal TValue[] GetValueSamples<TValue>()
88 {
89 valueSamples ??= new Dictionary<Type, Array>();
90 if (!valueSamples.TryGetValue(typeof(TValue), out var buffer))
91 valueSamples[typeof(TValue)] = buffer = new TValue[MotionPage.Size];
92 return (TValue[])buffer;
93 }
94
95 internal void InvalidatePage(int rootIndex)
96 {
97 Revision++;
98 int page = rootIndex / MotionPage.Size;
99 if (rootIndex >= 0 && page < Pages.Length && Pages[page].Checked) Pages[page].Reset();
100 }
101
102 bool ShouldCompact => holes > 0 && (holes == RootCount || holes >= Math.Max(MotionPage.Size, RootCount / 8));
103
104 public static MotionWorld Default => MotionUpdateDriver.World;
105
106 public MotionWorld(int capacity = 0) => EnsureCapacity(capacity);
107
108 public MotionHandle Schedule<TValue, TOptions, TAdapter>(ref MotionBuilder<TValue, TOptions, TAdapter> builder)
109 where TValue : unmanaged
110 where TOptions : unmanaged, IMotionOptions
111 where TAdapter : unmanaged, IMotionAdapter<TValue, TOptions>
112 => builder.SchedulePending(this, MotionTimeKind.Time);
113
114 public void EnsureCapacity(int capacity)
115 {
116 if (disposed) throw new ObjectDisposedException(nameof(MotionWorld));
117 if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
118 if (Data.Length < capacity || Roots.Length < capacity) Revision++;
119 if (Roots.Length < capacity) ResizeRoots(capacity);
120 if (Data.Length < capacity) ResizeSlots(capacity);
121 while (slotCount < capacity) ReturnToPool(NewNode());
122 }
123
124 MotionNode NewNode()
125 {
126 if (slotCount == Data.Length)
127 ResizeSlots(Math.Max(16, checked(Data.Length * 2)));
128 var node = new MotionNode(this, slotCount);
129 rootOf[slotCount] = -1;
130 Slots[slotCount++] = node;
131 return node;
132 }
133
134 void ResizeSlots(int capacity)
135 {
136 Array.Resize(ref Data, capacity);
137 Array.Resize(ref Times, capacity);
138 Array.Resize(ref freeSlots, capacity);
139 Array.Resize(ref Slots, capacity);
140 Array.Resize(ref rootOf, capacity);
141 }
142
143 void ResizeRoots(int capacity)
144 {
145 Array.Resize(ref Roots, capacity);
146 Array.Resize(ref pageLive, (capacity + MotionPage.Size - 1) / MotionPage.Size);
147 }
148
149 internal MotionNode Rent(double duration)
150 {
151 if (disposed) throw new ObjectDisposedException(nameof(MotionWorld));
152 if (RootCount == Roots.Length)
153 {
154 if (ShouldCompact && !updating) Compact();
155 if (RootCount == Roots.Length) ResizeRoots(Math.Max(16, checked(RootCount * 2)));
156 }
157 var node = freeCount == 0 ? NewNode() : Slots[freeSlots[--freeCount]];
158 InvalidatePage(RootCount);
159 if (liveSlots++ == 0) liveWorlds.Add(StorageId, this);
160 node.Version = checked(node.Version + 1);
161 node.Valid = true;
162 node.Owned = node.Ended = node.Preserved = false;
163 node.Speed = 1f;
164 node.CompletedLoops = 0;
165 node.Active = true;
166 Data[node.Slot].Duration = duration;
167 Times[node.Slot] = 0;
168 // A page of ended roots becomes live again when the last page is appended to.
169 if (pageLive[RootCount / MotionPage.Size]++ == 0 && RootCount % MotionPage.Size != 0) emptyPages--;
170 rootOf[node.Slot] = RootCount;
171 Roots[RootCount++] = node.Slot;
172 return node;
173 }
174
175 internal void Retire(MotionNode node)
176 {
177 if (disposed || !node.Valid) { Free(node); return; }
178 node.NextRetiredSlot = retiredSlot;
179 retiredSlot = node.Slot;
180 }
181
182 void ReturnToPool(MotionNode node)
183 {
184 freeSlots[freeCount++] = node.Slot;
185 }
186
187 internal void Free(MotionNode node)
188 {
189 node.Valid = false;
190 node.DebugName = null;
191 if (--liveSlots == 0)
192 {
193 liveWorlds.Remove(StorageId);
194 if (lastResolved == this) lastResolved = null;
195 }
196 if (!disposed)
197 {
198 // The node cleared its bindings when it ended.
199 Data[node.Slot].Reclaim();
200 ReturnToPool(node);
201 }
202 }
203
204 void ReclaimRetired()
205 {
206 while (retiredSlot >= 0)
207 {
208 var node = Slots[retiredSlot];
209 retiredSlot = node.NextRetiredSlot;
210 Free(node);
211 }
212 }
213
214 internal void DetachRoot(MotionNode node)
215 {
216 int index = rootOf[node.Slot];
217 if (index < 0) return;
218 int page = index / MotionPage.Size;
219 if (--pageLive[page] == 0) emptyPages++;
220 Revision++;
221 firstHole = Math.Min(firstHole, index);
222 Roots[index] = -1;
223 if (page < Pages.Length)
224 {
225 ref var block = ref Pages[page];
226 if (block.AcceptsHoles && index < block.End)
227 {
228 block.Channels.ClearTarget(index % MotionPage.Size);
229 block.Sparse = true;
230 while (block.Head < block.End && Roots[block.Head] < 0) block.Head++;
231 if (block.Head == block.End) block.Reset();
232 }
233 else block.Reset();
234 }
235 rootOf[node.Slot] = -1;
236 holes++;
237 }
238
239 void Compact()
240 {
241 int write = firstHole;
242 int lastPage = (RootCount - 1) / MotionPage.Size;
243 for (int read = firstHole; read < RootCount; read++)
244 {
245 int slot = Roots[read];
246 if (slot < 0) continue;
247 rootOf[slot] = write;
248 Roots[write++] = slot;
249 }
250 RootCount = write;
251 for (int page = firstHole / MotionPage.Size; page <= lastPage; page++)
252 {
253 if (page < Pages.Length) Pages[page].Reset();
254 pageLive[page] = Math.Max(0, Math.Min(MotionPage.Size, RootCount - page * MotionPage.Size));
255 }
256 firstHole = int.MaxValue;
257 holes = 0;
258 emptyPages = 0;
259 }
260
261 // Removes the pages whose roots have all ended. Later pages move down whole, keeping
262 // their order, their holes and their cached bindings.
263 void DropEmptyPages()
264 {
265 int pages = (RootCount + MotionPage.Size - 1) / MotionPage.Size;
266 int write = 0, kept = 0;
267 Revision++;
268 for (int page = 0; page < pages; page++)
269 {
270 int from = page * MotionPage.Size;
271 int length = Math.Min(RootCount, from + MotionPage.Size) - from;
272 if (pageLive[page] == 0)
273 {
274 holes -= length;
275 if (page < Pages.Length) Pages[page].Reset();
276 continue;
277 }
278 kept = write * MotionPage.Size + length;
279 if (write != page)
280 {
281 int to = write * MotionPage.Size;
282 Array.Copy(Roots, from, Roots, to, length);
283 for (int i = to; i < to + length; i++)
284 {
285 int slot = Roots[i];
286 if (slot >= 0) rootOf[slot] = i;
287 }
288 pageLive[write] = pageLive[page];
289 pageLive[page] = 0;
290 if (page < Pages.Length)
291 {
292 // The vacated page takes over the storage of the page it replaces.
293 var moved = Pages[page];
294 var spare = Pages[write].Channels;
295 moved.Head += to - from;
296 moved.End += to - from;
297 Pages[write] = moved;
298 Pages[page] = new MotionPage { Channels = spare };
299 }
300 else if (write < Pages.Length) Pages[write].Reset();
301 }
302 write++;
303 }
304 RootCount = kept;
305 emptyPages = 0;
306 firstHole = int.MaxValue;
307 if (holes > 0)
308 for (int i = 0; i < RootCount; i++)
309 if (Roots[i] < 0) { firstHole = i; break; }
310 }
311
312 internal static void CheckTime(double value, string name)
313 {
314 if (!(value >= 0 && value <= double.MaxValue)) throw new ArgumentOutOfRangeException(name);
315 }
316
317 // Reference path for one binding at a time. It stops at the first root that needs Tick:
318 // another kind of motion, special playback, or a binding that reaches its end.
319 internal static void AdvanceIndividually(MotionWorld world, ref int index, int boundary, double dt)
320 {
321 var order = world.Roots;
322 var all = world.Data;
323 var stamps = world.Times;
324 long version = world.Revision;
325 var kind = all[order[index]].TimeKind;
326 do
327 {
328 int slot = order[index];
329 if (slot < 0) return;
330 ref var item = ref all[slot];
331 if (item.Advance < MotionAdvance.Float || item.Advance == MotionAdvance.Clock || item.SpecialPlayback || item.TimeKind != kind) return;
332 double time = stamps[slot] + dt;
333 if (time >= item.Duration || time < 0) return;
334 if (item.Timed) world.Slots[slot].Seek(time, ticking: true);
335 else
336 {
337 stamps[slot] = time;
338 item.Started = true;
339 float t = item.EaseAt((float)(time / item.Duration));
340 float value = t == 1f ? item.To : item.From + (item.To - item.From) * t;
341 UnsafeUtility.As<Delegate, Action<float, object>>(ref item.Setter)(value, item.State);
342 }
343 index++;
344 // User code may have replaced the arrays captured above.
345 } while (index < boundary && world.Revision == version);
346 }
347
348 // Unbound motions only keep time. No user code runs, so the arrays cannot change.
349 static void AdvanceClocks(MotionWorld world, ref int index, int count, double dt)
350 {
351 var order = world.Roots;
352 var all = world.Data;
353 var stamps = world.Times;
354 var kind = all[order[index]].TimeKind;
355 int i = index;
356 do
357 {
358 int slot = order[i];
359 if (slot >= 0)
360 {
361 ref var item = ref all[slot];
362 if (item.Advance != MotionAdvance.Clock || item.SpecialPlayback || item.TimeKind != kind) break;
363 double time = stamps[slot] + dt;
364 if (!(time >= 0 && time < item.Duration)) break;
365 stamps[slot] = time;
366 item.Started = true;
367 }
368 i++;
369 } while (i < count);
370 index = i;
371 }
372
373 internal bool IsPageHead(int index)
374 {
375 int offset = index % MotionPage.Size;
376 if (offset == 0) return true;
377 int page = index / MotionPage.Size;
378 if (page < Pages.Length && Pages[page].Compatible) return Pages[page].Head == index;
379 int origin = index - offset;
380 if (Roots[origin] >= 0 || Roots[index - 1] >= 0) return false;
381 for (int i = origin + 1; i < index - 1; i++)
382 if (Roots[i] >= 0) return false;
383 return true;
384 }
385
386 public void Tick(double deltaTime)
387 {
388 CheckTime(deltaTime, nameof(deltaTime));
389 // A setter can dispose a typed world and schedule a replacement during this call.
390 var scheduled = ScheduledWorlds;
391 TickClocks(deltaTime, deltaTime, deltaTime);
392 if (scheduled != null)
393 foreach (var world in scheduled)
394 if (!world.IsDisposed) world.Tick(deltaTime);
395 }
396
397 internal void TickClocks(double scaled, double unscaled, double realtime)
398 {
399 if (disposed) throw new ObjectDisposedException(nameof(MotionWorld));
400 if (updating) throw new InvalidOperationException("Recursive Tick.");
401 ReclaimRetired();
402 updating = true;
403 try
404 {
405 int count = RootCount;
406 for (int i = 0; i < count && !disposed;)
407 {
408 int slot = Roots[i];
409 if (slot < 0) { i++; continue; }
410 ref var current = ref Data[slot];
411 try
412 {
413 double dt = current.TimeKind == MotionTimeKind.Time ? scaled :
414 current.TimeKind == MotionTimeKind.UnscaledTime ? unscaled : realtime;
415 double time = Times[slot] + (current.SpecialPlayback ? dt * Slots[slot].Speed : dt);
416 if (!current.SpecialPlayback && (current.Setter != null || current.ClockOnly) && time >= 0 && time < current.Duration &&
417 (current.Advance != MotionAdvance.None || !current.Timed))
418 {
419 switch (current.Advance)
420 {
421 case MotionAdvance.Float: FloatPages.Advance(this, ref i, count, dt); continue;
422 case MotionAdvance.Clock: AdvanceClocks(this, ref i, count, dt); continue;
423 case MotionAdvance.Page: ((ValueTrack)current.State).Advance(this, ref i, count, dt); continue;
424 }
425 Times[slot] = time;
426 current.Started = true;
427 if (!current.ClockOnly) current.Apply((float)(time / current.Duration));
428 }
429 else Slots[slot].Seek(time, ticking: true);
430 }
431 catch (Exception ex)
432 {
433 MotionDispatcher.Report(ex);
434 if (!disposed && Roots[i] >= 0 && Data[Roots[i]].CancelOnError) Slots[Roots[i]].Release(false);
435 }
436 i++;
437 }
438 if (ShouldCompact)
439 {
440 // Motions that started together tend to end together and vacate whole pages.
441 if (emptyPages > 0 && (long)emptyPages * MotionPage.Size * 2 >= holes) DropEmptyPages();
442 if (ShouldCompact) Compact();
443 }
444 }
445 finally { updating = false; }
446 }
447
448 public void Dispose()
449 {
450 if (disposed) return;
451 Revision++;
452 disposed = true;
453 ReclaimRetired();
454 if (ScheduledWorlds != null)
455 foreach (var world in ScheduledWorlds) world.Dispose();
456 for (int i = 0; i < slotCount; i++)
457 if (Slots[i].Active && !Slots[i].Owned) Slots[i].Release(false);
458 // Includes children of sequence builders which have never been run.
459 for (int i = 0; i < slotCount; i++)
460 if (Slots[i].Active) Slots[i].Release(false);
461 RootCount = 0;
462 Roots = Array.Empty<int>();
463 Data = Array.Empty<MotionData>();
464 Times = Array.Empty<double>();
465 Pages = Array.Empty<MotionPage>();
466 valueSamples = null;
467 Slots = Array.Empty<MotionNode>();
468 slotCount = 0;
469 freeSlots = Array.Empty<int>();
470 freeCount = 0;
471 }
472
473 public void CancelAll()
474 {
475 // Callbacks may create new motions and reuse slots during cancellation.
476 var snapshot = new List<MotionHandle>(RootCount);
477 CollectRoots(snapshot);
478 if (ScheduledWorlds != null)
479 foreach (var world in ScheduledWorlds) world.CollectRoots(snapshot);
480 foreach (var handle in snapshot)
481 if (handle.IsActive() && !handle.Node.Owned) handle.Cancel();
482 if (!updating && holes > 0) Compact();
483 }
484
485 void CollectRoots(List<MotionHandle> snapshot)
486 {
487 for (int i = 0; i < RootCount; i++)
488 if (Roots[i] >= 0) snapshot.Add(new MotionHandle(Slots[Roots[i]]));
489 }
490
491 internal void ResetWithoutCallbacks()
492 {
493 ReclaimRetired();
494 for (int i = 0; i < slotCount; i++)
495 {
496 var node = Slots[i];
497 if (node.Active) node.Abandon();
498 else node.Valid = false; // A terminal callback can reset this world before Retire.
499 }
500 if (!updating && holes > 0) Compact();
501 }
502 }
503 }