暫無描述
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FindTightRectJob.cs 2.6KB

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