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.

76 lines
2.4KB

  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. [global::Unity.Collections.LowLevel.Unsafe.NativeDisableUnsafePtrRestriction]
  12. NativeBag* _data;
  13. readonly Allocator _allocator;
  14. readonly uint _threadsCount;
  15. public uint count => _threadsCount;
  16. public AtomicNativeBags(Allocator allocator)
  17. {
  18. _allocator = allocator;
  19. _threadsCount = JobsUtility.MaxJobThreadCount + 1;
  20. var bufferSize = MemoryUtilities.SizeOf<NativeBag>();
  21. var bufferCount = _threadsCount;
  22. var allocationSize = bufferSize * bufferCount;
  23. var ptr = (byte*)MemoryUtilities.Alloc((uint) allocationSize, allocator);
  24. // MemoryUtilities.MemClear((IntPtr) ptr, (uint) allocationSize);
  25. for (int i = 0; i < bufferCount; i++)
  26. {
  27. var bufferPtr = (NativeBag*)(ptr + bufferSize * i);
  28. var buffer = new NativeBag(allocator);
  29. MemoryUtilities.CopyStructureToPtr(ref buffer, (IntPtr) bufferPtr);
  30. }
  31. _data = (NativeBag*)ptr;
  32. }
  33. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  34. public ref NativeBag GetBuffer(int index)
  35. {
  36. if (_data == null)
  37. throw new Exception("using invalid AtomicNativeBags");
  38. return ref MemoryUtilities.ArrayElementAsRef<NativeBag>((IntPtr) _data, index);
  39. }
  40. public void Dispose()
  41. {
  42. if (_data == null)
  43. throw new Exception("using invalid AtomicNativeBags");
  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 (_data == null)
  54. throw new Exception("using invalid AtomicNativeBags");
  55. for (int i = 0; i < _threadsCount; i++)
  56. {
  57. GetBuffer(i).Clear();
  58. }
  59. }
  60. }
  61. }
  62. #endif