FishPlayer

一个喜欢摸鱼的废物

0%

给PrimeTween新增小小的异步代码支持

最近做的新项目没有使用 DOTween 了,转而使用性能比较高的 PrimeTween。这是一个比较新的插件,看了下大概是前两年上架的。
比起历史悠久的 DOTween 相比, PrimeTween 虽然性能很高,但是不像 DOTween 有丰富的特性以及一些额外的其它插件的联动支持。

具体的就说 UniTask 吧,他有一个专门的拓展类给予 DOTwee 异步相关的支持。这里面有我现在马上就需要用到的 “使用 CancellationToken 取消对 Tween 的异步等待” 的功能。

PrimeTween 没有这个支持,没关系,我只要照着这个拓展类抄一个就好,虽然这俩Tween的实现不太一样,但是核心的行为还是非常相似的。

思路

稍微点F12跳两下就发现,其实这个功能的实现思路就是通过方法 CancellationToken.Register 去给C ancellationToken 收到取消请求的时机注册一个回调。在这个回调中去处理关于Tween的各种处理。

DOTween 的拓展处理中会把原本 Tween 的正常播放完成相关回调拿出来然后缓存在自己的结构中并换上自己的响应动画的正常完成。PrimeTween 和 DOTween 不一样的地方在于 PrimeTween 的回调不能重复绑定,所以照着抄的时候为了保证代码的一致性,我选择用 PrimeTween 插件中的 Sequence 把原本的 Tween/Sequence 包装起来,似乎这个应该是他插件本身就推荐的做法。当然包起来以后就不可以再编辑原 Tween 的一些参数了。

PrimeTween 高性能的原因似乎是他把实际执行 Tween 行为的实例都用对象池管理起来了,不像 DOTween 需要用户自己管理动画实例对象。而且 DOTween 的用于存放相关动画参数的数据结构 TweenSetting 好像也是类,这点其实让我有点讨厌。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455

namespace Cysharp.Threading.Tasks
{
public enum TweenCancelBehaviour
{
KillAndCancelAwait,
// TODO @Hiko finish those cancel behaviour if really need :)
// Kill,
//KillWithCompleteCallback,
}

public static class PrimeTweenAsyncExtensions
{
public struct TweenAwaiter : ICriticalNotifyCompletion
{
private readonly Tween tween;
private readonly Sequence warppedSequence;

// killed(non active) as completed.
public bool IsCompleted => !tween.isAlive;

public TweenAwaiter(Tween tween)
{
this.tween = tween;
warppedSequence = Sequence.Create(this.tween);
}

public TweenAwaiter GetAwaiter()
{
return this;
}

public void GetResult() { }

public void OnCompleted(Action continuation)
{
UnsafeOnCompleted(continuation);
}

public void UnsafeOnCompleted(Action continuation)
{
// onKill is called after OnCompleted, both Complete(false/true) and Kill(false/true).
warppedSequence.OnComplete(PooledPrimeTweenCallback.Create(continuation));
}
}

public static TweenAwaiter GetAwaiter(this Tween tween)
{
return new TweenAwaiter(tween);
}

public static UniTask WithCancellation(in this Tween tween, CancellationToken cancellationToken)
{
if (!tween.isAlive) return UniTask.CompletedTask;
return new UniTask(TweenConfiguredSource.Create(tween, TweenCancelBehaviour.KillAndCancelAwait, cancellationToken, out var token, out _), token);
}

public static UniTask WithCancellation(in this Tween tween, CancellationToken cancellationToken, out Sequence warppedTween)
{
warppedTween = default;
if (!tween.isAlive) return UniTask.CompletedTask;
return new UniTask(TweenConfiguredSource.Create(tween, TweenCancelBehaviour.KillAndCancelAwait, cancellationToken, out var token, out warppedTween), token);
}

private sealed class TweenConfiguredSource : IUniTaskSource, ITaskPoolNode<TweenConfiguredSource>
{
private static TaskPool<TweenConfiguredSource> s_pool;

private TweenConfiguredSource m_nextNode;

private Tween m_tween;
// use sequence to warp the original tween cuz original tween may already bind a completion callback
private Sequence m_warppedSequence;

private TweenCancelBehaviour m_cancelBehaviour;
private CancellationToken m_cancellationToken;
private CancellationTokenRegistration m_cancellationRegistration;
bool m_isCanceled;

private UniTaskCompletionSourceCore<AsyncUnit> m_core;

/// <summary>
/// event will be triggered when the tween completes normally
/// </summary>
private readonly Action m_tweenCompleteNotifyCallback;

public ref TweenConfiguredSource NextNode => ref m_nextNode;

static TweenConfiguredSource()
{
TaskPool.RegisterSizeGetter(typeof(TweenConfiguredSource), () => s_pool.Size);
}

private TweenConfiguredSource()
{
m_tweenCompleteNotifyCallback = OnTweenCompleteCallbackDelegate;
}

public static IUniTaskSource Create(Tween tween, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, out short token)
{
return Create(tween, cancelBehaviour, cancellationToken, out token, out _);
}

public static IUniTaskSource Create(Tween tween, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, out short token, out Sequence warppedTween)
{
if (cancellationToken.IsCancellationRequested)
{
DoCancelBeforeCreate(tween, cancelBehaviour);
warppedTween = default;
return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
}

if (!s_pool.TryPop(out var result))
{
result = new TweenConfiguredSource();
}

result.m_tween = tween;
result.m_cancelBehaviour = cancelBehaviour;
result.m_cancellationToken = cancellationToken;
result.m_isCanceled = false;
// warp the original tween and bind our comlete callback
result.m_warppedSequence = Sequence.Create(result.m_tween);
result.m_warppedSequence.OnComplete(result.m_tweenCompleteNotifyCallback);

if (cancellationToken.CanBeCanceled)
{
result.m_cancellationRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(x =>
{
TweenConfiguredSource source = (TweenConfiguredSource)x;
switch (source.m_cancelBehaviour)
{
case TweenCancelBehaviour.KillAndCancelAwait:
default:
// token canceled stop tween
source.m_isCanceled = true;
source.m_warppedSequence.Stop();
source.OnTweenCompleteCallbackDelegate();
break;
}
}, result);
}

TaskTracker.TrackActiveTask(result, 3);
token = result.m_core.Version;
warppedTween = result.m_warppedSequence;
return result;
}

private static void DoCancelBeforeCreate(Tween tween, TweenCancelBehaviour tweenCancelBehaviour)
{
switch (tweenCancelBehaviour)
{
case TweenCancelBehaviour.KillAndCancelAwait:
default:
tween.Stop();
break;
}
}

public UniTaskStatus UnsafeGetStatus()
{
return m_core.UnsafeGetStatus();
}

public void OnCompleted(Action<object> continuation, object state, short token)
{
m_core.OnCompleted(continuation, state, token);
}

public void GetResult(short token)
{
try
{
m_core.GetResult(token);
}
finally
{
TryReturnSelfToPool();
}
}

public UniTaskStatus GetStatus(short token)
{
return m_core.GetStatus(token);
}

private bool TryReturnSelfToPool()
{
TaskTracker.RemoveTracking(this);
m_core.Reset();
m_cancellationRegistration.Dispose();

m_tween = default;
m_warppedSequence = default;
m_cancellationToken = default;
return s_pool.TryPush(this);
}

/// <summary>
/// Tween completes normally
/// </summary>
private void OnTweenCompleteCallbackDelegate()
{
if (m_isCanceled)
{
m_core.TrySetCanceled(m_cancellationToken);
}
else
{
m_core.TrySetResult(AsyncUnit.Default);
}
}
}

//----------------------------------

public struct SequenceAwaiter : ICriticalNotifyCompletion
{
private readonly Sequence originSequence;
private readonly Sequence warppedSequence;

// killed(non active) as completed.
public bool IsCompleted => !originSequence.isAlive;

public SequenceAwaiter(Sequence sequence)
{
originSequence = sequence;
warppedSequence = Sequence.Create();
warppedSequence.Insert(0f, sequence);
}

public SequenceAwaiter GetAwaiter()
{
return this;
}

public void GetResult() { }

public void OnCompleted(Action continuation)
{
UnsafeOnCompleted(continuation);
}

public void UnsafeOnCompleted(Action continuation)
{
// onKill is called after OnCompleted, both Complete(false/true) and Kill(false/true).
warppedSequence.OnComplete(PooledPrimeTweenCallback.Create(continuation));
}
}

public static SequenceAwaiter GetAwaiter(this Sequence tween)
{
return new SequenceAwaiter(tween);
}

public static UniTask WithCancellation(in this Sequence sequence, CancellationToken cancellationToken)
{
if (!sequence.isAlive) return UniTask.CompletedTask;
return new UniTask(SequenceConfiguredSource.Create(sequence, TweenCancelBehaviour.KillAndCancelAwait, cancellationToken, out var token, out _), token);
}

public static UniTask WithCancellation(in this Sequence sequence, CancellationToken cancellationToken, out Sequence warppedTween)
{
warppedTween = default;
if (!sequence.isAlive) return UniTask.CompletedTask;
return new UniTask(SequenceConfiguredSource.Create(sequence, TweenCancelBehaviour.KillAndCancelAwait, cancellationToken, out var token, out warppedTween), token);
}

private sealed class SequenceConfiguredSource : IUniTaskSource, ITaskPoolNode<SequenceConfiguredSource>
{
private static TaskPool<SequenceConfiguredSource> s_pool;

private SequenceConfiguredSource m_nextNode;

private Sequence m_originSequence;
// use sequence to warp the original sequence cuz original tween may already bind a completion callback
private Sequence m_warppedSequence;

private TweenCancelBehaviour m_cancelBehaviour;
private CancellationToken m_cancellationToken;
private CancellationTokenRegistration m_cancellationRegistration;
bool m_isCanceled;

private UniTaskCompletionSourceCore<AsyncUnit> m_core;

private readonly Action m_SequenceCompleteNotifyCallback;

public ref SequenceConfiguredSource NextNode => ref m_nextNode;

static SequenceConfiguredSource()
{
TaskPool.RegisterSizeGetter(typeof(SequenceConfiguredSource), () => s_pool.Size);
}

private SequenceConfiguredSource()
{
m_SequenceCompleteNotifyCallback = OnSequenceCompleteCallbackDelegate;
}

public static IUniTaskSource Create(Sequence Sequence, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, out short token)
{
return Create(Sequence, cancelBehaviour, cancellationToken, out token, out _);
}

public static IUniTaskSource Create(Sequence Sequence, TweenCancelBehaviour cancelBehaviour, CancellationToken cancellationToken, out short token, out Sequence warppedSequence)
{
if (cancellationToken.IsCancellationRequested)
{
DoCancelBeforeCreate(Sequence, cancelBehaviour);
warppedSequence = default;
return AutoResetUniTaskCompletionSource.CreateFromCanceled(cancellationToken, out token);
}

if (!s_pool.TryPop(out var result))
{
result = new SequenceConfiguredSource();
}

result.m_originSequence = Sequence;
result.m_cancelBehaviour = cancelBehaviour;
result.m_cancellationToken = cancellationToken;
result.m_isCanceled = false;

result.m_warppedSequence = Sequence.Create();
result.m_warppedSequence.Insert(0f, result.m_originSequence);
result.m_warppedSequence.OnComplete(result.m_SequenceCompleteNotifyCallback);

if (cancellationToken.CanBeCanceled)
{
result.m_cancellationRegistration = cancellationToken.RegisterWithoutCaptureExecutionContext(x =>
{
SequenceConfiguredSource source = (SequenceConfiguredSource)x;
switch (source.m_cancelBehaviour)
{
case TweenCancelBehaviour.KillAndCancelAwait:
source.m_isCanceled = true;
source.m_warppedSequence.Stop();
source.OnSequenceCompleteCallbackDelegate();
break;
default:
break;
}
}, result);
}

TaskTracker.TrackActiveTask(result, 3);
token = result.m_core.Version;
warppedSequence = result.m_warppedSequence;
return result;
}

private static void DoCancelBeforeCreate(Sequence Sequence, TweenCancelBehaviour tweenCancelBehaviour)
{
switch (tweenCancelBehaviour)
{
case TweenCancelBehaviour.KillAndCancelAwait:
default:
Sequence.Stop();
break;
}
}

public UniTaskStatus UnsafeGetStatus()
{
return m_core.UnsafeGetStatus();
}

public void OnCompleted(Action<object> continuation, object state, short token)
{
m_core.OnCompleted(continuation, state, token);
}

public void GetResult(short token)
{
try
{
m_core.GetResult(token);
}
finally
{
TryReturnSelfToPool();
}
}

public UniTaskStatus GetStatus(short token)
{
return m_core.GetStatus(token);
}

private bool TryReturnSelfToPool()
{
TaskTracker.RemoveTracking(this);
m_core.Reset();
m_cancellationRegistration.Dispose();

m_originSequence = default;
m_warppedSequence = default;
m_cancellationToken = default;
return s_pool.TryPush(this);
}

private void OnSequenceCompleteCallbackDelegate()
{
if (m_isCanceled)
{
m_core.TrySetCanceled(m_cancellationToken);
}
else
{
m_core.TrySetResult(AsyncUnit.Default);
}
}
}

}

public sealed class PooledPrimeTweenCallback
{
private static readonly ConcurrentQueue<PooledPrimeTweenCallback> s_pool = new ConcurrentQueue<PooledPrimeTweenCallback>();

private readonly Action m_runDelegate;
private Action m_continuation;

private PooledPrimeTweenCallback()
{
m_runDelegate = Run;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Action Create(Action continuation)
{
if (!s_pool.TryDequeue(out PooledPrimeTweenCallback item))
{
item = new PooledPrimeTweenCallback();
}

item.m_continuation = continuation;
return item.m_runDelegate;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Run()
{
Action call = m_continuation;
m_continuation = null;
if (call != null)
{
s_pool.Enqueue(this);
call.Invoke();
}
}

}
}