PipelineBase.cs 61 KB

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