BufferManager.cs 34 KB

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