| | 1 | | using Cysharp.Threading.Tasks; |
| | 2 | | using GPUSkinning; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.Threading; |
| | 5 | | using UnityEngine; |
| | 6 | |
|
| | 7 | | public class GPUSkinningThrottlerService : IGPUSkinningThrottlerService |
| | 8 | | { |
| 430 | 9 | | private readonly Dictionary<IGPUSkinning, int> gpuSkinnings = new (); |
| | 10 | |
|
| | 11 | | private CancellationTokenSource cts; |
| | 12 | |
|
| | 13 | | public static GPUSkinningThrottlerService Create(bool initializeOnSpawn) |
| | 14 | | { |
| 430 | 15 | | GPUSkinningThrottlerService service = new GPUSkinningThrottlerService(); |
| | 16 | |
|
| 430 | 17 | | if (initializeOnSpawn) |
| 430 | 18 | | service.Initialize(); |
| | 19 | |
|
| 430 | 20 | | return service; |
| | 21 | | } |
| | 22 | |
|
| | 23 | | public void Initialize() |
| | 24 | | { |
| 855 | 25 | | cts = new CancellationTokenSource(); |
| 855 | 26 | | ThrottleUpdateAsync(cts.Token).Forget(); |
| 855 | 27 | | } |
| | 28 | |
|
| | 29 | | public void Register(IGPUSkinning gpuSkinning, int framesBetweenUpdates = 1) |
| | 30 | | { |
| 5 | 31 | | if (!gpuSkinnings.ContainsKey(gpuSkinning)) |
| 5 | 32 | | gpuSkinnings.Add(gpuSkinning, framesBetweenUpdates); |
| | 33 | | else |
| 0 | 34 | | ModifyThrottling(gpuSkinning, framesBetweenUpdates); |
| 0 | 35 | | } |
| | 36 | |
|
| | 37 | | public void Unregister(IGPUSkinning gpuSkinning) |
| | 38 | | { |
| 521 | 39 | | if (gpuSkinnings.ContainsKey(gpuSkinning)) |
| 0 | 40 | | gpuSkinnings.Remove(gpuSkinning); |
| 521 | 41 | | } |
| | 42 | |
|
| | 43 | | public void ModifyThrottling(IGPUSkinning gpuSkinning, int framesBetweenUpdates) |
| | 44 | | { |
| 5 | 45 | | if (gpuSkinnings.ContainsKey(gpuSkinning)) |
| 5 | 46 | | gpuSkinnings[gpuSkinning] = framesBetweenUpdates; |
| 5 | 47 | | } |
| | 48 | |
|
| | 49 | | public void ForceStop() |
| | 50 | | { |
| 1 | 51 | | Cancel(); |
| 1 | 52 | | } |
| | 53 | |
|
| | 54 | | public void Dispose() |
| | 55 | | { |
| 431 | 56 | | Cancel(); |
| 431 | 57 | | gpuSkinnings.Clear(); |
| 431 | 58 | | } |
| | 59 | |
|
| | 60 | | private void Cancel() |
| | 61 | | { |
| 432 | 62 | | if (cts != null) |
| | 63 | | { |
| 430 | 64 | | cts.Cancel(); |
| 430 | 65 | | cts.Dispose(); |
| 430 | 66 | | cts = null; |
| | 67 | | } |
| 432 | 68 | | } |
| | 69 | |
|
| | 70 | | private async UniTaskVoid ThrottleUpdateAsync(CancellationToken ct) |
| | 71 | | { |
| 2565 | 72 | | await UniTask.DelayFrame(1, PlayerLoopTiming.PostLateUpdate, ct); |
| | 73 | |
|
| | 74 | | // Cancel gracefully |
| 6570668 | 75 | | while (!ct.IsCancellationRequested) |
| | 76 | | { |
| 13141408 | 77 | | foreach (KeyValuePair<IGPUSkinning, int> entry in gpuSkinnings) |
| 36 | 78 | | if (Time.frameCount % entry.Value == 0) |
| 23 | 79 | | entry.Key.Update(); |
| | 80 | |
|
| 19711579 | 81 | | await UniTask.DelayFrame(1, PlayerLoopTiming.PostLateUpdate, ct); |
| | 82 | | } |
| 0 | 83 | | } |
| | 84 | | } |