API reference · 日本語API索引

MotionHandleExtensions.cs

Runtime/Lifecycle/MotionHandleExtensions.cs

1 // Unity 6.7 reports DEVELOPMENT_BUILD even in a branch it does not compile. Earlier versions
2 // have no other symbol for a development build, so only this guard is exempt.
3 #pragma warning disable UAC0009
4 #if UNITY_7000_0_OR_NEWER
5 #if UNITY_ENABLE_CHECKS || UNITY_EDITOR
6 #define MEATMOTION_DEBUG_NAMES
7 #endif
8 #elif DEVELOPMENT_BUILD || UNITY_EDITOR
9 #define MEATMOTION_DEBUG_NAMES
10 #endif
11 #pragma warning restore UAC0009
12 using System;
13 using System.Collections;
14 using System.Collections.Generic;
15 using System.Threading;
16 using System.Threading.Tasks;
17 using UnityEngine;
18 
19 namespace MeatMotion
20 {
21     public enum LinkBehavior { CancelOnDestroy, CancelOnDisable, CompleteOnDisable }
22     public enum DisposeBehavior { Cancel, Complete }
23     public enum CancelBehavior : byte { None, Cancel, Complete }
24 
25     public sealed class CompositeMotionHandle : ICollection<MotionHandle>
26     {
27         readonly List<MotionHandle> handles;
28         public CompositeMotionHandle() : this(0) { }
29         public CompositeMotionHandle(int capacity) => handles = new List<MotionHandle>(capacity);
30         public int Count => handles.Count;
31         public bool IsReadOnly => false;
32         public void Add(MotionHandle handle) => handles.Add(handle);
33         public void Clear() => handles.Clear();
34         public bool Contains(MotionHandle item) => handles.Contains(item);
35         public void CopyTo(MotionHandle[] array, int arrayIndex) => handles.CopyTo(array, arrayIndex);
36         public bool Remove(MotionHandle item) => handles.Remove(item);
37         public List<MotionHandle>.Enumerator GetEnumerator() => handles.GetEnumerator();
38         IEnumerator<MotionHandle> IEnumerable<MotionHandle>.GetEnumerator() => GetEnumerator();
39         IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
40         public void Complete() => Drain(true);
41         public void Cancel() => Drain(false);
42 
43         void Drain(bool complete)
44         {
45             if (handles.Count == 0) return;
46             // Keep callback edits to the collection independent of the current batch.
47             var pending = handles.ToArray();
48             handles.Clear();
49             int index = 0;
50             try
51             {
52                 for (; index < pending.Length; index++)
53                 {
54                     var handle = pending[index];
55                     if (!handle.IsActive()) continue;
56                     if (complete) handle.Complete();
57                     else handle.Cancel();
58                 }
59             }
60             catch
61             {
62                 // Keep the failed and unprocessed entries available for a later Cancel.
63                 handles.InsertRange(0, new ArraySegment<MotionHandle>(pending, index, pending.Length - index));
64                 throw;
65             }
66         }
67     }
68 
69     public static class MotionHandleExtensions
70     {
71         public static bool IsValid(this MotionHandle handle) => handle.Node != null;
72         public static bool IsActive(this MotionHandle handle) => handle.IsActive();
73         public static bool IsPlaying(this MotionHandle handle) => handle.IsPlaying();
74         public static MotionHandle Preserve(this MotionHandle handle) => handle.Preserve();
75         public static void Complete(this MotionHandle handle) => handle.Complete();
76         public static bool TryComplete(this MotionHandle handle) => handle.TryComplete();
77         public static void Cancel(this MotionHandle handle) => handle.Cancel();
78         public static bool TryCancel(this MotionHandle handle) => handle.TryCancel();
79         public static string GetDebugName(this MotionHandle handle)
80         {
81 #if MEATMOTION_DEBUG_NAMES
82             return handle.RequireValid().DebugName ?? handle.ToString();
83 #else
84             return handle.ToString();
85 #endif
86         }
87 
88         public static MotionHandle AddTo(this MotionHandle handle, CompositeMotionHandle compositeMotionHandle)
89         {
90             compositeMotionHandle.Add(handle);
91             return handle;
92         }
93 
94         public static MotionHandle AddTo(this MotionHandle handle, GameObject target) => handle.AddTo(target, LinkBehavior.CancelOnDestroy);
95         public static MotionHandle AddTo(this MotionHandle handle, Component target) => handle.AddTo(target.gameObject);
96         public static MotionHandle AddTo(this MotionHandle handle, Component target, LinkBehavior linkBehaviour) => handle.AddTo(target.gameObject, linkBehaviour);
97         public static MotionHandle AddTo(this MotionHandle handle, GameObject target, LinkBehavior linkBehaviour)
98         {
99             if (!target.TryGetComponent<MotionHandleLinker>(out var linker)) linker = target.AddComponent<MotionHandleLinker>();
100             linker.Register(handle, linkBehaviour);
101             return handle;
102         }
103         public static MotionHandle AddTo(this MotionHandle handle, MonoBehaviour target)
104         {
105             if (handle.Node is { Active: true } node)
106                 new ComponentLink(handle).Register(node, target.destroyCancellationToken);
107             return handle;
108         }
109 
110         sealed class ComponentLink : MotionObserver
111         {
112             readonly MotionHandle handle;
113             CancellationTokenRegistration registration;
114             internal ComponentLink(MotionHandle handle) => this.handle = handle;
115             internal void Register(MotionNode node, CancellationToken token)
116             {
117                 Attach(node);
118                 registration = token.Register(static x => ((ComponentLink)x).handle.TryCancel(), this);
119                 if (!handle.IsActive()) registration.Dispose();
120             }
121             protected override void Signal(bool completed)
122             {
123                 if (handle.Node is { Active: true } node) Attach(node);
124                 else registration.Dispose();
125             }
126             protected override void OnReset() => registration.Dispose();
127         }
128 
129         sealed class MotionDisposable : IDisposable
130         {
131             internal MotionHandle Handle;
132             internal DisposeBehavior Behavior;
133             public void Dispose()
134             {
135                 if (Behavior == DisposeBehavior.Complete) Handle.TryComplete();
136                 else if (Behavior == DisposeBehavior.Cancel) Handle.TryCancel();
137             }
138         }
139         public static IDisposable ToDisposable(this MotionHandle handle, DisposeBehavior disposeBehavior = DisposeBehavior.Cancel)
140             => new MotionDisposable { Handle = handle, Behavior = disposeBehavior };
141         public static IEnumerator ToYieldInstruction(this MotionHandle handle)
142         {
143             while (handle.IsActive()) yield return null;
144         }
145         public static MotionAwaiter GetAwaiter(this MotionHandle handle) => new MotionAwaiter(handle);
146 
147         public static ValueTask ToValueTask(this MotionHandle handle, CancellationToken cancellationToken = default)
148             => handle.ToValueTask(CancelBehavior.Cancel, true, cancellationToken);
149         public static ValueTask ToValueTask(this MotionHandle handle, CancelBehavior cancelBehavior, CancellationToken cancellationToken = default)
150             => handle.ToValueTask(cancelBehavior, true, cancellationToken);
151         public static ValueTask ToValueTask(this MotionHandle handle, CancelBehavior cancelBehavior, bool cancelAwaitOnMotionCanceled, CancellationToken cancellationToken = default)
152         {
153             var node = handle.Node;
154             if (node?.Active != true) return default;
155             if (!cancellationToken.CanBeCanceled) return TokenlessValueWait.Create(node, cancelAwaitOnMotionCanceled);
156             var wait = new MotionWait();
157             var result = wait.ValueTask;
158             wait.Start(handle, cancelBehavior, cancelAwaitOnMotionCanceled, cancellationToken);
159             return result;
160         }
161 
162         public static Awaitable ToAwaitable(this MotionHandle handle, CancellationToken cancellationToken = default)
163             => handle.ToAwaitable(CancelBehavior.Cancel, true, cancellationToken);
164         public static Awaitable ToAwaitable(this MotionHandle handle, CancelBehavior cancelBehavior, CancellationToken cancellationToken = default)
165             => handle.ToAwaitable(cancelBehavior, true, cancellationToken);
166         public static Awaitable ToAwaitable(this MotionHandle handle, CancelBehavior cancelBehavior, bool cancelAwaitOnMotionCanceled, CancellationToken cancellationToken = default)
167         {
168             var source = new AwaitableCompletionSource();
169             var result = source.Awaitable;
170             if (handle.IsActive()) new MotionWait(source).Start(handle, cancelBehavior, cancelAwaitOnMotionCanceled, cancellationToken);
171             else source.SetResult();
172             return result;
173         }
174     }
175 }