PipelineBase.cs 64 KB

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