Nessuna descrizione
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.

NativeReference.cs 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using Unity.Burst;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using Unity.Jobs;
  7. namespace Unity.Collections
  8. {
  9. /// <summary>
  10. /// An unmanaged single value.
  11. /// </summary>
  12. /// <remarks>The functional equivalent of an array of length 1.
  13. /// When you need just one value, NativeReference can be preferable to an array because it better conveys the intent.</remarks>
  14. /// <typeparam name="T">The type of value.</typeparam>
  15. [StructLayout(LayoutKind.Sequential)]
  16. [NativeContainer]
  17. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  18. public unsafe struct NativeReference<T>
  19. : INativeDisposable
  20. , IEquatable<NativeReference<T>>
  21. where T : unmanaged
  22. {
  23. [NativeDisableUnsafePtrRestriction]
  24. internal void* m_Data;
  25. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  26. internal AtomicSafetyHandle m_Safety;
  27. static readonly SharedStatic<int> s_SafetyId = SharedStatic<int>.GetOrCreate<NativeReference<T>>();
  28. #endif
  29. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  30. /// <summary>
  31. /// Initializes and returns an instance of NativeReference.
  32. /// </summary>
  33. /// <param name="allocator">The allocator to use.</param>
  34. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  35. public NativeReference(AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  36. {
  37. Allocate(allocator, out this);
  38. if (options == NativeArrayOptions.ClearMemory)
  39. {
  40. UnsafeUtility.MemClear(m_Data, UnsafeUtility.SizeOf<T>());
  41. }
  42. }
  43. /// <summary>
  44. /// Initializes and returns an instance of NativeReference.
  45. /// </summary>
  46. /// <param name="allocator">The allocator to use.</param>
  47. /// <param name="value">The initial value.</param>
  48. public NativeReference(T value, AllocatorManager.AllocatorHandle allocator)
  49. {
  50. Allocate(allocator, out this);
  51. *(T*)m_Data = value;
  52. }
  53. static void Allocate(AllocatorManager.AllocatorHandle allocator, out NativeReference<T> reference)
  54. {
  55. CollectionHelper.CheckAllocator(allocator);
  56. reference = default;
  57. reference.m_Data = Memory.Unmanaged.Allocate(UnsafeUtility.SizeOf<T>(), UnsafeUtility.AlignOf<T>(), allocator);
  58. reference.m_AllocatorLabel = allocator;
  59. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  60. reference.m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
  61. CollectionHelper.InitNativeContainer<T>(reference.m_Safety);
  62. CollectionHelper.SetStaticSafetyId<NativeQueue<T>>(ref reference.m_Safety, ref s_SafetyId.Data);
  63. #endif
  64. }
  65. /// <summary>
  66. /// The value stored in this reference.
  67. /// </summary>
  68. /// <param name="value">The new value to store in this reference.</param>
  69. /// <value>The value stored in this reference.</value>
  70. public T Value
  71. {
  72. get
  73. {
  74. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  75. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  76. #endif
  77. return *(T*)m_Data;
  78. }
  79. set
  80. {
  81. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  82. AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
  83. #endif
  84. *(T*)m_Data = value;
  85. }
  86. }
  87. /// <summary>
  88. /// Whether this reference has been allocated (and not yet deallocated).
  89. /// </summary>
  90. /// <value>True if this reference has been allocated (and not yet deallocated).</value>
  91. public readonly bool IsCreated => m_Data != null;
  92. /// <summary>
  93. /// Releases all resources (memory and safety handles).
  94. /// </summary>
  95. public void Dispose()
  96. {
  97. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  98. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  99. {
  100. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  101. }
  102. #endif
  103. if (!IsCreated)
  104. {
  105. return;
  106. }
  107. if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
  108. {
  109. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  110. CollectionHelper.DisposeSafetyHandle(ref m_Safety);
  111. #endif
  112. Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
  113. m_AllocatorLabel = Allocator.Invalid;
  114. }
  115. m_Data = null;
  116. }
  117. /// <summary>
  118. /// Creates and schedules a job that will release all resources (memory and safety handles) of this reference.
  119. /// </summary>
  120. /// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
  121. /// <returns>The handle of a new job that will release all resources (memory and safety handles) of this reference.</returns>
  122. public JobHandle Dispose(JobHandle inputDeps)
  123. {
  124. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  125. if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
  126. {
  127. AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
  128. }
  129. #endif
  130. if (!IsCreated)
  131. {
  132. return inputDeps;
  133. }
  134. if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
  135. {
  136. var jobHandle = new NativeReferenceDisposeJob
  137. {
  138. Data = new NativeReferenceDispose
  139. {
  140. m_Data = m_Data,
  141. m_AllocatorLabel = m_AllocatorLabel,
  142. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  143. m_Safety = m_Safety
  144. #endif
  145. }
  146. }.Schedule(inputDeps);
  147. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  148. AtomicSafetyHandle.Release(m_Safety);
  149. #endif
  150. m_Data = null;
  151. m_AllocatorLabel = Allocator.Invalid;
  152. return jobHandle;
  153. }
  154. m_Data = null;
  155. return inputDeps;
  156. }
  157. /// <summary>
  158. /// Copy the value of another reference to this reference.
  159. /// </summary>
  160. /// <param name="reference">The reference to copy from.</param>
  161. public void CopyFrom(NativeReference<T> reference)
  162. {
  163. Copy(this, reference);
  164. }
  165. /// <summary>
  166. /// Copy the value of this reference to another reference.
  167. /// </summary>
  168. /// <param name="reference">The reference to copy to.</param>
  169. public void CopyTo(NativeReference<T> reference)
  170. {
  171. Copy(reference, this);
  172. }
  173. /// <summary>
  174. /// Returns true if the value stored in this reference is equal to the value stored in another reference.
  175. /// </summary>
  176. /// <param name="other">A reference to compare with.</param>
  177. /// <returns>True if the value stored in this reference is equal to the value stored in another reference.</returns>
  178. [ExcludeFromBurstCompatTesting("Equals boxes because Value does not implement IEquatable<T>")]
  179. public bool Equals(NativeReference<T> other)
  180. {
  181. return Value.Equals(other.Value);
  182. }
  183. /// <summary>
  184. /// Returns true if the value stored in this reference is equal to an object.
  185. /// </summary>
  186. /// <remarks>Can only be equal if the object is itself a NativeReference.</remarks>
  187. /// <param name="obj">An object to compare with.</param>
  188. /// <returns>True if the value stored in this reference is equal to the object.</returns>
  189. [ExcludeFromBurstCompatTesting("Takes managed object")]
  190. public override bool Equals(object obj)
  191. {
  192. if (ReferenceEquals(null, obj))
  193. {
  194. return false;
  195. }
  196. return obj is NativeReference<T> && Equals((NativeReference<T>)obj);
  197. }
  198. /// <summary>
  199. /// Returns the hash code of this reference.
  200. /// </summary>
  201. /// <returns>The hash code of this reference.</returns>
  202. public override int GetHashCode()
  203. {
  204. return Value.GetHashCode();
  205. }
  206. /// <summary>
  207. /// Returns true if the values stored in two references are equal.
  208. /// </summary>
  209. /// <param name="left">A reference.</param>
  210. /// <param name="right">Another reference.</param>
  211. /// <returns>True if the two values are equal.</returns>
  212. public static bool operator ==(NativeReference<T> left, NativeReference<T> right)
  213. {
  214. return left.Equals(right);
  215. }
  216. /// <summary>
  217. /// Returns true if the values stored in two references are unequal.
  218. /// </summary>
  219. /// <param name="left">A reference.</param>
  220. /// <param name="right">Another reference.</param>
  221. /// <returns>True if the two values are unequal.</returns>
  222. public static bool operator !=(NativeReference<T> left, NativeReference<T> right)
  223. {
  224. return !left.Equals(right);
  225. }
  226. /// <summary>
  227. /// Copies the value of a reference to another reference.
  228. /// </summary>
  229. /// <param name="dst">The destination reference.</param>
  230. /// <param name="src">The source reference.</param>
  231. public static void Copy(NativeReference<T> dst, NativeReference<T> src)
  232. {
  233. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  234. AtomicSafetyHandle.CheckReadAndThrow(src.m_Safety);
  235. AtomicSafetyHandle.CheckWriteAndThrow(dst.m_Safety);
  236. #endif
  237. UnsafeUtility.MemCpy(dst.m_Data, src.m_Data, UnsafeUtility.SizeOf<T>());
  238. }
  239. /// <summary>
  240. /// Returns a read-only reference aliasing the value of this reference.
  241. /// </summary>
  242. /// <returns>A read-only reference aliasing the value of this reference.</returns>
  243. public ReadOnly AsReadOnly()
  244. {
  245. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  246. return new ReadOnly(m_Data, ref m_Safety);
  247. #else
  248. return new ReadOnly(m_Data);
  249. #endif
  250. }
  251. /// <summary>
  252. /// Returns a read-only native reference that aliases the content of a native reference.
  253. /// </summary>
  254. /// <param name="nativeReference">NativeReference to alias.</param>
  255. /// <returns>A read-only native reference that aliases the content of a native reference.</returns>
  256. public static implicit operator ReadOnly(NativeReference<T> nativeReference)
  257. {
  258. return nativeReference.AsReadOnly();
  259. }
  260. /// <summary>
  261. /// A read-only alias for the value of a NativeReference. Does not have its own allocated storage.
  262. /// </summary>
  263. [NativeContainer]
  264. [NativeContainerIsReadOnly]
  265. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  266. public unsafe struct ReadOnly
  267. {
  268. [NativeDisableUnsafePtrRestriction]
  269. readonly void* m_Data;
  270. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  271. AtomicSafetyHandle m_Safety;
  272. internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
  273. [GenerateTestsForBurstCompatibility(CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
  274. internal ReadOnly(void* data, ref AtomicSafetyHandle safety)
  275. {
  276. m_Data = data;
  277. m_Safety = safety;
  278. CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
  279. }
  280. #else
  281. internal ReadOnly(void* data)
  282. {
  283. m_Data = data;
  284. }
  285. #endif
  286. /// <summary>
  287. /// The value aliased by this reference.
  288. /// </summary>
  289. /// <value>The value aliased by the reference.</value>
  290. public T Value
  291. {
  292. get
  293. {
  294. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  295. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  296. #endif
  297. return *(T*)m_Data;
  298. }
  299. }
  300. }
  301. }
  302. [NativeContainer]
  303. unsafe struct NativeReferenceDispose
  304. {
  305. [NativeDisableUnsafePtrRestriction]
  306. internal void* m_Data;
  307. internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
  308. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  309. internal AtomicSafetyHandle m_Safety;
  310. #endif
  311. public void Dispose()
  312. {
  313. Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
  314. }
  315. }
  316. [BurstCompile]
  317. struct NativeReferenceDisposeJob : IJob
  318. {
  319. internal NativeReferenceDispose Data;
  320. public void Execute()
  321. {
  322. Data.Dispose();
  323. }
  324. }
  325. }
  326. namespace Unity.Collections.LowLevel.Unsafe
  327. {
  328. /// <summary>
  329. /// Provides extension methods for NativeReference.
  330. /// </summary>
  331. [GenerateTestsForBurstCompatibility]
  332. public static class NativeReferenceUnsafeUtility
  333. {
  334. /// <summary>
  335. /// Returns a pointer to this reference's stored value.
  336. /// </summary>
  337. /// <remarks>Performs a job safety check for read-write access.</remarks>
  338. /// <typeparam name="T">The type of the value.</typeparam>
  339. /// <param name="reference">The reference.</param>
  340. /// <returns>A pointer to this reference's stored value.</returns>
  341. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  342. public static unsafe T* GetUnsafePtr<T>(this NativeReference<T> reference)
  343. where T : unmanaged
  344. {
  345. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  346. AtomicSafetyHandle.CheckWriteAndThrow(reference.m_Safety);
  347. #endif
  348. return (T*)reference.m_Data;
  349. }
  350. /// <summary>
  351. /// Returns a pointer to this reference's stored value.
  352. /// </summary>
  353. /// <remarks>Performs a job safety check for read-only access.</remarks>
  354. /// <typeparam name="T">The type of the value.</typeparam>
  355. /// <param name="reference">The reference.</param>
  356. /// <returns>A pointer to this reference's stored value.</returns>
  357. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  358. public static unsafe T* GetUnsafeReadOnlyPtr<T>(this NativeReference<T> reference)
  359. where T : unmanaged
  360. {
  361. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  362. AtomicSafetyHandle.CheckReadAndThrow(reference.m_Safety);
  363. #endif
  364. return (T*)reference.m_Data;
  365. }
  366. /// <summary>
  367. /// Returns a pointer to this reference's stored value.
  368. /// </summary>
  369. /// <remarks>Performs no job safety checks.</remarks>
  370. /// <typeparam name="T">The type of the value.</typeparam>
  371. /// <param name="reference">The reference.</param>
  372. /// <returns>A pointer to this reference's stored value.</returns>
  373. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
  374. public static unsafe T* GetUnsafePtrWithoutChecks<T>(this NativeReference<T> reference)
  375. where T : unmanaged
  376. {
  377. return (T*)reference.m_Data;
  378. }
  379. }
  380. }