PipelineBase.cs 49 KB

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