PipelineBase.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Shader;
  4. using Silk.NET.Vulkan;
  5. using System;
  6. using System.Linq;
  7. using System.Numerics;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Vulkan
  11. {
  12. class PipelineBase : IDisposable
  13. {
  14. public const int DescriptorSetLayouts = 4;
  15. public const int UniformSetIndex = 0;
  16. public const int StorageSetIndex = 1;
  17. public const int TextureSetIndex = 2;
  18. public const int ImageSetIndex = 3;
  19. protected readonly VulkanRenderer Gd;
  20. protected readonly Device Device;
  21. public readonly PipelineCache PipelineCache;
  22. public readonly AutoFlushCounter AutoFlush;
  23. protected PipelineDynamicState DynamicState;
  24. private PipelineState _newState;
  25. private bool _stateDirty;
  26. private GAL.PrimitiveTopology _topology;
  27. private ulong _currentPipelineHandle;
  28. protected Auto<DisposablePipeline> Pipeline;
  29. protected PipelineBindPoint Pbp;
  30. protected CommandBufferScoped Cbs;
  31. protected CommandBufferScoped? PreloadCbs;
  32. protected CommandBuffer CommandBuffer;
  33. public CommandBufferScoped CurrentCommandBuffer => Cbs;
  34. private ShaderCollection _program;
  35. private Vector4<float>[] _renderScale = new Vector4<float>[73];
  36. private int _fragmentScaleCount;
  37. protected FramebufferParams FramebufferParams;
  38. private Auto<DisposableFramebuffer> _framebuffer;
  39. private Auto<DisposableRenderPass> _renderPass;
  40. private int _writtenAttachmentCount;
  41. private bool _framebufferUsingColorWriteMask;
  42. private ITexture[] _preMaskColors;
  43. private ITexture _preMaskDepthStencil;
  44. private readonly DescriptorSetUpdater _descriptorSetUpdater;
  45. private IndexBufferState _indexBuffer;
  46. private IndexBufferPattern _indexBufferPattern;
  47. private readonly BufferState[] _transformFeedbackBuffers;
  48. private readonly VertexBufferState[] _vertexBuffers;
  49. private ulong _vertexBuffersDirty;
  50. protected Rectangle<int> ClearScissor;
  51. public SupportBufferUpdater SupportBufferUpdater;
  52. public IndexBufferPattern QuadsToTrisPattern;
  53. public IndexBufferPattern TriFanToTrisPattern;
  54. private bool _needsIndexBufferRebind;
  55. private bool _needsTransformFeedbackBuffersRebind;
  56. private bool _tfEnabled;
  57. private bool _tfActive;
  58. private PipelineColorBlendAttachmentState[] _storedBlend;
  59. public ulong DrawCount { get; private set; }
  60. public bool RenderPassActive { get; private set; }
  61. public unsafe PipelineBase(VulkanRenderer gd, Device device)
  62. {
  63. Gd = gd;
  64. Device = device;
  65. AutoFlush = new AutoFlushCounter();
  66. var pipelineCacheCreateInfo = new PipelineCacheCreateInfo()
  67. {
  68. SType = StructureType.PipelineCacheCreateInfo
  69. };
  70. gd.Api.CreatePipelineCache(device, pipelineCacheCreateInfo, null, out PipelineCache).ThrowOnError();
  71. _descriptorSetUpdater = new DescriptorSetUpdater(gd, this);
  72. _transformFeedbackBuffers = new BufferState[Constants.MaxTransformFeedbackBuffers];
  73. _vertexBuffers = new VertexBufferState[Constants.MaxVertexBuffers + 1];
  74. const int EmptyVbSize = 16;
  75. using var emptyVb = gd.BufferManager.Create(gd, EmptyVbSize);
  76. emptyVb.SetData(0, new byte[EmptyVbSize]);
  77. _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize, 0);
  78. _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length);
  79. ClearScissor = new Rectangle<int>(0, 0, 0xffff, 0xffff);
  80. var defaultScale = new Vector4<float> { X = 1f, Y = 0f, Z = 0f, W = 0f };
  81. new Span<Vector4<float>>(_renderScale).Fill(defaultScale);
  82. _storedBlend = new PipelineColorBlendAttachmentState[Constants.MaxRenderTargets];
  83. _newState.Initialize();
  84. }
  85. public void Initialize()
  86. {
  87. _descriptorSetUpdater.Initialize();
  88. SupportBufferUpdater = new SupportBufferUpdater(Gd);
  89. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, SupportBuffer.RenderScaleMaxCount);
  90. QuadsToTrisPattern = new IndexBufferPattern(Gd, 4, 6, 0, new[] { 0, 1, 2, 0, 2, 3 }, 4, false);
  91. TriFanToTrisPattern = new IndexBufferPattern(Gd, 3, 3, 2, new[] { int.MinValue, -1, 0 }, 1, true);
  92. }
  93. public unsafe void Barrier()
  94. {
  95. MemoryBarrier memoryBarrier = new MemoryBarrier()
  96. {
  97. SType = StructureType.MemoryBarrier,
  98. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  99. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  100. };
  101. Gd.Api.CmdPipelineBarrier(
  102. CommandBuffer,
  103. PipelineStageFlags.FragmentShaderBit,
  104. PipelineStageFlags.FragmentShaderBit,
  105. 0,
  106. 1,
  107. memoryBarrier,
  108. 0,
  109. null,
  110. 0,
  111. null);
  112. }
  113. public void ComputeBarrier()
  114. {
  115. MemoryBarrier memoryBarrier = new MemoryBarrier()
  116. {
  117. SType = StructureType.MemoryBarrier,
  118. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  119. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  120. };
  121. Gd.Api.CmdPipelineBarrier(
  122. CommandBuffer,
  123. PipelineStageFlags.ComputeShaderBit,
  124. PipelineStageFlags.AllCommandsBit,
  125. 0,
  126. 1,
  127. new ReadOnlySpan<MemoryBarrier>(memoryBarrier),
  128. 0,
  129. ReadOnlySpan<BufferMemoryBarrier>.Empty,
  130. 0,
  131. ReadOnlySpan<ImageMemoryBarrier>.Empty);
  132. }
  133. public void BeginTransformFeedback(GAL.PrimitiveTopology topology)
  134. {
  135. _tfEnabled = true;
  136. }
  137. public void ClearBuffer(BufferHandle destination, int offset, int size, uint value)
  138. {
  139. EndRenderPass();
  140. var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size).Value;
  141. BufferHolder.InsertBufferBarrier(
  142. Gd,
  143. Cbs.CommandBuffer,
  144. dst,
  145. BufferHolder.DefaultAccessFlags,
  146. AccessFlags.TransferWriteBit,
  147. PipelineStageFlags.AllCommandsBit,
  148. PipelineStageFlags.TransferBit,
  149. offset,
  150. size);
  151. Gd.Api.CmdFillBuffer(CommandBuffer, dst, (ulong)offset, (ulong)size, value);
  152. BufferHolder.InsertBufferBarrier(
  153. Gd,
  154. Cbs.CommandBuffer,
  155. dst,
  156. AccessFlags.TransferWriteBit,
  157. BufferHolder.DefaultAccessFlags,
  158. PipelineStageFlags.TransferBit,
  159. PipelineStageFlags.AllCommandsBit,
  160. offset,
  161. size);
  162. }
  163. public unsafe void ClearRenderTargetColor(int index, int layer, int layerCount, ColorF color)
  164. {
  165. if (FramebufferParams == null || !FramebufferParams.IsValidColorAttachment(index))
  166. {
  167. return;
  168. }
  169. if (_renderPass == null)
  170. {
  171. CreateRenderPass();
  172. }
  173. BeginRenderPass();
  174. var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha));
  175. var attachment = new ClearAttachment(ImageAspectFlags.ColorBit, (uint)index, clearValue);
  176. var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);
  177. FramebufferParams.InsertClearBarrier(Cbs, index);
  178. Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
  179. }
  180. public unsafe void ClearRenderTargetDepthStencil(int layer, int layerCount, float depthValue, bool depthMask, int stencilValue, int stencilMask)
  181. {
  182. // TODO: Use stencilMask (fully)
  183. if (FramebufferParams == null || !FramebufferParams.HasDepthStencil)
  184. {
  185. return;
  186. }
  187. if (_renderPass == null)
  188. {
  189. CreateRenderPass();
  190. }
  191. BeginRenderPass();
  192. var clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue));
  193. var flags = depthMask ? ImageAspectFlags.DepthBit : 0;
  194. if (stencilMask != 0)
  195. {
  196. flags |= ImageAspectFlags.StencilBit;
  197. }
  198. var attachment = new ClearAttachment(flags, 0, clearValue);
  199. var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);
  200. FramebufferParams.InsertClearBarrierDS(Cbs);
  201. Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
  202. }
  203. public unsafe void CommandBufferBarrier()
  204. {
  205. MemoryBarrier memoryBarrier = new MemoryBarrier()
  206. {
  207. SType = StructureType.MemoryBarrier,
  208. SrcAccessMask = BufferHolder.DefaultAccessFlags,
  209. DstAccessMask = AccessFlags.IndirectCommandReadBit
  210. };
  211. Gd.Api.CmdPipelineBarrier(
  212. CommandBuffer,
  213. PipelineStageFlags.AllCommandsBit,
  214. PipelineStageFlags.DrawIndirectBit,
  215. 0,
  216. 1,
  217. memoryBarrier,
  218. 0,
  219. null,
  220. 0,
  221. null);
  222. }
  223. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  224. {
  225. EndRenderPass();
  226. var src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false);
  227. var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true);
  228. BufferHolder.Copy(Gd, Cbs, src, dst, srcOffset, dstOffset, size);
  229. }
  230. public void DirtyVertexBuffer(Auto<DisposableBuffer> buffer)
  231. {
  232. for (int i = 0; i < _vertexBuffers.Length; i++)
  233. {
  234. if (_vertexBuffers[i].BoundEquals(buffer))
  235. {
  236. _vertexBuffersDirty |= 1UL << i;
  237. }
  238. }
  239. }
  240. public void DirtyIndexBuffer(Auto<DisposableBuffer> buffer)
  241. {
  242. if (_indexBuffer.BoundEquals(buffer))
  243. {
  244. _needsIndexBufferRebind = true;
  245. }
  246. }
  247. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  248. {
  249. if (!_program.IsLinked)
  250. {
  251. return;
  252. }
  253. EndRenderPass();
  254. RecreatePipelineIfNeeded(PipelineBindPoint.Compute);
  255. Gd.Api.CmdDispatch(CommandBuffer, (uint)groupsX, (uint)groupsY, (uint)groupsZ);
  256. }
  257. public void DispatchComputeIndirect(Auto<DisposableBuffer> indirectBuffer, int indirectBufferOffset)
  258. {
  259. if (!_program.IsLinked)
  260. {
  261. return;
  262. }
  263. EndRenderPass();
  264. RecreatePipelineIfNeeded(PipelineBindPoint.Compute);
  265. Gd.Api.CmdDispatchIndirect(CommandBuffer, indirectBuffer.Get(Cbs, indirectBufferOffset, 12).Value, (ulong)indirectBufferOffset);
  266. }
  267. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  268. {
  269. if (!_program.IsLinked)
  270. {
  271. return;
  272. }
  273. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  274. BeginRenderPass();
  275. DrawCount++;
  276. if (Gd.TopologyUnsupported(_topology))
  277. {
  278. // Temporarily bind a conversion pattern as an index buffer.
  279. _needsIndexBufferRebind = true;
  280. IndexBufferPattern pattern = _topology switch
  281. {
  282. GAL.PrimitiveTopology.Quads => QuadsToTrisPattern,
  283. GAL.PrimitiveTopology.TriangleFan or
  284. GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern,
  285. _ => throw new NotSupportedException($"Unsupported topology: {_topology}")
  286. };
  287. BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount);
  288. var buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false);
  289. Gd.Api.CmdBindIndexBuffer(CommandBuffer, buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value, 0, Silk.NET.Vulkan.IndexType.Uint32);
  290. BeginRenderPass(); // May have been interrupted to set buffer data.
  291. ResumeTransformFeedbackInternal();
  292. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)indexCount, (uint)instanceCount, 0, firstVertex, (uint)firstInstance);
  293. }
  294. else
  295. {
  296. ResumeTransformFeedbackInternal();
  297. Gd.Api.CmdDraw(CommandBuffer, (uint)vertexCount, (uint)instanceCount, (uint)firstVertex, (uint)firstInstance);
  298. }
  299. }
  300. private void UpdateIndexBufferPattern()
  301. {
  302. IndexBufferPattern pattern = null;
  303. if (Gd.TopologyUnsupported(_topology))
  304. {
  305. pattern = _topology switch
  306. {
  307. GAL.PrimitiveTopology.Quads => QuadsToTrisPattern,
  308. GAL.PrimitiveTopology.TriangleFan or
  309. GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern,
  310. _ => throw new NotSupportedException($"Unsupported topology: {_topology}")
  311. };
  312. }
  313. if (_indexBufferPattern != pattern)
  314. {
  315. _indexBufferPattern = pattern;
  316. _needsIndexBufferRebind = true;
  317. }
  318. }
  319. public void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int firstVertex, int firstInstance)
  320. {
  321. if (!_program.IsLinked)
  322. {
  323. return;
  324. }
  325. UpdateIndexBufferPattern();
  326. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  327. BeginRenderPass();
  328. DrawCount++;
  329. if (_indexBufferPattern != null)
  330. {
  331. // Convert the index buffer into a supported topology.
  332. IndexBufferPattern pattern = _indexBufferPattern;
  333. int convertedCount = pattern.GetConvertedCount(indexCount);
  334. if (_needsIndexBufferRebind)
  335. {
  336. _indexBuffer.BindConvertedIndexBuffer(Gd, Cbs, firstIndex, indexCount, convertedCount, pattern);
  337. _needsIndexBufferRebind = false;
  338. }
  339. BeginRenderPass(); // May have been interrupted to set buffer data.
  340. ResumeTransformFeedbackInternal();
  341. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)convertedCount, (uint)instanceCount, 0, firstVertex, (uint)firstInstance);
  342. }
  343. else
  344. {
  345. ResumeTransformFeedbackInternal();
  346. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)indexCount, (uint)instanceCount, (uint)firstIndex, firstVertex, (uint)firstInstance);
  347. }
  348. }
  349. public void DrawIndexedIndirect(BufferRange indirectBuffer)
  350. {
  351. if (!_program.IsLinked)
  352. {
  353. return;
  354. }
  355. UpdateIndexBufferPattern();
  356. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  357. BeginRenderPass();
  358. DrawCount++;
  359. if (_indexBufferPattern != null)
  360. {
  361. // Convert the index buffer into a supported topology.
  362. IndexBufferPattern pattern = _indexBufferPattern;
  363. Auto<DisposableBuffer> indirectBufferAuto = _indexBuffer.BindConvertedIndexBufferIndirect(
  364. Gd,
  365. Cbs,
  366. indirectBuffer,
  367. BufferRange.Empty,
  368. pattern,
  369. false,
  370. 1,
  371. indirectBuffer.Size);
  372. _needsIndexBufferRebind = false;
  373. BeginRenderPass(); // May have been interrupted to set buffer data.
  374. ResumeTransformFeedbackInternal();
  375. Gd.Api.CmdDrawIndexedIndirect(CommandBuffer, indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value, 0, 1, (uint)indirectBuffer.Size);
  376. }
  377. else
  378. {
  379. var buffer = Gd.BufferManager
  380. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  381. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  382. ResumeTransformFeedbackInternal();
  383. Gd.Api.CmdDrawIndexedIndirect(CommandBuffer, buffer, (ulong)indirectBuffer.Offset, 1, (uint)indirectBuffer.Size);
  384. }
  385. }
  386. public void DrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  387. {
  388. if (!_program.IsLinked)
  389. {
  390. return;
  391. }
  392. UpdateIndexBufferPattern();
  393. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  394. BeginRenderPass();
  395. DrawCount++;
  396. var countBuffer = Gd.BufferManager
  397. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false)
  398. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  399. if (_indexBufferPattern != null)
  400. {
  401. // Convert the index buffer into a supported topology.
  402. IndexBufferPattern pattern = _indexBufferPattern;
  403. Auto<DisposableBuffer> indirectBufferAuto = _indexBuffer.BindConvertedIndexBufferIndirect(
  404. Gd,
  405. Cbs,
  406. indirectBuffer,
  407. parameterBuffer,
  408. pattern,
  409. true,
  410. maxDrawCount,
  411. stride);
  412. _needsIndexBufferRebind = false;
  413. BeginRenderPass(); // May have been interrupted to set buffer data.
  414. ResumeTransformFeedbackInternal();
  415. if (Gd.Capabilities.SupportsIndirectParameters)
  416. {
  417. Gd.DrawIndirectCountApi.CmdDrawIndexedIndirectCount(
  418. CommandBuffer,
  419. indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value,
  420. 0,
  421. countBuffer,
  422. (ulong)parameterBuffer.Offset,
  423. (uint)maxDrawCount,
  424. (uint)stride);
  425. }
  426. else
  427. {
  428. // This is also fine because the indirect data conversion always zeros
  429. // the entries that are past the current draw count.
  430. Gd.Api.CmdDrawIndexedIndirect(
  431. CommandBuffer,
  432. indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value,
  433. 0,
  434. (uint)maxDrawCount,
  435. (uint)stride);
  436. }
  437. }
  438. else
  439. {
  440. var buffer = Gd.BufferManager
  441. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  442. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  443. ResumeTransformFeedbackInternal();
  444. if (Gd.Capabilities.SupportsIndirectParameters)
  445. {
  446. Gd.DrawIndirectCountApi.CmdDrawIndexedIndirectCount(
  447. CommandBuffer,
  448. buffer,
  449. (ulong)indirectBuffer.Offset,
  450. countBuffer,
  451. (ulong)parameterBuffer.Offset,
  452. (uint)maxDrawCount,
  453. (uint)stride);
  454. }
  455. else
  456. {
  457. // Not fully correct, but we can't do much better if the host does not support indirect count.
  458. Gd.Api.CmdDrawIndexedIndirect(
  459. CommandBuffer,
  460. buffer,
  461. (ulong)indirectBuffer.Offset,
  462. (uint)maxDrawCount,
  463. (uint)stride);
  464. }
  465. }
  466. }
  467. public void DrawIndirect(BufferRange indirectBuffer)
  468. {
  469. if (!_program.IsLinked)
  470. {
  471. return;
  472. }
  473. // TODO: Support quads and other unsupported topologies.
  474. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  475. BeginRenderPass();
  476. ResumeTransformFeedbackInternal();
  477. DrawCount++;
  478. var buffer = Gd.BufferManager
  479. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  480. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  481. Gd.Api.CmdDrawIndirect(CommandBuffer, buffer, (ulong)indirectBuffer.Offset, 1, (uint)indirectBuffer.Size);
  482. }
  483. public void DrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  484. {
  485. if (!Gd.Capabilities.SupportsIndirectParameters)
  486. {
  487. // TODO: Fallback for when this is not supported.
  488. throw new NotSupportedException();
  489. }
  490. if (!_program.IsLinked)
  491. {
  492. return;
  493. }
  494. // TODO: Support quads and other unsupported topologies.
  495. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  496. BeginRenderPass();
  497. ResumeTransformFeedbackInternal();
  498. DrawCount++;
  499. var buffer = Gd.BufferManager
  500. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  501. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  502. var countBuffer = Gd.BufferManager
  503. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false)
  504. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  505. Gd.DrawIndirectCountApi.CmdDrawIndirectCount(
  506. CommandBuffer,
  507. buffer,
  508. (ulong)indirectBuffer.Offset,
  509. countBuffer,
  510. (ulong)parameterBuffer.Offset,
  511. (uint)maxDrawCount,
  512. (uint)stride);
  513. }
  514. public void DrawTexture(ITexture texture, ISampler sampler, Extents2DF srcRegion, Extents2DF dstRegion)
  515. {
  516. if (texture is TextureView srcTexture)
  517. {
  518. SupportBufferUpdater.Commit();
  519. var oldCullMode = _newState.CullMode;
  520. var oldStencilTestEnable = _newState.StencilTestEnable;
  521. var oldDepthTestEnable = _newState.DepthTestEnable;
  522. var oldDepthWriteEnable = _newState.DepthWriteEnable;
  523. var oldTopology = _newState.Topology;
  524. var oldViewports = DynamicState.Viewports;
  525. var oldViewportsCount = _newState.ViewportsCount;
  526. _newState.CullMode = CullModeFlags.None;
  527. _newState.StencilTestEnable = false;
  528. _newState.DepthTestEnable = false;
  529. _newState.DepthWriteEnable = false;
  530. SignalStateChange();
  531. Gd.HelperShader.DrawTexture(
  532. Gd,
  533. this,
  534. srcTexture,
  535. sampler,
  536. srcRegion,
  537. dstRegion);
  538. _newState.CullMode = oldCullMode;
  539. _newState.StencilTestEnable = oldStencilTestEnable;
  540. _newState.DepthTestEnable = oldDepthTestEnable;
  541. _newState.DepthWriteEnable = oldDepthWriteEnable;
  542. _newState.Topology = oldTopology;
  543. DynamicState.SetViewports(ref oldViewports, oldViewportsCount);
  544. _newState.ViewportsCount = oldViewportsCount;
  545. SignalStateChange();
  546. }
  547. }
  548. public void EndTransformFeedback()
  549. {
  550. PauseTransformFeedbackInternal();
  551. _tfEnabled = false;
  552. }
  553. public double GetCounterDivisor(CounterType type)
  554. {
  555. if (type == CounterType.SamplesPassed)
  556. {
  557. return _renderScale[0].X * _renderScale[0].X;
  558. }
  559. return 1;
  560. }
  561. public bool IsCommandBufferActive(CommandBuffer cb)
  562. {
  563. return CommandBuffer.Handle == cb.Handle;
  564. }
  565. public void SetAlphaTest(bool enable, float reference, GAL.CompareOp op)
  566. {
  567. // This is currently handled using shader specialization, as Vulkan does not support alpha test.
  568. // In the future, we may want to use this to write the reference value into the support buffer,
  569. // to avoid creating one version of the shader per reference value used.
  570. }
  571. public void SetBlendState(AdvancedBlendDescriptor blend)
  572. {
  573. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  574. {
  575. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index];
  576. if (index == 0)
  577. {
  578. var blendOp = blend.Op.Convert();
  579. vkBlend = new PipelineColorBlendAttachmentState(
  580. blendEnable: true,
  581. colorBlendOp: blendOp,
  582. alphaBlendOp: blendOp,
  583. colorWriteMask: vkBlend.ColorWriteMask);
  584. if (Gd.Capabilities.SupportsBlendEquationAdvancedNonPreMultipliedSrcColor)
  585. {
  586. _newState.AdvancedBlendSrcPreMultiplied = blend.SrcPreMultiplied;
  587. }
  588. if (Gd.Capabilities.SupportsBlendEquationAdvancedCorrelatedOverlap)
  589. {
  590. _newState.AdvancedBlendOverlap = blend.Overlap.Convert();
  591. }
  592. }
  593. else
  594. {
  595. vkBlend = new PipelineColorBlendAttachmentState(
  596. colorWriteMask: vkBlend.ColorWriteMask);
  597. }
  598. if (vkBlend.ColorWriteMask == 0)
  599. {
  600. _storedBlend[index] = vkBlend;
  601. vkBlend = new PipelineColorBlendAttachmentState();
  602. }
  603. }
  604. SignalStateChange();
  605. }
  606. public void SetBlendState(int index, BlendDescriptor blend)
  607. {
  608. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index];
  609. if (blend.Enable)
  610. {
  611. vkBlend.BlendEnable = blend.Enable;
  612. vkBlend.SrcColorBlendFactor = blend.ColorSrcFactor.Convert();
  613. vkBlend.DstColorBlendFactor = blend.ColorDstFactor.Convert();
  614. vkBlend.ColorBlendOp = blend.ColorOp.Convert();
  615. vkBlend.SrcAlphaBlendFactor = blend.AlphaSrcFactor.Convert();
  616. vkBlend.DstAlphaBlendFactor = blend.AlphaDstFactor.Convert();
  617. vkBlend.AlphaBlendOp = blend.AlphaOp.Convert();
  618. }
  619. else
  620. {
  621. vkBlend = new PipelineColorBlendAttachmentState(
  622. colorWriteMask: vkBlend.ColorWriteMask);
  623. }
  624. if (vkBlend.ColorWriteMask == 0)
  625. {
  626. _storedBlend[index] = vkBlend;
  627. vkBlend = new PipelineColorBlendAttachmentState();
  628. }
  629. DynamicState.SetBlendConstants(
  630. blend.BlendConstant.Red,
  631. blend.BlendConstant.Green,
  632. blend.BlendConstant.Blue,
  633. blend.BlendConstant.Alpha);
  634. // Reset advanced blend state back defaults to the cache to help the pipeline cache.
  635. _newState.AdvancedBlendSrcPreMultiplied = true;
  636. _newState.AdvancedBlendDstPreMultiplied = true;
  637. _newState.AdvancedBlendOverlap = BlendOverlapEXT.UncorrelatedExt;
  638. SignalStateChange();
  639. }
  640. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  641. {
  642. DynamicState.SetDepthBias(factor, units, clamp);
  643. _newState.DepthBiasEnable = enables != 0;
  644. SignalStateChange();
  645. }
  646. public void SetDepthClamp(bool clamp)
  647. {
  648. _newState.DepthClampEnable = clamp;
  649. SignalStateChange();
  650. }
  651. public void SetDepthMode(DepthMode mode)
  652. {
  653. // Currently this is emulated on the shader, because Vulkan had no support for changing the depth mode.
  654. // In the future, we may want to use the VK_EXT_depth_clip_control extension to change it here.
  655. }
  656. public void SetDepthTest(DepthTestDescriptor depthTest)
  657. {
  658. _newState.DepthTestEnable = depthTest.TestEnable;
  659. _newState.DepthWriteEnable = depthTest.WriteEnable;
  660. _newState.DepthCompareOp = depthTest.Func.Convert();
  661. SignalStateChange();
  662. }
  663. public void SetFaceCulling(bool enable, Face face)
  664. {
  665. _newState.CullMode = enable ? face.Convert() : CullModeFlags.None;
  666. SignalStateChange();
  667. }
  668. public void SetFrontFace(GAL.FrontFace frontFace)
  669. {
  670. _newState.FrontFace = frontFace.Convert();
  671. SignalStateChange();
  672. }
  673. public void SetImage(int binding, ITexture image, GAL.Format imageFormat)
  674. {
  675. _descriptorSetUpdater.SetImage(binding, image, imageFormat);
  676. }
  677. public void SetImage(int binding, Auto<DisposableImageView> image)
  678. {
  679. _descriptorSetUpdater.SetImage(binding, image);
  680. }
  681. public void SetIndexBuffer(BufferRange buffer, GAL.IndexType type)
  682. {
  683. if (buffer.Handle != BufferHandle.Null)
  684. {
  685. _indexBuffer = new IndexBufferState(buffer.Handle, buffer.Offset, buffer.Size, type.Convert());
  686. }
  687. else
  688. {
  689. _indexBuffer = IndexBufferState.Null;
  690. }
  691. _needsIndexBufferRebind = true;
  692. }
  693. public void SetLineParameters(float width, bool smooth)
  694. {
  695. _newState.LineWidth = width;
  696. SignalStateChange();
  697. }
  698. public void SetLogicOpState(bool enable, LogicalOp op)
  699. {
  700. _newState.LogicOpEnable = enable;
  701. _newState.LogicOp = op.Convert();
  702. SignalStateChange();
  703. }
  704. public void SetMultisampleState(MultisampleDescriptor multisample)
  705. {
  706. _newState.AlphaToCoverageEnable = multisample.AlphaToCoverageEnable;
  707. _newState.AlphaToOneEnable = multisample.AlphaToOneEnable;
  708. SignalStateChange();
  709. }
  710. public void SetOrigin(Origin origin)
  711. {
  712. // TODO.
  713. }
  714. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  715. {
  716. _newState.PatchControlPoints = (uint)vertices;
  717. SignalStateChange();
  718. // TODO: Default levels (likely needs emulation on shaders?)
  719. }
  720. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  721. {
  722. // TODO.
  723. }
  724. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  725. {
  726. // TODO.
  727. }
  728. public void SetPrimitiveRestart(bool enable, int index)
  729. {
  730. _newState.PrimitiveRestartEnable = enable;
  731. // TODO: What to do about the index?
  732. SignalStateChange();
  733. }
  734. public void SetPrimitiveTopology(GAL.PrimitiveTopology topology)
  735. {
  736. _topology = topology;
  737. var vkTopology = Gd.TopologyRemap(topology).Convert();
  738. _newState.Topology = vkTopology;
  739. SignalStateChange();
  740. }
  741. public void SetProgram(IProgram program)
  742. {
  743. var internalProgram = (ShaderCollection)program;
  744. var stages = internalProgram.GetInfos();
  745. _program = internalProgram;
  746. _descriptorSetUpdater.SetProgram(internalProgram);
  747. _newState.PipelineLayout = internalProgram.PipelineLayout;
  748. _newState.StagesCount = (uint)stages.Length;
  749. stages.CopyTo(_newState.Stages.AsSpan().Slice(0, stages.Length));
  750. SignalStateChange();
  751. if (_program.IsCompute)
  752. {
  753. EndRenderPass();
  754. }
  755. }
  756. public void Specialize<T>(in T data) where T : unmanaged
  757. {
  758. var dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1));
  759. if (!dataSpan.SequenceEqual(_newState.SpecializationData.Span))
  760. {
  761. _newState.SpecializationData = new SpecData(dataSpan);
  762. SignalStateChange();
  763. }
  764. }
  765. protected virtual void SignalAttachmentChange()
  766. {
  767. }
  768. public void SetRasterizerDiscard(bool discard)
  769. {
  770. _newState.RasterizerDiscardEnable = discard;
  771. SignalStateChange();
  772. }
  773. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMask)
  774. {
  775. int count = Math.Min(Constants.MaxRenderTargets, componentMask.Length);
  776. int writtenAttachments = 0;
  777. for (int i = 0; i < count; i++)
  778. {
  779. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i];
  780. var newMask = (ColorComponentFlags)componentMask[i];
  781. // When color write mask is 0, remove all blend state to help the pipeline cache.
  782. // Restore it when the mask becomes non-zero.
  783. if (vkBlend.ColorWriteMask != newMask)
  784. {
  785. if (newMask == 0)
  786. {
  787. _storedBlend[i] = vkBlend;
  788. vkBlend = new PipelineColorBlendAttachmentState();
  789. }
  790. else if (vkBlend.ColorWriteMask == 0)
  791. {
  792. vkBlend = _storedBlend[i];
  793. }
  794. }
  795. vkBlend.ColorWriteMask = newMask;
  796. if (componentMask[i] != 0)
  797. {
  798. writtenAttachments++;
  799. }
  800. }
  801. if (_framebufferUsingColorWriteMask)
  802. {
  803. SetRenderTargetsInternal(_preMaskColors, _preMaskDepthStencil, true);
  804. }
  805. else
  806. {
  807. SignalStateChange();
  808. if (writtenAttachments != _writtenAttachmentCount)
  809. {
  810. SignalAttachmentChange();
  811. _writtenAttachmentCount = writtenAttachments;
  812. }
  813. }
  814. }
  815. private void SetRenderTargetsInternal(ITexture[] colors, ITexture depthStencil, bool filterWriteMasked)
  816. {
  817. FramebufferParams?.UpdateModifications();
  818. CreateFramebuffer(colors, depthStencil, filterWriteMasked);
  819. CreateRenderPass();
  820. SignalStateChange();
  821. SignalAttachmentChange();
  822. }
  823. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  824. {
  825. _framebufferUsingColorWriteMask = false;
  826. SetRenderTargetsInternal(colors, depthStencil, Gd.IsTBDR);
  827. }
  828. public void SetRenderTargetScale(float scale)
  829. {
  830. _renderScale[0].X = scale;
  831. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  832. }
  833. public void SetScissors(ReadOnlySpan<Rectangle<int>> regions)
  834. {
  835. int maxScissors = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  836. int count = Math.Min(maxScissors, regions.Length);
  837. if (count > 0)
  838. {
  839. ClearScissor = regions[0];
  840. }
  841. for (int i = 0; i < count; i++)
  842. {
  843. var region = regions[i];
  844. var offset = new Offset2D(region.X, region.Y);
  845. var extent = new Extent2D((uint)region.Width, (uint)region.Height);
  846. DynamicState.SetScissor(i, new Rect2D(offset, extent));
  847. }
  848. DynamicState.ScissorsCount = count;
  849. _newState.ScissorsCount = (uint)count;
  850. SignalStateChange();
  851. }
  852. public void SetStencilTest(StencilTestDescriptor stencilTest)
  853. {
  854. DynamicState.SetStencilMasks(
  855. (uint)stencilTest.BackFuncMask,
  856. (uint)stencilTest.BackMask,
  857. (uint)stencilTest.BackFuncRef,
  858. (uint)stencilTest.FrontFuncMask,
  859. (uint)stencilTest.FrontMask,
  860. (uint)stencilTest.FrontFuncRef);
  861. _newState.StencilTestEnable = stencilTest.TestEnable;
  862. _newState.StencilBackFailOp = stencilTest.BackSFail.Convert();
  863. _newState.StencilBackPassOp = stencilTest.BackDpPass.Convert();
  864. _newState.StencilBackDepthFailOp = stencilTest.BackDpFail.Convert();
  865. _newState.StencilBackCompareOp = stencilTest.BackFunc.Convert();
  866. _newState.StencilFrontFailOp = stencilTest.FrontSFail.Convert();
  867. _newState.StencilFrontPassOp = stencilTest.FrontDpPass.Convert();
  868. _newState.StencilFrontDepthFailOp = stencilTest.FrontDpFail.Convert();
  869. _newState.StencilFrontCompareOp = stencilTest.FrontFunc.Convert();
  870. SignalStateChange();
  871. }
  872. public void SetStorageBuffers(ReadOnlySpan<BufferAssignment> buffers)
  873. {
  874. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, buffers);
  875. }
  876. public void SetStorageBuffers(int first, ReadOnlySpan<Auto<DisposableBuffer>> buffers)
  877. {
  878. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, first, buffers);
  879. }
  880. public void SetTextureAndSampler(ShaderStage stage, int binding, ITexture texture, ISampler sampler)
  881. {
  882. _descriptorSetUpdater.SetTextureAndSampler(Cbs, stage, binding, texture, sampler);
  883. }
  884. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  885. {
  886. PauseTransformFeedbackInternal();
  887. int count = Math.Min(Constants.MaxTransformFeedbackBuffers, buffers.Length);
  888. for (int i = 0; i < count; i++)
  889. {
  890. var range = buffers[i];
  891. _transformFeedbackBuffers[i].Dispose();
  892. if (range.Handle != BufferHandle.Null)
  893. {
  894. _transformFeedbackBuffers[i] =
  895. new BufferState(Gd.BufferManager.GetBuffer(CommandBuffer, range.Handle, range.Offset, range.Size, true), range.Offset, range.Size);
  896. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  897. }
  898. else
  899. {
  900. _transformFeedbackBuffers[i] = BufferState.Null;
  901. }
  902. }
  903. }
  904. public void SetUniformBuffers(ReadOnlySpan<BufferAssignment> buffers)
  905. {
  906. _descriptorSetUpdater.SetUniformBuffers(CommandBuffer, buffers);
  907. }
  908. public void SetUserClipDistance(int index, bool enableClip)
  909. {
  910. // TODO.
  911. }
  912. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  913. {
  914. var formatCapabilities = Gd.FormatCapabilities;
  915. Span<int> newVbScalarSizes = stackalloc int[Constants.MaxVertexBuffers];
  916. int count = Math.Min(Constants.MaxVertexAttributes, vertexAttribs.Length);
  917. uint dirtyVbSizes = 0;
  918. for (int i = 0; i < count; i++)
  919. {
  920. var attribute = vertexAttribs[i];
  921. var rawIndex = attribute.BufferIndex;
  922. var bufferIndex = attribute.IsZero ? 0 : rawIndex + 1;
  923. if (!attribute.IsZero)
  924. {
  925. newVbScalarSizes[rawIndex] = Math.Max(newVbScalarSizes[rawIndex], attribute.Format.GetScalarSize());
  926. dirtyVbSizes |= 1u << rawIndex;
  927. }
  928. _newState.Internal.VertexAttributeDescriptions[i] = new VertexInputAttributeDescription(
  929. (uint)i,
  930. (uint)bufferIndex,
  931. formatCapabilities.ConvertToVertexVkFormat(attribute.Format),
  932. (uint)attribute.Offset);
  933. }
  934. while (dirtyVbSizes != 0)
  935. {
  936. int dirtyBit = BitOperations.TrailingZeroCount(dirtyVbSizes);
  937. ref var buffer = ref _vertexBuffers[dirtyBit + 1];
  938. if (buffer.AttributeScalarAlignment != newVbScalarSizes[dirtyBit])
  939. {
  940. _vertexBuffersDirty |= 1UL << (dirtyBit + 1);
  941. buffer.AttributeScalarAlignment = newVbScalarSizes[dirtyBit];
  942. }
  943. dirtyVbSizes &= ~(1u << dirtyBit);
  944. }
  945. _newState.VertexAttributeDescriptionsCount = (uint)count;
  946. SignalStateChange();
  947. }
  948. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  949. {
  950. int count = Math.Min(Constants.MaxVertexBuffers, vertexBuffers.Length);
  951. _newState.Internal.VertexBindingDescriptions[0] = new VertexInputBindingDescription(0, 0, VertexInputRate.Vertex);
  952. int validCount = 1;
  953. for (int i = 0; i < count; i++)
  954. {
  955. var vertexBuffer = vertexBuffers[i];
  956. // TODO: Support divisor > 1
  957. var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex;
  958. if (vertexBuffer.Buffer.Handle != BufferHandle.Null)
  959. {
  960. var vb = Gd.BufferManager.GetBuffer(CommandBuffer, vertexBuffer.Buffer.Handle, false);
  961. if (vb != null)
  962. {
  963. int binding = i + 1;
  964. int descriptorIndex = validCount++;
  965. _newState.Internal.VertexBindingDescriptions[descriptorIndex] = new VertexInputBindingDescription(
  966. (uint)binding,
  967. (uint)vertexBuffer.Stride,
  968. inputRate);
  969. int vbSize = vertexBuffer.Buffer.Size;
  970. if (Gd.Vendor == Vendor.Amd && !Gd.IsMoltenVk && vertexBuffer.Stride > 0)
  971. {
  972. // AMD has a bug where if offset + stride * count is greater than
  973. // the size, then the last attribute will have the wrong value.
  974. // As a workaround, simply use the full buffer size.
  975. int remainder = vbSize % vertexBuffer.Stride;
  976. if (remainder != 0)
  977. {
  978. vbSize += vertexBuffer.Stride - remainder;
  979. }
  980. }
  981. ref var buffer = ref _vertexBuffers[binding];
  982. int oldScalarAlign = buffer.AttributeScalarAlignment;
  983. buffer.Dispose();
  984. if (Gd.Capabilities.VertexBufferAlignment < 2 &&
  985. (vertexBuffer.Stride % FormatExtensions.MaxBufferFormatScalarSize) == 0)
  986. {
  987. buffer = new VertexBufferState(
  988. vb,
  989. descriptorIndex,
  990. vertexBuffer.Buffer.Offset,
  991. vbSize,
  992. vertexBuffer.Stride);
  993. buffer.BindVertexBuffer(Gd, Cbs, (uint)binding, ref _newState);
  994. }
  995. else
  996. {
  997. // May need to be rewritten. Bind this buffer before draw.
  998. buffer = new VertexBufferState(
  999. vertexBuffer.Buffer.Handle,
  1000. descriptorIndex,
  1001. vertexBuffer.Buffer.Offset,
  1002. vbSize,
  1003. vertexBuffer.Stride);
  1004. _vertexBuffersDirty |= 1UL << binding;
  1005. }
  1006. buffer.AttributeScalarAlignment = oldScalarAlign;
  1007. }
  1008. }
  1009. }
  1010. _newState.VertexBindingDescriptionsCount = (uint)validCount;
  1011. SignalStateChange();
  1012. }
  1013. public void SetViewports(ReadOnlySpan<GAL.Viewport> viewports, bool disableTransform)
  1014. {
  1015. int maxViewports = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  1016. int count = Math.Min(maxViewports, viewports.Length);
  1017. static float Clamp(float value)
  1018. {
  1019. return Math.Clamp(value, 0f, 1f);
  1020. }
  1021. DynamicState.ViewportsCount = (uint)count;
  1022. for (int i = 0; i < count; i++)
  1023. {
  1024. var viewport = viewports[i];
  1025. DynamicState.SetViewport(i, new Silk.NET.Vulkan.Viewport(
  1026. viewport.Region.X,
  1027. viewport.Region.Y,
  1028. viewport.Region.Width == 0f ? 1f : viewport.Region.Width,
  1029. viewport.Region.Height == 0f ? 1f : viewport.Region.Height,
  1030. Clamp(viewport.DepthNear),
  1031. Clamp(viewport.DepthFar)));
  1032. }
  1033. float disableTransformF = disableTransform ? 1.0f : 0.0f;
  1034. if (SupportBufferUpdater.Data.ViewportInverse.W != disableTransformF || disableTransform)
  1035. {
  1036. float scale = _renderScale[0].X;
  1037. SupportBufferUpdater.UpdateViewportInverse(new Vector4<float>
  1038. {
  1039. X = scale * 2f / viewports[0].Region.Width,
  1040. Y = scale * 2f / viewports[0].Region.Height,
  1041. Z = 1,
  1042. W = disableTransformF
  1043. });
  1044. }
  1045. _newState.ViewportsCount = (uint)count;
  1046. SignalStateChange();
  1047. }
  1048. public void SwapBuffer(Auto<DisposableBuffer> from, Auto<DisposableBuffer> to)
  1049. {
  1050. _indexBuffer.Swap(from, to);
  1051. for (int i = 0; i < _vertexBuffers.Length; i++)
  1052. {
  1053. _vertexBuffers[i].Swap(from, to);
  1054. }
  1055. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1056. {
  1057. _transformFeedbackBuffers[i].Swap(from, to);
  1058. }
  1059. _descriptorSetUpdater.SwapBuffer(from, to);
  1060. SignalCommandBufferChange();
  1061. }
  1062. public unsafe void TextureBarrier()
  1063. {
  1064. MemoryBarrier memoryBarrier = new MemoryBarrier()
  1065. {
  1066. SType = StructureType.MemoryBarrier,
  1067. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  1068. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  1069. };
  1070. Gd.Api.CmdPipelineBarrier(
  1071. CommandBuffer,
  1072. PipelineStageFlags.FragmentShaderBit,
  1073. PipelineStageFlags.FragmentShaderBit,
  1074. 0,
  1075. 1,
  1076. memoryBarrier,
  1077. 0,
  1078. null,
  1079. 0,
  1080. null);
  1081. }
  1082. public void TextureBarrierTiled()
  1083. {
  1084. TextureBarrier();
  1085. }
  1086. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  1087. {
  1088. bool changed = false;
  1089. for (int index = 0; index < totalCount; index++)
  1090. {
  1091. if (_renderScale[1 + index].X != scales[index])
  1092. {
  1093. _renderScale[1 + index].X = scales[index];
  1094. changed = true;
  1095. }
  1096. }
  1097. // Only update fragment count if there are scales after it for the vertex stage.
  1098. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  1099. {
  1100. _fragmentScaleCount = fragmentCount;
  1101. SupportBufferUpdater.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  1102. }
  1103. if (changed)
  1104. {
  1105. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  1106. }
  1107. }
  1108. protected void SignalCommandBufferChange()
  1109. {
  1110. _needsIndexBufferRebind = true;
  1111. _needsTransformFeedbackBuffersRebind = true;
  1112. _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length);
  1113. _descriptorSetUpdater.SignalCommandBufferChange();
  1114. DynamicState.ForceAllDirty();
  1115. _currentPipelineHandle = 0;
  1116. }
  1117. private void CreateFramebuffer(ITexture[] colors, ITexture depthStencil, bool filterWriteMasked)
  1118. {
  1119. if (filterWriteMasked)
  1120. {
  1121. // TBDR GPUs don't work properly if the same attachment is bound to multiple targets,
  1122. // due to each attachment being a copy of the real attachment, rather than a direct write.
  1123. // Just try to remove duplicate attachments.
  1124. // Save a copy of the array to rebind when mask changes.
  1125. void maskOut()
  1126. {
  1127. if (!_framebufferUsingColorWriteMask)
  1128. {
  1129. _preMaskColors = colors.ToArray();
  1130. _preMaskDepthStencil = depthStencil;
  1131. }
  1132. // If true, then the framebuffer must be recreated when the mask changes.
  1133. _framebufferUsingColorWriteMask = true;
  1134. }
  1135. // Look for textures that are masked out.
  1136. for (int i = 0; i < colors.Length; i++)
  1137. {
  1138. if (colors[i] == null)
  1139. {
  1140. continue;
  1141. }
  1142. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i];
  1143. for (int j = 0; j < i; j++)
  1144. {
  1145. // Check each binding for a duplicate binding before it.
  1146. if (colors[i] == colors[j])
  1147. {
  1148. // Prefer the binding with no write mask.
  1149. ref var vkBlend2 = ref _newState.Internal.ColorBlendAttachmentState[j];
  1150. if (vkBlend.ColorWriteMask == 0)
  1151. {
  1152. colors[i] = null;
  1153. maskOut();
  1154. }
  1155. else if (vkBlend2.ColorWriteMask == 0)
  1156. {
  1157. colors[j] = null;
  1158. maskOut();
  1159. }
  1160. }
  1161. }
  1162. }
  1163. }
  1164. FramebufferParams = new FramebufferParams(Device, colors, depthStencil);
  1165. UpdatePipelineAttachmentFormats();
  1166. }
  1167. protected void UpdatePipelineAttachmentFormats()
  1168. {
  1169. var dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan();
  1170. FramebufferParams.AttachmentFormats.CopyTo(dstAttachmentFormats);
  1171. for (int i = FramebufferParams.AttachmentFormats.Length; i < dstAttachmentFormats.Length; i++)
  1172. {
  1173. dstAttachmentFormats[i] = 0;
  1174. }
  1175. _newState.ColorBlendAttachmentStateCount = (uint)(FramebufferParams.MaxColorAttachmentIndex + 1);
  1176. _newState.HasDepthStencil = FramebufferParams.HasDepthStencil;
  1177. _newState.SamplesCount = FramebufferParams.AttachmentSamples.Length != 0 ? FramebufferParams.AttachmentSamples[0] : 1;
  1178. }
  1179. protected unsafe void CreateRenderPass()
  1180. {
  1181. const int MaxAttachments = Constants.MaxRenderTargets + 1;
  1182. AttachmentDescription[] attachmentDescs = null;
  1183. var subpass = new SubpassDescription()
  1184. {
  1185. PipelineBindPoint = PipelineBindPoint.Graphics
  1186. };
  1187. AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments];
  1188. var hasFramebuffer = FramebufferParams != null;
  1189. if (hasFramebuffer && FramebufferParams.AttachmentsCount != 0)
  1190. {
  1191. attachmentDescs = new AttachmentDescription[FramebufferParams.AttachmentsCount];
  1192. for (int i = 0; i < FramebufferParams.AttachmentsCount; i++)
  1193. {
  1194. attachmentDescs[i] = new AttachmentDescription(
  1195. 0,
  1196. FramebufferParams.AttachmentFormats[i],
  1197. TextureStorage.ConvertToSampleCountFlags(Gd.Capabilities.SupportedSampleCounts, FramebufferParams.AttachmentSamples[i]),
  1198. AttachmentLoadOp.Load,
  1199. AttachmentStoreOp.Store,
  1200. AttachmentLoadOp.Load,
  1201. AttachmentStoreOp.Store,
  1202. ImageLayout.General,
  1203. ImageLayout.General);
  1204. }
  1205. int colorAttachmentsCount = FramebufferParams.ColorAttachmentsCount;
  1206. if (colorAttachmentsCount > MaxAttachments - 1)
  1207. {
  1208. colorAttachmentsCount = MaxAttachments - 1;
  1209. }
  1210. if (colorAttachmentsCount != 0)
  1211. {
  1212. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex;
  1213. subpass.ColorAttachmentCount = (uint)maxAttachmentIndex + 1;
  1214. subpass.PColorAttachments = &attachmentReferences[0];
  1215. // Fill with VK_ATTACHMENT_UNUSED to cover any gaps.
  1216. for (int i = 0; i <= maxAttachmentIndex; i++)
  1217. {
  1218. subpass.PColorAttachments[i] = new AttachmentReference(Vk.AttachmentUnused, ImageLayout.Undefined);
  1219. }
  1220. for (int i = 0; i < colorAttachmentsCount; i++)
  1221. {
  1222. int bindIndex = FramebufferParams.AttachmentIndices[i];
  1223. subpass.PColorAttachments[bindIndex] = new AttachmentReference((uint)i, ImageLayout.General);
  1224. }
  1225. }
  1226. if (FramebufferParams.HasDepthStencil)
  1227. {
  1228. uint dsIndex = (uint)FramebufferParams.AttachmentsCount - 1;
  1229. subpass.PDepthStencilAttachment = &attachmentReferences[MaxAttachments - 1];
  1230. *subpass.PDepthStencilAttachment = new AttachmentReference(dsIndex, ImageLayout.General);
  1231. }
  1232. }
  1233. var subpassDependency = PipelineConverter.CreateSubpassDependency();
  1234. fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs)
  1235. {
  1236. var renderPassCreateInfo = new RenderPassCreateInfo()
  1237. {
  1238. SType = StructureType.RenderPassCreateInfo,
  1239. PAttachments = pAttachmentDescs,
  1240. AttachmentCount = attachmentDescs != null ? (uint)attachmentDescs.Length : 0,
  1241. PSubpasses = &subpass,
  1242. SubpassCount = 1,
  1243. PDependencies = &subpassDependency,
  1244. DependencyCount = 1
  1245. };
  1246. Gd.Api.CreateRenderPass(Device, renderPassCreateInfo, null, out var renderPass).ThrowOnError();
  1247. _renderPass?.Dispose();
  1248. _renderPass = new Auto<DisposableRenderPass>(new DisposableRenderPass(Gd.Api, Device, renderPass));
  1249. }
  1250. EndRenderPass();
  1251. _framebuffer?.Dispose();
  1252. _framebuffer = hasFramebuffer ? FramebufferParams.Create(Gd.Api, Cbs, _renderPass) : null;
  1253. }
  1254. protected void SignalStateChange()
  1255. {
  1256. _stateDirty = true;
  1257. }
  1258. private void RecreatePipelineIfNeeded(PipelineBindPoint pbp)
  1259. {
  1260. DynamicState.ReplayIfDirty(Gd.Api, CommandBuffer);
  1261. // Commit changes to the support buffer before drawing.
  1262. SupportBufferUpdater.Commit();
  1263. if (_needsIndexBufferRebind && _indexBufferPattern == null)
  1264. {
  1265. _indexBuffer.BindIndexBuffer(Gd, Cbs);
  1266. _needsIndexBufferRebind = false;
  1267. }
  1268. if (_needsTransformFeedbackBuffersRebind)
  1269. {
  1270. PauseTransformFeedbackInternal();
  1271. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1272. {
  1273. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  1274. }
  1275. _needsTransformFeedbackBuffersRebind = false;
  1276. }
  1277. if (_vertexBuffersDirty != 0)
  1278. {
  1279. while (_vertexBuffersDirty != 0)
  1280. {
  1281. int i = BitOperations.TrailingZeroCount(_vertexBuffersDirty);
  1282. _vertexBuffers[i].BindVertexBuffer(Gd, Cbs, (uint)i, ref _newState);
  1283. _vertexBuffersDirty &= ~(1UL << i);
  1284. }
  1285. }
  1286. if (_stateDirty || Pbp != pbp)
  1287. {
  1288. CreatePipeline(pbp);
  1289. _stateDirty = false;
  1290. Pbp = pbp;
  1291. }
  1292. _descriptorSetUpdater.UpdateAndBindDescriptorSets(Cbs, pbp);
  1293. }
  1294. private void CreatePipeline(PipelineBindPoint pbp)
  1295. {
  1296. // We can only create a pipeline if the have the shader stages set.
  1297. if (_newState.Stages != null)
  1298. {
  1299. if (pbp == PipelineBindPoint.Graphics && _renderPass == null)
  1300. {
  1301. CreateRenderPass();
  1302. }
  1303. var pipeline = pbp == PipelineBindPoint.Compute
  1304. ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache)
  1305. : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass.Get(Cbs).Value);
  1306. ulong pipelineHandle = pipeline.GetUnsafe().Value.Handle;
  1307. if (_currentPipelineHandle != pipelineHandle)
  1308. {
  1309. _currentPipelineHandle = pipelineHandle;
  1310. Pipeline = pipeline;
  1311. PauseTransformFeedbackInternal();
  1312. Gd.Api.CmdBindPipeline(CommandBuffer, pbp, Pipeline.Get(Cbs).Value);
  1313. }
  1314. }
  1315. }
  1316. private unsafe void BeginRenderPass()
  1317. {
  1318. if (!RenderPassActive)
  1319. {
  1320. var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height));
  1321. var clearValue = new ClearValue();
  1322. var renderPassBeginInfo = new RenderPassBeginInfo()
  1323. {
  1324. SType = StructureType.RenderPassBeginInfo,
  1325. RenderPass = _renderPass.Get(Cbs).Value,
  1326. Framebuffer = _framebuffer.Get(Cbs).Value,
  1327. RenderArea = renderArea,
  1328. PClearValues = &clearValue,
  1329. ClearValueCount = 1
  1330. };
  1331. Gd.Api.CmdBeginRenderPass(CommandBuffer, renderPassBeginInfo, SubpassContents.Inline);
  1332. RenderPassActive = true;
  1333. }
  1334. }
  1335. public void EndRenderPass()
  1336. {
  1337. if (RenderPassActive)
  1338. {
  1339. PauseTransformFeedbackInternal();
  1340. Gd.Api.CmdEndRenderPass(CommandBuffer);
  1341. SignalRenderPassEnd();
  1342. RenderPassActive = false;
  1343. }
  1344. }
  1345. protected virtual void SignalRenderPassEnd()
  1346. {
  1347. }
  1348. private void PauseTransformFeedbackInternal()
  1349. {
  1350. if (_tfEnabled && _tfActive)
  1351. {
  1352. EndTransformFeedbackInternal();
  1353. _tfActive = false;
  1354. }
  1355. }
  1356. private void ResumeTransformFeedbackInternal()
  1357. {
  1358. if (_tfEnabled && !_tfActive)
  1359. {
  1360. BeginTransformFeedbackInternal();
  1361. _tfActive = true;
  1362. }
  1363. }
  1364. private unsafe void BeginTransformFeedbackInternal()
  1365. {
  1366. Gd.TransformFeedbackApi.CmdBeginTransformFeedback(CommandBuffer, 0, 0, null, null);
  1367. }
  1368. private unsafe void EndTransformFeedbackInternal()
  1369. {
  1370. Gd.TransformFeedbackApi.CmdEndTransformFeedback(CommandBuffer, 0, 0, null, null);
  1371. }
  1372. protected virtual void Dispose(bool disposing)
  1373. {
  1374. if (disposing)
  1375. {
  1376. _renderPass?.Dispose();
  1377. _framebuffer?.Dispose();
  1378. _newState.Dispose();
  1379. _descriptorSetUpdater.Dispose();
  1380. for (int i = 0; i < _vertexBuffers.Length; i++)
  1381. {
  1382. _vertexBuffers[i].Dispose();
  1383. }
  1384. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1385. {
  1386. _transformFeedbackBuffers[i].Dispose();
  1387. }
  1388. Pipeline?.Dispose();
  1389. unsafe
  1390. {
  1391. Gd.Api.DestroyPipelineCache(Device, PipelineCache, null);
  1392. }
  1393. SupportBufferUpdater.Dispose();
  1394. }
  1395. }
  1396. public void Dispose()
  1397. {
  1398. Dispose(true);
  1399. }
  1400. }
  1401. }