Mirror of Svelto.ECS because we're a fan of it
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.

83 lines
2.5KB

  1. #if UNITY_NATIVE //because of the thread count, ATM this is only for unity
  2. using System;
  3. using System.Runtime.CompilerServices;
  4. using Svelto.Common;
  5. using Unity.Jobs.LowLevel.Unsafe;
  6. using Allocator = Svelto.Common.Allocator;
  7. namespace Svelto.ECS.DataStructures
  8. {
  9. public unsafe struct AtomicNativeBags:IDisposable
  10. {
  11. public uint count => _threadsCount;
  12. public AtomicNativeBags(Allocator allocator)
  13. {
  14. _allocator = allocator;
  15. _threadsCount = JobsUtility.MaxJobThreadCount + 1;
  16. var bufferSize = MemoryUtilities.SizeOf<NativeBag>();
  17. var bufferCount = _threadsCount;
  18. var allocationSize = bufferSize * bufferCount;
  19. var ptr = (byte*)MemoryUtilities.Alloc((uint) allocationSize, allocator);
  20. // MemoryUtilities.MemClear((IntPtr) ptr, (uint) allocationSize);
  21. for (int i = 0; i < bufferCount; i++)
  22. {
  23. var bufferPtr = (NativeBag*)(ptr + bufferSize * i);
  24. var buffer = new NativeBag(allocator);
  25. MemoryUtilities.CopyStructureToPtr(ref buffer, (IntPtr) bufferPtr);
  26. }
  27. _data = (NativeBag*)ptr;
  28. }
  29. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  30. public ref NativeBag GetBuffer(int index)
  31. {
  32. #if DEBUG
  33. if (_data == null)
  34. throw new Exception("using invalid AtomicNativeBags");
  35. #endif
  36. return ref MemoryUtilities.ArrayElementAsRef<NativeBag>((IntPtr) _data, index);
  37. }
  38. public void Dispose()
  39. {
  40. #if DEBUG
  41. if (_data == null)
  42. throw new Exception("using invalid AtomicNativeBags");
  43. #endif
  44. for (int i = 0; i < _threadsCount; i++)
  45. {
  46. GetBuffer(i).Dispose();
  47. }
  48. MemoryUtilities.Free((IntPtr) _data, _allocator);
  49. _data = null;
  50. }
  51. public void Clear()
  52. {
  53. #if DEBUG
  54. if (_data == null)
  55. throw new Exception("using invalid AtomicNativeBags");
  56. #endif
  57. for (int i = 0; i < _threadsCount; i++)
  58. {
  59. GetBuffer(i).Clear();
  60. }
  61. }
  62. #if UNITY_COLLECTIONS || UNITY_JOBS || UNITY_BURST
  63. [global::Unity.Collections.LowLevel.Unsafe.NativeDisableUnsafePtrRestriction]
  64. #endif
  65. NativeBag* _data;
  66. readonly Allocator _allocator;
  67. readonly uint _threadsCount;
  68. }
  69. }
  70. #endif