BufferManager.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.State;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Memory.Range;
  6. using System;
  7. using System.Collections.ObjectModel;
  8. using System.Linq;
  9. namespace Ryujinx.Graphics.Gpu.Memory
  10. {
  11. /// <summary>
  12. /// Buffer manager.
  13. /// </summary>
  14. class BufferManager
  15. {
  16. private const int StackToHeapThreshold = 16;
  17. private const int OverlapsBufferInitialCapacity = 10;
  18. private const int OverlapsBufferMaxCapacity = 10000;
  19. private const ulong BufferAlignmentSize = 0x1000;
  20. private const ulong BufferAlignmentMask = BufferAlignmentSize - 1;
  21. private GpuContext _context;
  22. private RangeList<Buffer> _buffers;
  23. private Buffer[] _bufferOverlaps;
  24. private IndexBuffer _indexBuffer;
  25. private VertexBuffer[] _vertexBuffers;
  26. private BufferBounds[] _transformFeedbackBuffers;
  27. /// <summary>
  28. /// Holds shader stage buffer state and binding information.
  29. /// </summary>
  30. private class BuffersPerStage
  31. {
  32. /// <summary>
  33. /// Shader buffer binding information.
  34. /// </summary>
  35. public BufferDescriptor[] Bindings { get; }
  36. /// <summary>
  37. /// Buffer regions.
  38. /// </summary>
  39. public BufferBounds[] Buffers { get; }
  40. /// <summary>
  41. /// Total amount of buffers used on the shader.
  42. /// </summary>
  43. public int Count { get; private set; }
  44. /// <summary>
  45. /// Creates a new instance of the shader stage buffer information.
  46. /// </summary>
  47. /// <param name="count">Maximum amount of buffers that the shader stage can use</param>
  48. public BuffersPerStage(int count)
  49. {
  50. Bindings = new BufferDescriptor[count];
  51. Buffers = new BufferBounds[count];
  52. }
  53. /// <summary>
  54. /// Sets the region of a buffer at a given slot.
  55. /// </summary>
  56. /// <param name="index">Buffer slot</param>
  57. /// <param name="address">Region virtual address</param>
  58. /// <param name="size">Region size in bytes</param>
  59. /// <param name="flags">Buffer usage flags</param>
  60. public void SetBounds(int index, ulong address, ulong size, BufferUsageFlags flags = BufferUsageFlags.None)
  61. {
  62. Buffers[index] = new BufferBounds(address, size, flags);
  63. }
  64. /// <summary>
  65. /// Sets shader buffer binding information.
  66. /// </summary>
  67. /// <param name="descriptors">Buffer binding information</param>
  68. public void SetBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  69. {
  70. if (descriptors == null)
  71. {
  72. Count = 0;
  73. return;
  74. }
  75. descriptors.CopyTo(Bindings, 0);
  76. Count = descriptors.Count;
  77. }
  78. }
  79. private BuffersPerStage _cpStorageBuffers;
  80. private BuffersPerStage _cpUniformBuffers;
  81. private BuffersPerStage[] _gpStorageBuffers;
  82. private BuffersPerStage[] _gpUniformBuffers;
  83. private int _cpStorageBufferBindings;
  84. private int _cpUniformBufferBindings;
  85. private int _gpStorageBufferBindings;
  86. private int _gpUniformBufferBindings;
  87. private bool _gpStorageBuffersDirty;
  88. private bool _gpUniformBuffersDirty;
  89. private bool _indexBufferDirty;
  90. private bool _vertexBuffersDirty;
  91. private uint _vertexBuffersEnableMask;
  92. private bool _transformFeedbackBuffersDirty;
  93. private bool _rebind;
  94. /// <summary>
  95. /// Creates a new instance of the buffer manager.
  96. /// </summary>
  97. /// <param name="context">The GPU context that the buffer manager belongs to</param>
  98. public BufferManager(GpuContext context)
  99. {
  100. _context = context;
  101. _buffers = new RangeList<Buffer>();
  102. _bufferOverlaps = new Buffer[OverlapsBufferInitialCapacity];
  103. _vertexBuffers = new VertexBuffer[Constants.TotalVertexBuffers];
  104. _transformFeedbackBuffers = new BufferBounds[Constants.TotalTransformFeedbackBuffers];
  105. _cpStorageBuffers = new BuffersPerStage(Constants.TotalCpStorageBuffers);
  106. _cpUniformBuffers = new BuffersPerStage(Constants.TotalCpUniformBuffers);
  107. _gpStorageBuffers = new BuffersPerStage[Constants.ShaderStages];
  108. _gpUniformBuffers = new BuffersPerStage[Constants.ShaderStages];
  109. for (int index = 0; index < Constants.ShaderStages; index++)
  110. {
  111. _gpStorageBuffers[index] = new BuffersPerStage(Constants.TotalGpStorageBuffers);
  112. _gpUniformBuffers[index] = new BuffersPerStage(Constants.TotalGpUniformBuffers);
  113. }
  114. }
  115. /// <summary>
  116. /// Sets the memory range with the index buffer data, to be used for subsequent draw calls.
  117. /// </summary>
  118. /// <param name="gpuVa">Start GPU virtual address of the index buffer</param>
  119. /// <param name="size">Size, in bytes, of the index buffer</param>
  120. /// <param name="type">Type of each index buffer element</param>
  121. public void SetIndexBuffer(ulong gpuVa, ulong size, IndexType type)
  122. {
  123. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  124. _indexBuffer.Address = address;
  125. _indexBuffer.Size = size;
  126. _indexBuffer.Type = type;
  127. _indexBufferDirty = true;
  128. }
  129. /// <summary>
  130. /// Sets a new index buffer that overrides the one set on the call to <see cref="CommitGraphicsBindings"/>.
  131. /// </summary>
  132. /// <param name="buffer">Buffer to be used as index buffer</param>
  133. /// <param name="type">Type of each index buffer element</param>
  134. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  135. {
  136. _context.Renderer.Pipeline.SetIndexBuffer(buffer, type);
  137. _indexBufferDirty = true;
  138. }
  139. /// <summary>
  140. /// Sets the memory range with vertex buffer data, to be used for subsequent draw calls.
  141. /// </summary>
  142. /// <param name="index">Index of the vertex buffer (up to 16)</param>
  143. /// <param name="gpuVa">GPU virtual address of the buffer</param>
  144. /// <param name="size">Size in bytes of the buffer</param>
  145. /// <param name="stride">Stride of the buffer, defined as the number of bytes of each vertex</param>
  146. /// <param name="divisor">Vertex divisor of the buffer, for instanced draws</param>
  147. public void SetVertexBuffer(int index, ulong gpuVa, ulong size, int stride, int divisor)
  148. {
  149. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  150. _vertexBuffers[index].Address = address;
  151. _vertexBuffers[index].Size = size;
  152. _vertexBuffers[index].Stride = stride;
  153. _vertexBuffers[index].Divisor = divisor;
  154. _vertexBuffersDirty = true;
  155. if (address != 0)
  156. {
  157. _vertexBuffersEnableMask |= 1u << index;
  158. }
  159. else
  160. {
  161. _vertexBuffersEnableMask &= ~(1u << index);
  162. }
  163. }
  164. /// <summary>
  165. /// Sets a transform feedback buffer on the graphics pipeline.
  166. /// The output from the vertex transformation stages are written into the feedback buffer.
  167. /// </summary>
  168. /// <param name="index">Index of the transform feedback buffer</param>
  169. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  170. /// <param name="size">Size in bytes of the transform feedback buffer</param>
  171. public void SetTransformFeedbackBuffer(int index, ulong gpuVa, ulong size)
  172. {
  173. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  174. _transformFeedbackBuffers[index] = new BufferBounds(address, size);
  175. _transformFeedbackBuffersDirty = true;
  176. }
  177. /// <summary>
  178. /// Sets a storage buffer on the compute pipeline.
  179. /// Storage buffers can be read and written to on shaders.
  180. /// </summary>
  181. /// <param name="index">Index of the storage buffer</param>
  182. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  183. /// <param name="size">Size in bytes of the storage buffer</param>
  184. /// <param name="flags">Buffer usage flags</param>
  185. public void SetComputeStorageBuffer(int index, ulong gpuVa, ulong size, BufferUsageFlags flags)
  186. {
  187. size += gpuVa & ((ulong)_context.Capabilities.StorageBufferOffsetAlignment - 1);
  188. gpuVa = BitUtils.AlignDown(gpuVa, _context.Capabilities.StorageBufferOffsetAlignment);
  189. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  190. _cpStorageBuffers.SetBounds(index, address, size, flags);
  191. }
  192. /// <summary>
  193. /// Sets a storage buffer on the graphics pipeline.
  194. /// Storage buffers can be read and written to on shaders.
  195. /// </summary>
  196. /// <param name="stage">Index of the shader stage</param>
  197. /// <param name="index">Index of the storage buffer</param>
  198. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  199. /// <param name="size">Size in bytes of the storage buffer</param>
  200. /// <param name="flags">Buffer usage flags</param>
  201. public void SetGraphicsStorageBuffer(int stage, int index, ulong gpuVa, ulong size, BufferUsageFlags flags)
  202. {
  203. size += gpuVa & ((ulong)_context.Capabilities.StorageBufferOffsetAlignment - 1);
  204. gpuVa = BitUtils.AlignDown(gpuVa, _context.Capabilities.StorageBufferOffsetAlignment);
  205. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  206. if (_gpStorageBuffers[stage].Buffers[index].Address != address ||
  207. _gpStorageBuffers[stage].Buffers[index].Size != size)
  208. {
  209. _gpStorageBuffersDirty = true;
  210. }
  211. _gpStorageBuffers[stage].SetBounds(index, address, size, flags);
  212. }
  213. /// <summary>
  214. /// Sets a uniform buffer on the compute pipeline.
  215. /// Uniform buffers are read-only from shaders, and have a small capacity.
  216. /// </summary>
  217. /// <param name="index">Index of the uniform buffer</param>
  218. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  219. /// <param name="size">Size in bytes of the storage buffer</param>
  220. public void SetComputeUniformBuffer(int index, ulong gpuVa, ulong size)
  221. {
  222. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  223. _cpUniformBuffers.SetBounds(index, address, size);
  224. }
  225. /// <summary>
  226. /// Sets a uniform buffer on the graphics pipeline.
  227. /// Uniform buffers are read-only from shaders, and have a small capacity.
  228. /// </summary>
  229. /// <param name="stage">Index of the shader stage</param>
  230. /// <param name="index">Index of the uniform buffer</param>
  231. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  232. /// <param name="size">Size in bytes of the storage buffer</param>
  233. public void SetGraphicsUniformBuffer(int stage, int index, ulong gpuVa, ulong size)
  234. {
  235. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  236. _gpUniformBuffers[stage].SetBounds(index, address, size);
  237. _gpUniformBuffersDirty = true;
  238. }
  239. /// <summary>
  240. /// Sets the binding points for the storage buffers bound on the compute pipeline.
  241. /// </summary>
  242. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  243. public void SetComputeStorageBufferBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  244. {
  245. _cpStorageBuffers.SetBindings(descriptors);
  246. _cpStorageBufferBindings = descriptors.Count != 0 ? descriptors.Max(x => x.Binding) + 1 : 0;
  247. }
  248. /// <summary>
  249. /// Sets the binding points for the storage buffers bound on the graphics pipeline.
  250. /// </summary>
  251. /// <param name="stage">Index of the shader stage</param>
  252. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  253. public void SetGraphicsStorageBufferBindings(int stage, ReadOnlyCollection<BufferDescriptor> descriptors)
  254. {
  255. _gpStorageBuffers[stage].SetBindings(descriptors);
  256. _gpStorageBuffersDirty = true;
  257. }
  258. /// <summary>
  259. /// Sets the total number of storage buffer bindings used.
  260. /// </summary>
  261. /// <param name="count">Number of storage buffer bindings used</param>
  262. public void SetGraphicsStorageBufferBindingsCount(int count)
  263. {
  264. _gpStorageBufferBindings = count;
  265. }
  266. /// <summary>
  267. /// Sets the binding points for the uniform buffers bound on the compute pipeline.
  268. /// </summary>
  269. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  270. public void SetComputeUniformBufferBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  271. {
  272. _cpUniformBuffers.SetBindings(descriptors);
  273. _cpUniformBufferBindings = descriptors.Count != 0 ? descriptors.Max(x => x.Binding) + 1 : 0;
  274. }
  275. /// <summary>
  276. /// Sets the enabled uniform buffers mask on the graphics pipeline.
  277. /// Each bit set on the mask indicates that the respective buffer index is enabled.
  278. /// </summary>
  279. /// <param name="stage">Index of the shader stage</param>
  280. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  281. public void SetGraphicsUniformBufferBindings(int stage, ReadOnlyCollection<BufferDescriptor> descriptors)
  282. {
  283. _gpUniformBuffers[stage].SetBindings(descriptors);
  284. _gpUniformBuffersDirty = true;
  285. }
  286. /// <summary>
  287. /// Sets the total number of uniform buffer bindings used.
  288. /// </summary>
  289. /// <param name="count">Number of uniform buffer bindings used</param>
  290. public void SetGraphicsUniformBufferBindingsCount(int count)
  291. {
  292. _gpUniformBufferBindings = count;
  293. }
  294. /// <summary>
  295. /// Gets a bit mask indicating which compute uniform buffers are currently bound.
  296. /// </summary>
  297. /// <returns>Mask where each bit set indicates a bound constant buffer</returns>
  298. public uint GetComputeUniformBufferUseMask()
  299. {
  300. uint mask = 0;
  301. for (int i = 0; i < _cpUniformBuffers.Buffers.Length; i++)
  302. {
  303. if (_cpUniformBuffers.Buffers[i].Address != 0)
  304. {
  305. mask |= 1u << i;
  306. }
  307. }
  308. return mask;
  309. }
  310. /// <summary>
  311. /// Gets a bit mask indicating which graphics uniform buffers are currently bound.
  312. /// </summary>
  313. /// <param name="stage">Index of the shader stage</param>
  314. /// <returns>Mask where each bit set indicates a bound constant buffer</returns>
  315. public uint GetGraphicsUniformBufferUseMask(int stage)
  316. {
  317. uint mask = 0;
  318. for (int i = 0; i < _gpUniformBuffers[stage].Buffers.Length; i++)
  319. {
  320. if (_gpUniformBuffers[stage].Buffers[i].Address != 0)
  321. {
  322. mask |= 1u << i;
  323. }
  324. }
  325. return mask;
  326. }
  327. /// <summary>
  328. /// Handles removal of buffers written to a memory region being unmapped.
  329. /// </summary>
  330. /// <param name="sender">Sender object</param>
  331. /// <param name="e">Event arguments</param>
  332. public void MemoryUnmappedHandler(object sender, UnmapEventArgs e)
  333. {
  334. Buffer[] overlaps = new Buffer[10];
  335. int overlapCount;
  336. ulong address = _context.MemoryManager.Translate(e.Address);
  337. ulong size = e.Size;
  338. lock (_buffers)
  339. {
  340. overlapCount = _buffers.FindOverlaps(address, size, ref overlaps);
  341. }
  342. for (int i = 0; i < overlapCount; i++)
  343. {
  344. overlaps[i].Unmapped(address, size);
  345. }
  346. }
  347. /// <summary>
  348. /// Performs address translation of the GPU virtual address, and creates a
  349. /// new buffer, if needed, for the specified range.
  350. /// </summary>
  351. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  352. /// <param name="size">Size in bytes of the buffer</param>
  353. /// <returns>CPU virtual address of the buffer, after address translation</returns>
  354. private ulong TranslateAndCreateBuffer(ulong gpuVa, ulong size)
  355. {
  356. if (gpuVa == 0)
  357. {
  358. return 0;
  359. }
  360. ulong address = _context.MemoryManager.Translate(gpuVa);
  361. if (address == MemoryManager.PteUnmapped)
  362. {
  363. return 0;
  364. }
  365. CreateBuffer(address, size);
  366. return address;
  367. }
  368. /// <summary>
  369. /// Creates a new buffer for the specified range, if it does not yet exist.
  370. /// This can be used to ensure the existance of a buffer.
  371. /// </summary>
  372. /// <param name="address">Address of the buffer in memory</param>
  373. /// <param name="size">Size of the buffer in bytes</param>
  374. public void CreateBuffer(ulong address, ulong size)
  375. {
  376. ulong endAddress = address + size;
  377. ulong alignedAddress = address & ~BufferAlignmentMask;
  378. ulong alignedEndAddress = (endAddress + BufferAlignmentMask) & ~BufferAlignmentMask;
  379. // The buffer must have the size of at least one page.
  380. if (alignedEndAddress == alignedAddress)
  381. {
  382. alignedEndAddress += BufferAlignmentSize;
  383. }
  384. CreateBufferAligned(alignedAddress, alignedEndAddress - alignedAddress);
  385. }
  386. /// <summary>
  387. /// Creates a new buffer for the specified range, if needed.
  388. /// If a buffer where this range can be fully contained already exists,
  389. /// then the creation of a new buffer is not necessary.
  390. /// </summary>
  391. /// <param name="address">Address of the buffer in guest memory</param>
  392. /// <param name="size">Size in bytes of the buffer</param>
  393. private void CreateBufferAligned(ulong address, ulong size)
  394. {
  395. int overlapsCount;
  396. lock (_buffers)
  397. {
  398. overlapsCount = _buffers.FindOverlapsNonOverlapping(address, size, ref _bufferOverlaps);
  399. }
  400. if (overlapsCount != 0)
  401. {
  402. // The buffer already exists. We can just return the existing buffer
  403. // if the buffer we need is fully contained inside the overlapping buffer.
  404. // Otherwise, we must delete the overlapping buffers and create a bigger buffer
  405. // that fits all the data we need. We also need to copy the contents from the
  406. // old buffer(s) to the new buffer.
  407. ulong endAddress = address + size;
  408. if (_bufferOverlaps[0].Address > address || _bufferOverlaps[0].EndAddress < endAddress)
  409. {
  410. for (int index = 0; index < overlapsCount; index++)
  411. {
  412. Buffer buffer = _bufferOverlaps[index];
  413. address = Math.Min(address, buffer.Address);
  414. endAddress = Math.Max(endAddress, buffer.EndAddress);
  415. lock (_buffers)
  416. {
  417. _buffers.Remove(buffer);
  418. }
  419. }
  420. Buffer newBuffer = new Buffer(_context, address, endAddress - address);
  421. newBuffer.SynchronizeMemory(address, endAddress - address);
  422. lock (_buffers)
  423. {
  424. _buffers.Add(newBuffer);
  425. }
  426. for (int index = 0; index < overlapsCount; index++)
  427. {
  428. Buffer buffer = _bufferOverlaps[index];
  429. int dstOffset = (int)(buffer.Address - newBuffer.Address);
  430. buffer.SynchronizeMemory(buffer.Address, buffer.Size);
  431. buffer.CopyTo(newBuffer, dstOffset);
  432. newBuffer.InheritModifiedRanges(buffer);
  433. buffer.Dispose();
  434. }
  435. // Existing buffers were modified, we need to rebind everything.
  436. _rebind = true;
  437. }
  438. }
  439. else
  440. {
  441. // No overlap, just create a new buffer.
  442. Buffer buffer = new Buffer(_context, address, size);
  443. lock (_buffers)
  444. {
  445. _buffers.Add(buffer);
  446. }
  447. }
  448. ShrinkOverlapsBufferIfNeeded();
  449. }
  450. /// <summary>
  451. /// Resizes the temporary buffer used for range list intersection results, if it has grown too much.
  452. /// </summary>
  453. private void ShrinkOverlapsBufferIfNeeded()
  454. {
  455. if (_bufferOverlaps.Length > OverlapsBufferMaxCapacity)
  456. {
  457. Array.Resize(ref _bufferOverlaps, OverlapsBufferMaxCapacity);
  458. }
  459. }
  460. /// <summary>
  461. /// Gets the address of the compute uniform buffer currently bound at the given index.
  462. /// </summary>
  463. /// <param name="index">Index of the uniform buffer binding</param>
  464. /// <returns>The uniform buffer address, or an undefined value if the buffer is not currently bound</returns>
  465. public ulong GetComputeUniformBufferAddress(int index)
  466. {
  467. return _cpUniformBuffers.Buffers[index].Address;
  468. }
  469. /// <summary>
  470. /// Gets the address of the graphics uniform buffer currently bound at the given index.
  471. /// </summary>
  472. /// <param name="stage">Index of the shader stage</param>
  473. /// <param name="index">Index of the uniform buffer binding</param>
  474. /// <returns>The uniform buffer address, or an undefined value if the buffer is not currently bound</returns>
  475. public ulong GetGraphicsUniformBufferAddress(int stage, int index)
  476. {
  477. return _gpUniformBuffers[stage].Buffers[index].Address;
  478. }
  479. /// <summary>
  480. /// Ensures that the compute engine bindings are visible to the host GPU.
  481. /// Note: this actually performs the binding using the host graphics API.
  482. /// </summary>
  483. public void CommitComputeBindings()
  484. {
  485. int sCount = _cpStorageBufferBindings;
  486. Span<BufferRange> sRanges = sCount < StackToHeapThreshold ? stackalloc BufferRange[sCount] : new BufferRange[sCount];
  487. for (int index = 0; index < _cpStorageBuffers.Count; index++)
  488. {
  489. ref var bindingInfo = ref _cpStorageBuffers.Bindings[index];
  490. BufferBounds bounds = _cpStorageBuffers.Buffers[bindingInfo.Slot];
  491. if (bounds.Address != 0)
  492. {
  493. sRanges[bindingInfo.Binding] = GetBufferRange(bounds.Address, bounds.Size, bounds.Flags.HasFlag(BufferUsageFlags.Write));
  494. }
  495. }
  496. _context.Renderer.Pipeline.SetStorageBuffers(sRanges);
  497. int uCount = _cpUniformBufferBindings;
  498. Span<BufferRange> uRanges = uCount < StackToHeapThreshold ? stackalloc BufferRange[uCount] : new BufferRange[uCount];
  499. for (int index = 0; index < _cpUniformBuffers.Count; index++)
  500. {
  501. ref var bindingInfo = ref _cpUniformBuffers.Bindings[index];
  502. BufferBounds bounds = _cpUniformBuffers.Buffers[bindingInfo.Slot];
  503. if (bounds.Address != 0)
  504. {
  505. uRanges[bindingInfo.Binding] = GetBufferRange(bounds.Address, bounds.Size);
  506. }
  507. }
  508. _context.Renderer.Pipeline.SetUniformBuffers(uRanges);
  509. // Force rebind after doing compute work.
  510. _rebind = true;
  511. }
  512. /// <summary>
  513. /// Ensures that the graphics engine bindings are visible to the host GPU.
  514. /// Note: this actually performs the binding using the host graphics API.
  515. /// </summary>
  516. public void CommitGraphicsBindings()
  517. {
  518. if (_indexBufferDirty || _rebind)
  519. {
  520. _indexBufferDirty = false;
  521. if (_indexBuffer.Address != 0)
  522. {
  523. BufferRange buffer = GetBufferRange(_indexBuffer.Address, _indexBuffer.Size);
  524. _context.Renderer.Pipeline.SetIndexBuffer(buffer, _indexBuffer.Type);
  525. }
  526. }
  527. else if (_indexBuffer.Address != 0)
  528. {
  529. SynchronizeBufferRange(_indexBuffer.Address, _indexBuffer.Size);
  530. }
  531. uint vbEnableMask = _vertexBuffersEnableMask;
  532. if (_vertexBuffersDirty || _rebind)
  533. {
  534. _vertexBuffersDirty = false;
  535. Span<VertexBufferDescriptor> vertexBuffers = stackalloc VertexBufferDescriptor[Constants.TotalVertexBuffers];
  536. for (int index = 0; (vbEnableMask >> index) != 0; index++)
  537. {
  538. VertexBuffer vb = _vertexBuffers[index];
  539. if (vb.Address == 0)
  540. {
  541. continue;
  542. }
  543. BufferRange buffer = GetBufferRange(vb.Address, vb.Size);
  544. vertexBuffers[index] = new VertexBufferDescriptor(buffer, vb.Stride, vb.Divisor);
  545. }
  546. _context.Renderer.Pipeline.SetVertexBuffers(vertexBuffers);
  547. }
  548. else
  549. {
  550. for (int index = 0; (vbEnableMask >> index) != 0; index++)
  551. {
  552. VertexBuffer vb = _vertexBuffers[index];
  553. if (vb.Address == 0)
  554. {
  555. continue;
  556. }
  557. SynchronizeBufferRange(vb.Address, vb.Size);
  558. }
  559. }
  560. if (_transformFeedbackBuffersDirty || _rebind)
  561. {
  562. _transformFeedbackBuffersDirty = false;
  563. Span<BufferRange> tfbs = stackalloc BufferRange[Constants.TotalTransformFeedbackBuffers];
  564. for (int index = 0; index < Constants.TotalTransformFeedbackBuffers; index++)
  565. {
  566. BufferBounds tfb = _transformFeedbackBuffers[index];
  567. if (tfb.Address == 0)
  568. {
  569. tfbs[index] = BufferRange.Empty;
  570. continue;
  571. }
  572. tfbs[index] = GetBufferRange(tfb.Address, tfb.Size);
  573. }
  574. _context.Renderer.Pipeline.SetTransformFeedbackBuffers(tfbs);
  575. }
  576. else
  577. {
  578. for (int index = 0; index < Constants.TotalTransformFeedbackBuffers; index++)
  579. {
  580. BufferBounds tfb = _transformFeedbackBuffers[index];
  581. if (tfb.Address == 0)
  582. {
  583. continue;
  584. }
  585. SynchronizeBufferRange(tfb.Address, tfb.Size);
  586. }
  587. }
  588. if (_gpStorageBuffersDirty || _rebind)
  589. {
  590. _gpStorageBuffersDirty = false;
  591. BindBuffers(_gpStorageBuffers, isStorage: true);
  592. }
  593. else
  594. {
  595. UpdateBuffers(_gpStorageBuffers);
  596. }
  597. if (_gpUniformBuffersDirty || _rebind)
  598. {
  599. _gpUniformBuffersDirty = false;
  600. BindBuffers(_gpUniformBuffers, isStorage: false);
  601. }
  602. else
  603. {
  604. UpdateBuffers(_gpUniformBuffers);
  605. }
  606. _rebind = false;
  607. }
  608. /// <summary>
  609. /// Bind respective buffer bindings on the host API.
  610. /// </summary>
  611. /// <param name="bindings">Bindings to bind</param>
  612. /// <param name="isStorage">True to bind as storage buffer, false to bind as uniform buffers</param>
  613. private void BindBuffers(BuffersPerStage[] bindings, bool isStorage)
  614. {
  615. int count = isStorage ? _gpStorageBufferBindings : _gpUniformBufferBindings;
  616. Span<BufferRange> ranges = count < StackToHeapThreshold ? stackalloc BufferRange[count] : new BufferRange[count];
  617. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  618. {
  619. ref var buffers = ref bindings[(int)stage - 1];
  620. for (int index = 0; index < buffers.Count; index++)
  621. {
  622. ref var bindingInfo = ref buffers.Bindings[index];
  623. BufferBounds bounds = buffers.Buffers[bindingInfo.Slot];
  624. if (bounds.Address != 0)
  625. {
  626. ranges[bindingInfo.Binding] = GetBufferRange(bounds.Address, bounds.Size, bounds.Flags.HasFlag(BufferUsageFlags.Write));
  627. }
  628. }
  629. }
  630. if (isStorage)
  631. {
  632. _context.Renderer.Pipeline.SetStorageBuffers(ranges);
  633. }
  634. else
  635. {
  636. _context.Renderer.Pipeline.SetUniformBuffers(ranges);
  637. }
  638. }
  639. /// <summary>
  640. /// Updates data for the already bound buffer bindings.
  641. /// </summary>
  642. /// <param name="bindings">Bindings to update</param>
  643. private void UpdateBuffers(BuffersPerStage[] bindings)
  644. {
  645. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  646. {
  647. ref var buffers = ref bindings[(int)stage - 1];
  648. for (int index = 0; index < buffers.Count; index++)
  649. {
  650. ref var binding = ref buffers.Bindings[index];
  651. BufferBounds bounds = buffers.Buffers[binding.Slot];
  652. if (bounds.Address == 0)
  653. {
  654. continue;
  655. }
  656. SynchronizeBufferRange(bounds.Address, bounds.Size);
  657. }
  658. }
  659. }
  660. /// <summary>
  661. /// Sets the buffer storage of a buffer texture.
  662. /// </summary>
  663. /// <param name="texture">Buffer texture</param>
  664. /// <param name="address">Address of the buffer in memory</param>
  665. /// <param name="size">Size of the buffer in bytes</param>
  666. /// <param name="compute">Indicates if the buffer texture belongs to the compute or graphics pipeline</param>
  667. public void SetBufferTextureStorage(ITexture texture, ulong address, ulong size, bool compute)
  668. {
  669. CreateBuffer(address, size);
  670. if (_rebind)
  671. {
  672. // We probably had to modify existing buffers to create the texture buffer,
  673. // so rebind everything to ensure we're using the new buffers for all bound resources.
  674. if (compute)
  675. {
  676. CommitComputeBindings();
  677. }
  678. else
  679. {
  680. CommitGraphicsBindings();
  681. }
  682. }
  683. texture.SetStorage(GetBufferRange(address, size));
  684. }
  685. /// <summary>
  686. /// Copy a buffer data from a given address to another.
  687. /// </summary>
  688. /// <remarks>
  689. /// This does a GPU side copy.
  690. /// </remarks>
  691. /// <param name="srcVa">GPU virtual address of the copy source</param>
  692. /// <param name="dstVa">GPU virtual address of the copy destination</param>
  693. /// <param name="size">Size in bytes of the copy</param>
  694. public void CopyBuffer(GpuVa srcVa, GpuVa dstVa, ulong size)
  695. {
  696. ulong srcAddress = TranslateAndCreateBuffer(srcVa.Pack(), size);
  697. ulong dstAddress = TranslateAndCreateBuffer(dstVa.Pack(), size);
  698. Buffer srcBuffer = GetBuffer(srcAddress, size);
  699. Buffer dstBuffer = GetBuffer(dstAddress, size);
  700. int srcOffset = (int)(srcAddress - srcBuffer.Address);
  701. int dstOffset = (int)(dstAddress - dstBuffer.Address);
  702. _context.Renderer.Pipeline.CopyBuffer(
  703. srcBuffer.Handle,
  704. dstBuffer.Handle,
  705. srcOffset,
  706. dstOffset,
  707. (int)size);
  708. if (srcBuffer.IsModified(srcAddress, size))
  709. {
  710. dstBuffer.SignalModified(dstAddress, size);
  711. }
  712. else
  713. {
  714. // Optimization: If the data being copied is already in memory, then copy it directly instead of flushing from GPU.
  715. dstBuffer.ClearModified(dstAddress, size);
  716. _context.PhysicalMemory.WriteUntracked(dstAddress, _context.PhysicalMemory.GetSpan(srcAddress, (int)size));
  717. }
  718. }
  719. /// <summary>
  720. /// Clears a buffer at a given address with the specified value.
  721. /// </summary>
  722. /// <remarks>
  723. /// Both the address and size must be aligned to 4 bytes.
  724. /// </remarks>
  725. /// <param name="gpuVa">GPU virtual address of the region to clear</param>
  726. /// <param name="size">Number of bytes to clear</param>
  727. /// <param name="value">Value to be written into the buffer</param>
  728. public void ClearBuffer(GpuVa gpuVa, ulong size, uint value)
  729. {
  730. ulong address = TranslateAndCreateBuffer(gpuVa.Pack(), size);
  731. Buffer buffer = GetBuffer(address, size);
  732. int offset = (int)(address - buffer.Address);
  733. _context.Renderer.Pipeline.ClearBuffer(buffer.Handle, offset, (int)size, value);
  734. buffer.SignalModified(address, size);
  735. }
  736. /// <summary>
  737. /// Gets a buffer sub-range for a given memory range.
  738. /// </summary>
  739. /// <param name="address">Start address of the memory range</param>
  740. /// <param name="size">Size in bytes of the memory range</param>
  741. /// <param name="write">Whether the buffer will be written to by this use</param>
  742. /// <returns>The buffer sub-range for the given range</returns>
  743. private BufferRange GetBufferRange(ulong address, ulong size, bool write = false)
  744. {
  745. return GetBuffer(address, size, write).GetRange(address, size);
  746. }
  747. /// <summary>
  748. /// Gets a buffer for a given memory range.
  749. /// A buffer overlapping with the specified range is assumed to already exist on the cache.
  750. /// </summary>
  751. /// <param name="address">Start address of the memory range</param>
  752. /// <param name="size">Size in bytes of the memory range</param>
  753. /// <param name="write">Whether the buffer will be written to by this use</param>
  754. /// <returns>The buffer where the range is fully contained</returns>
  755. private Buffer GetBuffer(ulong address, ulong size, bool write = false)
  756. {
  757. Buffer buffer;
  758. if (size != 0)
  759. {
  760. lock (_buffers)
  761. {
  762. buffer = _buffers.FindFirstOverlap(address, size);
  763. }
  764. buffer.SynchronizeMemory(address, size);
  765. if (write)
  766. {
  767. buffer.SignalModified(address, size);
  768. }
  769. }
  770. else
  771. {
  772. lock (_buffers)
  773. {
  774. buffer = _buffers.FindFirstOverlap(address, 1);
  775. }
  776. }
  777. return buffer;
  778. }
  779. /// <summary>
  780. /// Performs guest to host memory synchronization of a given memory range.
  781. /// </summary>
  782. /// <param name="address">Start address of the memory range</param>
  783. /// <param name="size">Size in bytes of the memory range</param>
  784. private void SynchronizeBufferRange(ulong address, ulong size)
  785. {
  786. if (size != 0)
  787. {
  788. Buffer buffer;
  789. lock (_buffers)
  790. {
  791. buffer = _buffers.FindFirstOverlap(address, size);
  792. }
  793. buffer.SynchronizeMemory(address, size);
  794. }
  795. }
  796. /// <summary>
  797. /// Disposes all buffers in the cache.
  798. /// It's an error to use the buffer manager after disposal.
  799. /// </summary>
  800. public void Dispose()
  801. {
  802. lock (_buffers)
  803. {
  804. foreach (Buffer buffer in _buffers)
  805. {
  806. buffer.Dispose();
  807. }
  808. }
  809. }
  810. }
  811. }