PipelineBase.cs 48 KB

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