A game about forced loneliness, made by TACStudios
at master 74 lines 2.7 kB view raw
1using System; 2using UnityEngine; 3using Unity.Collections; 4using Unity.Collections.LowLevel.Unsafe; 5using Unity.Jobs; 6using Unity.Burst; 7 8namespace UnityEditor.U2D.Common 9{ 10 [BurstCompile] 11 internal struct FindTightRectJob : IJobParallelFor 12 { 13 [ReadOnly, DeallocateOnJobCompletion] 14 NativeArray<IntPtr> m_Buffers; 15 [ReadOnly, DeallocateOnJobCompletion] 16 NativeArray<int> m_Width; 17 [ReadOnly, DeallocateOnJobCompletion] 18 NativeArray<int> m_Height; 19 NativeArray<RectInt> m_Output; 20 21 public unsafe void Execute(int index) 22 { 23 var rect = new RectInt(m_Width[index], m_Height[index], 0, 0); 24 25 if (m_Height[index] == 0 || m_Width[index] == 0) 26 { 27 m_Output[index] = rect; 28 return; 29 } 30 31 var color = (Color32*)m_Buffers[index].ToPointer(); 32 for (int i = 0; i < m_Height[index]; ++i) 33 { 34 for (int j = 0; j < m_Width[index]; ++j) 35 { 36 if (color->a != 0) 37 { 38 rect.x = Mathf.Min(j, rect.x); 39 rect.y = Mathf.Min(i, rect.y); 40 rect.width = Mathf.Max(j, rect.width); 41 rect.height = Mathf.Max(i, rect.height); 42 } 43 ++color; 44 } 45 } 46 rect.width = Mathf.Max(0, rect.width - rect.x + 1); 47 rect.height = Mathf.Max(0, rect.height - rect.y + 1); 48 m_Output[index] = rect; 49 } 50 51 public static unsafe RectInt[] Execute(NativeArray<Color32>[] buffers, int[] width, int[] height) 52 { 53 var job = new FindTightRectJob(); 54 job.m_Buffers = new NativeArray<IntPtr>(buffers.Length, Allocator.TempJob); 55 job.m_Width = new NativeArray<int>(width.Length, Allocator.TempJob); 56 job.m_Height = new NativeArray<int>(height.Length, Allocator.TempJob); 57 58 for (var i = 0; i < buffers.Length; ++i) 59 { 60 job.m_Buffers[i] = new IntPtr(buffers[i].GetUnsafeReadOnlyPtr()); 61 job.m_Width[i] = width[i]; 62 job.m_Height[i] = height[i]; 63 } 64 65 job.m_Output = new NativeArray<RectInt>(buffers.Length, Allocator.TempJob); 66 67 // Ensure all jobs are completed before we return since we don't own the buffers 68 job.Schedule(buffers.Length, 1).Complete(); 69 var rects = job.m_Output.ToArray(); 70 job.m_Output.Dispose(); 71 return rects; 72 } 73 } 74}