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.

InputEventBuffer.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Unity.Collections;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using UnityEngine.InputSystem.Utilities;
  7. ////TODO: batch append method
  8. ////TODO: switch to NativeArray long length (think we have it in Unity 2018.3)
  9. ////REVIEW: can we get rid of kBufferSizeUnknown and force size to always be known? (think this would have to wait until
  10. //// the native changes have landed in 2018.3)
  11. namespace UnityEngine.InputSystem.LowLevel
  12. {
  13. /// <summary>
  14. /// A buffer of raw memory holding a sequence of <see cref="InputEvent">input events</see>.
  15. /// </summary>
  16. /// <remarks>
  17. /// Note that event buffers are not thread-safe. It is not safe to write events to the buffer
  18. /// concurrently from multiple threads. It is, however, safe to traverse the contents of an
  19. /// existing buffer from multiple threads as long as it is not mutated at the same time.
  20. /// </remarks>
  21. public unsafe struct InputEventBuffer : IEnumerable<InputEventPtr>, IDisposable, ICloneable
  22. {
  23. public const long BufferSizeUnknown = -1;
  24. /// <summary>
  25. /// Total number of events in the buffer.
  26. /// </summary>
  27. /// <value>Number of events currently in the buffer.</value>
  28. public int eventCount => m_EventCount;
  29. /// <summary>
  30. /// Size of the used portion of the buffer in bytes. Use <see cref="capacityInBytes"/> to
  31. /// get the total allocated size.
  32. /// </summary>
  33. /// <value>Used size of buffer in bytes.</value>
  34. /// <remarks>
  35. /// If the size is not known, returns <see cref="BufferSizeUnknown"/>.
  36. ///
  37. /// Note that the size does not usually correspond to <see cref="eventCount"/> times <c>sizeof(InputEvent)</c>.
  38. /// as <see cref="InputEvent"/> instances are variable in size.
  39. /// </remarks>
  40. public long sizeInBytes => m_SizeInBytes;
  41. /// <summary>
  42. /// Total size of allocated memory in bytes. This value minus <see cref="sizeInBytes"/> is the
  43. /// spare capacity of the buffer. Will never be less than <see cref="sizeInBytes"/>.
  44. /// </summary>
  45. /// <value>Size of allocated memory in bytes.</value>
  46. /// <remarks>
  47. /// A buffer's capacity determines how much event data can be written to the buffer before it has to be
  48. /// reallocated.
  49. /// </remarks>
  50. public long capacityInBytes
  51. {
  52. get
  53. {
  54. if (!m_Buffer.IsCreated)
  55. return 0;
  56. return m_Buffer.Length;
  57. }
  58. }
  59. /// <summary>
  60. /// The raw underlying memory buffer.
  61. /// </summary>
  62. /// <value>Underlying buffer of unmanaged memory.</value>
  63. public NativeArray<byte> data => m_Buffer;
  64. /// <summary>
  65. /// Pointer to the first event in the buffer.
  66. /// </summary>
  67. /// <value>Pointer to first event in buffer.</value>
  68. public InputEventPtr bufferPtr
  69. {
  70. // When using ConvertExistingDataToNativeArray, the NativeArray isn't getting a "safety handle" (seems like a bug)
  71. // and calling GetUnsafeReadOnlyPtr() will result in a NullReferenceException. Get the pointer without checks here.
  72. get { return (InputEvent*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer); }
  73. }
  74. /// <summary>
  75. /// Construct an event buffer using the given memory block containing <see cref="InputEvent"/>s.
  76. /// </summary>
  77. /// <param name="eventPtr">A buffer containing <paramref name="eventCount"/> number of input events. The
  78. /// individual events in the buffer are variable-sized (depending on the type of each event).</param>
  79. /// <param name="eventCount">The number of events in <paramref name="eventPtr"/>. Can be zero.</param>
  80. /// <param name="sizeInBytes">Total number of bytes of event data in the memory block pointed to by <paramref name="eventPtr"/>.
  81. /// If -1 (default), the size of the actual event data in the buffer is considered unknown and has to be determined by walking
  82. /// <paramref name="eventCount"/> number of events (due to the variable size of each event).</param>
  83. /// <param name="capacityInBytes">The total size of the memory block allocated at <paramref name="eventPtr"/>. If this
  84. /// is larger than <paramref name="sizeInBytes"/>, additional events can be appended to the buffer until the capacity
  85. /// is exhausted. If this is -1 (default), the capacity is considered unknown and no additional events can be
  86. /// appended to the buffer.</param>
  87. /// <exception cref="ArgumentException"><paramref name="eventPtr"/> is <c>null</c> and <paramref name="eventCount"/> is not zero
  88. /// -or- <paramref name="capacityInBytes"/> is less than <paramref name="sizeInBytes"/>.</exception>
  89. public InputEventBuffer(InputEvent* eventPtr, int eventCount, int sizeInBytes = -1, int capacityInBytes = -1)
  90. : this()
  91. {
  92. if (eventPtr == null && eventCount != 0)
  93. throw new ArgumentException("eventPtr is NULL but eventCount is != 0", nameof(eventCount));
  94. if (capacityInBytes != 0 && capacityInBytes < sizeInBytes)
  95. throw new ArgumentException($"capacity({capacityInBytes}) cannot be smaller than size({sizeInBytes})",
  96. nameof(capacityInBytes));
  97. if (eventPtr != null)
  98. {
  99. if (capacityInBytes < 0)
  100. capacityInBytes = sizeInBytes;
  101. m_Buffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(eventPtr,
  102. capacityInBytes > 0 ? capacityInBytes : 0, Allocator.None);
  103. m_SizeInBytes = sizeInBytes >= 0 ? sizeInBytes : BufferSizeUnknown;
  104. m_EventCount = eventCount;
  105. m_WeOwnTheBuffer = false;
  106. }
  107. }
  108. /// <summary>
  109. /// Construct an event buffer using the array containing <see cref="InputEvent"/>s.
  110. /// </summary>
  111. /// <param name="buffer">A native array containing <paramref name="eventCount"/> number of input events. The
  112. /// individual events in the buffer are variable-sized (depending on the type of each event).</param>
  113. /// <param name="eventCount">The number of events in <paramref name="buffer"/>. Can be zero.</param>
  114. /// <param name="sizeInBytes">Total number of bytes of event data in the <paramref cref="buffer"/>.
  115. /// If -1 (default), the size of the actual event data in <paramref name="buffer"/> is considered unknown and has to be determined by walking
  116. /// <paramref name="eventCount"/> number of events (due to the variable size of each event).</param>
  117. /// <param name="transferNativeArrayOwnership">If true, ownership of the <c>NativeArray</c> given by <paramref name="buffer"/> is
  118. /// transferred to the <c>InputEventBuffer</c>. Calling <see cref="Dispose"/> will deallocate the array. Also, <see cref="AllocateEvent"/>
  119. /// may re-allocate the array.</param>
  120. /// <exception cref="ArgumentException"><paramref name="buffer"/> has no memory allocated but <paramref name="eventCount"/> is not zero.</exception>
  121. /// <exception cref="ArgumentOutOfRangeException"><paramref name="sizeInBytes"/> is greater than the total length allocated for
  122. /// <paramref name="buffer"/>.</exception>
  123. public InputEventBuffer(NativeArray<byte> buffer, int eventCount, int sizeInBytes = -1, bool transferNativeArrayOwnership = false)
  124. {
  125. if (eventCount > 0 && !buffer.IsCreated)
  126. throw new ArgumentException("buffer has no data but eventCount is > 0", nameof(eventCount));
  127. if (sizeInBytes > buffer.Length)
  128. throw new ArgumentOutOfRangeException(nameof(sizeInBytes));
  129. m_Buffer = buffer;
  130. m_WeOwnTheBuffer = transferNativeArrayOwnership;
  131. m_SizeInBytes = sizeInBytes >= 0 ? sizeInBytes : buffer.Length;
  132. m_EventCount = eventCount;
  133. }
  134. /// <summary>
  135. /// Append a new event to the end of the buffer by copying the event from <paramref name="eventPtr"/>.
  136. /// </summary>
  137. /// <param name="eventPtr">Data of the event to store in the buffer. This will be copied in full as
  138. /// per <see cref="InputEvent.sizeInBytes"/> found in the event's header.</param>
  139. /// <param name="capacityIncrementInBytes">If the buffer needs to be reallocated to accommodate the event, number of
  140. /// bytes to grow the buffer by.</param>
  141. /// <param name="allocator">If the buffer needs to be reallocated to accommodate the event, the type of allocation to
  142. /// use.</param>
  143. /// <exception cref="ArgumentNullException"><paramref name="eventPtr"/> is <c>null</c>.</exception>
  144. /// <remarks>
  145. /// If the buffer's current capacity (see <see cref="capacityInBytes"/>) is smaller than <see cref="InputEvent.sizeInBytes"/>
  146. /// of the given event, the buffer will be reallocated.
  147. /// </remarks>
  148. public void AppendEvent(InputEvent* eventPtr, int capacityIncrementInBytes = 2048, Allocator allocator = Allocator.Persistent)
  149. {
  150. if (eventPtr == null)
  151. throw new ArgumentNullException(nameof(eventPtr));
  152. // Allocate space.
  153. var eventSizeInBytes = eventPtr->sizeInBytes;
  154. var destinationPtr = AllocateEvent((int)eventSizeInBytes, capacityIncrementInBytes, allocator);
  155. // Copy event.
  156. UnsafeUtility.MemCpy(destinationPtr, eventPtr, eventSizeInBytes);
  157. }
  158. /// <summary>
  159. /// Make space for an event of <paramref name="sizeInBytes"/> bytes and return a pointer to
  160. /// the memory for the event.
  161. /// </summary>
  162. /// <param name="sizeInBytes">Number of bytes to make available for the event including the event header (see <see cref="InputEvent"/>).</param>
  163. /// <param name="capacityIncrementInBytes">If the buffer needs to be reallocated to accommodate the event, number of
  164. /// bytes to grow the buffer by.</param>
  165. /// <param name="allocator">If the buffer needs to be reallocated to accommodate the event, the type of allocation to
  166. /// use.</param>
  167. /// <returns>A pointer to a block of memory in <see cref="bufferPtr"/>. Store the event data here.</returns>
  168. /// <exception cref="ArgumentException"><paramref name="sizeInBytes"/> is less than the size needed for the
  169. /// header of an <see cref="InputEvent"/>. Will automatically be aligned to a multiple of 4.</exception>
  170. /// <remarks>
  171. /// Only <see cref="InputEvent.sizeInBytes"/> is initialized by this method. No other fields from the event's
  172. /// header are touched.
  173. ///
  174. /// The event will be appended to the buffer after the last event currently in the buffer (if any).
  175. /// </remarks>
  176. public InputEvent* AllocateEvent(int sizeInBytes, int capacityIncrementInBytes = 2048, Allocator allocator = Allocator.Persistent)
  177. {
  178. if (sizeInBytes < InputEvent.kBaseEventSize)
  179. throw new ArgumentException(
  180. $"sizeInBytes must be >= sizeof(InputEvent) == {InputEvent.kBaseEventSize} (was {sizeInBytes})",
  181. nameof(sizeInBytes));
  182. var alignedSizeInBytes = sizeInBytes.AlignToMultipleOf(InputEvent.kAlignment);
  183. // See if we need to enlarge our buffer.
  184. var necessaryCapacity = m_SizeInBytes + alignedSizeInBytes;
  185. var currentCapacity = capacityInBytes;
  186. if (currentCapacity < necessaryCapacity)
  187. {
  188. // Yes, so reallocate.
  189. var newCapacity = necessaryCapacity.AlignToMultipleOf(capacityIncrementInBytes);
  190. if (newCapacity > int.MaxValue)
  191. throw new NotImplementedException("NativeArray long support");
  192. var newBuffer =
  193. new NativeArray<byte>((int)newCapacity, allocator, NativeArrayOptions.ClearMemory);
  194. if (m_Buffer.IsCreated)
  195. {
  196. UnsafeUtility.MemCpy(newBuffer.GetUnsafePtr(),
  197. NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer),
  198. this.sizeInBytes);
  199. if (m_WeOwnTheBuffer)
  200. m_Buffer.Dispose();
  201. }
  202. m_Buffer = newBuffer;
  203. m_WeOwnTheBuffer = true;
  204. }
  205. var eventPtr = (InputEvent*)((byte*)NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(m_Buffer) + m_SizeInBytes);
  206. eventPtr->sizeInBytes = (uint)sizeInBytes;
  207. m_SizeInBytes += alignedSizeInBytes;
  208. ++m_EventCount;
  209. return eventPtr;
  210. }
  211. /// <summary>
  212. /// Whether the given event pointer refers to data within the event buffer.
  213. /// </summary>
  214. /// <param name="eventPtr"></param>
  215. /// <returns></returns>
  216. /// <remarks>
  217. /// Note that this method does NOT check whether the given pointer points to an actual
  218. /// event in the buffer. It solely performs a pointer out-of-bounds check.
  219. ///
  220. /// Also note that if the size of the memory buffer is unknown (<see cref="BufferSizeUnknown"/>,
  221. /// only a lower-bounds check is performed.
  222. /// </remarks>
  223. public bool Contains(InputEvent* eventPtr)
  224. {
  225. if (eventPtr == null)
  226. return false;
  227. if (sizeInBytes == 0)
  228. return false;
  229. var bufferPtr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(data);
  230. if (eventPtr < bufferPtr)
  231. return false;
  232. if (sizeInBytes != BufferSizeUnknown && eventPtr >= (byte*)bufferPtr + sizeInBytes)
  233. return false;
  234. return true;
  235. }
  236. public void Reset()
  237. {
  238. m_EventCount = 0;
  239. if (m_SizeInBytes != BufferSizeUnknown)
  240. m_SizeInBytes = 0;
  241. }
  242. /// <summary>
  243. /// Advance the read position to the next event in the buffer, preserving or not preserving the
  244. /// current event depending on <paramref name="leaveEventInBuffer"/>.
  245. /// </summary>
  246. /// <param name="currentReadPos"></param>
  247. /// <param name="currentWritePos"></param>
  248. /// <param name="numEventsRetainedInBuffer"></param>
  249. /// <param name="numRemainingEvents"></param>
  250. /// <param name="leaveEventInBuffer"></param>
  251. /// <remarks>
  252. /// This method MUST ONLY BE CALLED if the current event has been fully processed. If the at <paramref name="currentWritePos"/>
  253. /// is smaller than the current event, then this method will OVERWRITE parts or all of the current event.
  254. /// </remarks>
  255. internal void AdvanceToNextEvent(ref InputEvent* currentReadPos,
  256. ref InputEvent* currentWritePos, ref int numEventsRetainedInBuffer,
  257. ref int numRemainingEvents, bool leaveEventInBuffer)
  258. {
  259. Debug.Assert(currentReadPos >= currentWritePos, "Current write position is beyond read position");
  260. // Get new read position *before* potentially moving the current event so that we don't
  261. // end up overwriting the data we need to find the next event in memory.
  262. var newReadPos = currentReadPos;
  263. if (numRemainingEvents > 1)
  264. {
  265. // Don't perform safety check in non-debug builds.
  266. #if UNITY_EDITOR || DEVELOPMENT_BUILD
  267. newReadPos = InputEvent.GetNextInMemoryChecked(currentReadPos, ref this);
  268. #else
  269. newReadPos = InputEvent.GetNextInMemory(currentReadPos);
  270. #endif
  271. }
  272. // If the current event should be left in the buffer, advance write position.
  273. if (leaveEventInBuffer)
  274. {
  275. Debug.Assert(Contains(currentWritePos), "Current write position should be contained in buffer");
  276. // Move down in buffer if read and write pos have deviated from each other.
  277. var numBytes = currentReadPos->sizeInBytes;
  278. if (currentReadPos != currentWritePos)
  279. UnsafeUtility.MemMove(currentWritePos, currentReadPos, numBytes);
  280. currentWritePos = (InputEvent*)((byte*)currentWritePos + numBytes.AlignToMultipleOf(4));
  281. ++numEventsRetainedInBuffer;
  282. }
  283. currentReadPos = newReadPos;
  284. --numRemainingEvents;
  285. }
  286. public IEnumerator<InputEventPtr> GetEnumerator()
  287. {
  288. return new Enumerator(this);
  289. }
  290. IEnumerator IEnumerable.GetEnumerator()
  291. {
  292. return GetEnumerator();
  293. }
  294. public void Dispose()
  295. {
  296. // Nothing to do if we don't actually own the memory.
  297. if (!m_WeOwnTheBuffer)
  298. return;
  299. Debug.Assert(m_Buffer.IsCreated, "Buffer has not been created");
  300. m_Buffer.Dispose();
  301. m_WeOwnTheBuffer = false;
  302. m_SizeInBytes = 0;
  303. m_EventCount = 0;
  304. }
  305. public InputEventBuffer Clone()
  306. {
  307. var clone = new InputEventBuffer();
  308. if (m_Buffer.IsCreated)
  309. {
  310. clone.m_Buffer = new NativeArray<byte>(m_Buffer.Length, Allocator.Persistent);
  311. clone.m_Buffer.CopyFrom(m_Buffer);
  312. clone.m_WeOwnTheBuffer = true;
  313. }
  314. clone.m_SizeInBytes = m_SizeInBytes;
  315. clone.m_EventCount = m_EventCount;
  316. return clone;
  317. }
  318. object ICloneable.Clone()
  319. {
  320. return Clone();
  321. }
  322. private NativeArray<byte> m_Buffer;
  323. private long m_SizeInBytes;
  324. private int m_EventCount;
  325. private bool m_WeOwnTheBuffer; ////FIXME: what we really want is access to NativeArray's allocator label
  326. private struct Enumerator : IEnumerator<InputEventPtr>
  327. {
  328. private readonly InputEvent* m_Buffer;
  329. private readonly int m_EventCount;
  330. private InputEvent* m_CurrentEvent;
  331. private int m_CurrentIndex;
  332. public Enumerator(InputEventBuffer buffer)
  333. {
  334. m_Buffer = buffer.bufferPtr;
  335. m_EventCount = buffer.m_EventCount;
  336. m_CurrentEvent = null;
  337. m_CurrentIndex = 0;
  338. }
  339. public bool MoveNext()
  340. {
  341. if (m_CurrentIndex == m_EventCount)
  342. return false;
  343. if (m_CurrentEvent == null)
  344. {
  345. m_CurrentEvent = m_Buffer;
  346. return m_CurrentEvent != null;
  347. }
  348. Debug.Assert(m_CurrentEvent != null, "Current event must not be null");
  349. ++m_CurrentIndex;
  350. if (m_CurrentIndex == m_EventCount)
  351. return false;
  352. m_CurrentEvent = InputEvent.GetNextInMemory(m_CurrentEvent);
  353. return true;
  354. }
  355. public void Reset()
  356. {
  357. m_CurrentEvent = null;
  358. m_CurrentIndex = 0;
  359. }
  360. public void Dispose()
  361. {
  362. }
  363. public InputEventPtr Current => m_CurrentEvent;
  364. object IEnumerator.Current => Current;
  365. }
  366. }
  367. }