PipelineBase.cs 60 KB

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