PipelineBase.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  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. protected 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, 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, offset, size, 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, srcOffset, size, false);
  184. var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, 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
  354. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, true)
  355. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  356. var countBuffer = Gd.BufferManager
  357. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, true)
  358. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  359. Gd.DrawIndirectCountApi.CmdDrawIndirectCount(
  360. CommandBuffer,
  361. buffer,
  362. (ulong)indirectBuffer.Offset,
  363. countBuffer,
  364. (ulong)parameterBuffer.Offset,
  365. (uint)maxDrawCount,
  366. (uint)stride);
  367. }
  368. public void MultiDrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  369. {
  370. if (!Gd.Capabilities.SupportsIndirectParameters)
  371. {
  372. throw new NotSupportedException();
  373. }
  374. if (_program.LinkStatus != ProgramLinkStatus.Success)
  375. {
  376. return;
  377. }
  378. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  379. BeginRenderPass();
  380. ResumeTransformFeedbackInternal();
  381. DrawCount++;
  382. var buffer = Gd.BufferManager
  383. .GetBuffer(CommandBuffer, indirectBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, true)
  384. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  385. var countBuffer = Gd.BufferManager
  386. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, true)
  387. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  388. Gd.DrawIndirectCountApi.CmdDrawIndexedIndirectCount(
  389. CommandBuffer,
  390. buffer,
  391. (ulong)indirectBuffer.Offset,
  392. countBuffer,
  393. (ulong)parameterBuffer.Offset,
  394. (uint)maxDrawCount,
  395. (uint)stride);
  396. }
  397. public void SetAlphaTest(bool enable, float reference, GAL.CompareOp op)
  398. {
  399. // This is currently handled using shader specialization, as Vulkan does not support alpha test.
  400. // In the future, we may want to use this to write the reference value into the support buffer,
  401. // to avoid creating one version of the shader per reference value used.
  402. }
  403. public void SetBlendState(int index, BlendDescriptor blend)
  404. {
  405. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index];
  406. if (blend.Enable)
  407. {
  408. vkBlend.BlendEnable = blend.Enable;
  409. vkBlend.SrcColorBlendFactor = blend.ColorSrcFactor.Convert();
  410. vkBlend.DstColorBlendFactor = blend.ColorDstFactor.Convert();
  411. vkBlend.ColorBlendOp = blend.ColorOp.Convert();
  412. vkBlend.SrcAlphaBlendFactor = blend.AlphaSrcFactor.Convert();
  413. vkBlend.DstAlphaBlendFactor = blend.AlphaDstFactor.Convert();
  414. vkBlend.AlphaBlendOp = blend.AlphaOp.Convert();
  415. }
  416. else
  417. {
  418. vkBlend = new PipelineColorBlendAttachmentState(
  419. colorWriteMask: vkBlend.ColorWriteMask);
  420. }
  421. if (vkBlend.ColorWriteMask == 0)
  422. {
  423. _storedBlend[index] = vkBlend;
  424. vkBlend = new PipelineColorBlendAttachmentState();
  425. }
  426. DynamicState.SetBlendConstants(
  427. blend.BlendConstant.Red,
  428. blend.BlendConstant.Green,
  429. blend.BlendConstant.Blue,
  430. blend.BlendConstant.Alpha);
  431. SignalStateChange();
  432. }
  433. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  434. {
  435. DynamicState.SetDepthBias(factor, units, clamp);
  436. _newState.DepthBiasEnable = enables != 0;
  437. SignalStateChange();
  438. }
  439. public void SetDepthClamp(bool clamp)
  440. {
  441. _newState.DepthClampEnable = clamp;
  442. SignalStateChange();
  443. }
  444. public void SetDepthMode(DepthMode mode)
  445. {
  446. // Currently this is emulated on the shader, because Vulkan had no support for changing the depth mode.
  447. // In the future, we may want to use the VK_EXT_depth_clip_control extension to change it here.
  448. }
  449. public void SetDepthTest(DepthTestDescriptor depthTest)
  450. {
  451. _newState.DepthTestEnable = depthTest.TestEnable;
  452. _newState.DepthWriteEnable = depthTest.WriteEnable;
  453. _newState.DepthCompareOp = depthTest.Func.Convert();
  454. SignalStateChange();
  455. }
  456. public void SetFaceCulling(bool enable, Face face)
  457. {
  458. _newState.CullMode = enable ? face.Convert() : CullModeFlags.CullModeNone;
  459. SignalStateChange();
  460. }
  461. public void SetFrontFace(GAL.FrontFace frontFace)
  462. {
  463. _newState.FrontFace = frontFace.Convert();
  464. SignalStateChange();
  465. }
  466. public void SetImage(int binding, ITexture image, GAL.Format imageFormat)
  467. {
  468. _descriptorSetUpdater.SetImage(binding, image, imageFormat);
  469. }
  470. public void SetIndexBuffer(BufferRange buffer, GAL.IndexType type)
  471. {
  472. if (buffer.Handle != BufferHandle.Null)
  473. {
  474. _indexBuffer = new IndexBufferState(buffer.Handle, buffer.Offset, buffer.Size, type.Convert());
  475. }
  476. else
  477. {
  478. _indexBuffer = IndexBufferState.Null;
  479. }
  480. _needsIndexBufferRebind = true;
  481. }
  482. public void SetLineParameters(float width, bool smooth)
  483. {
  484. _newState.LineWidth = width;
  485. SignalStateChange();
  486. }
  487. public void SetLogicOpState(bool enable, LogicalOp op)
  488. {
  489. _newState.LogicOpEnable = enable;
  490. _newState.LogicOp = op.Convert();
  491. SignalStateChange();
  492. }
  493. public void SetMultisampleState(MultisampleDescriptor multisample)
  494. {
  495. _newState.AlphaToCoverageEnable = multisample.AlphaToCoverageEnable;
  496. _newState.AlphaToOneEnable = multisample.AlphaToOneEnable;
  497. SignalStateChange();
  498. }
  499. public void SetOrigin(Origin origin)
  500. {
  501. // TODO.
  502. }
  503. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  504. {
  505. _newState.PatchControlPoints = (uint)vertices;
  506. SignalStateChange();
  507. // TODO: Default levels (likely needs emulation on shaders?)
  508. }
  509. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  510. {
  511. // TODO.
  512. }
  513. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  514. {
  515. // TODO.
  516. }
  517. public void SetPrimitiveRestart(bool enable, int index)
  518. {
  519. _newState.PrimitiveRestartEnable = enable;
  520. // TODO: What to do about the index?
  521. SignalStateChange();
  522. }
  523. public void SetPrimitiveTopology(GAL.PrimitiveTopology topology)
  524. {
  525. _topology = topology;
  526. var vkTopology = Gd.TopologyRemap(topology).Convert();
  527. _newState.Topology = vkTopology;
  528. SignalStateChange();
  529. }
  530. public void SetProgram(IProgram program)
  531. {
  532. var internalProgram = (ShaderCollection)program;
  533. var stages = internalProgram.GetInfos();
  534. _program = internalProgram;
  535. _descriptorSetUpdater.SetProgram(internalProgram);
  536. _newState.PipelineLayout = internalProgram.PipelineLayout;
  537. _newState.StagesCount = (uint)stages.Length;
  538. stages.CopyTo(_newState.Stages.AsSpan().Slice(0, stages.Length));
  539. SignalStateChange();
  540. }
  541. protected virtual void SignalAttachmentChange()
  542. {
  543. }
  544. public void SetRasterizerDiscard(bool discard)
  545. {
  546. _newState.RasterizerDiscardEnable = discard;
  547. SignalStateChange();
  548. }
  549. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMask)
  550. {
  551. int count = Math.Min(Constants.MaxRenderTargets, componentMask.Length);
  552. int writtenAttachments = 0;
  553. for (int i = 0; i < count; i++)
  554. {
  555. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i];
  556. var newMask = (ColorComponentFlags)componentMask[i];
  557. // When color write mask is 0, remove all blend state to help the pipeline cache.
  558. // Restore it when the mask becomes non-zero.
  559. if (vkBlend.ColorWriteMask != newMask)
  560. {
  561. if (newMask == 0)
  562. {
  563. _storedBlend[i] = vkBlend;
  564. vkBlend = new PipelineColorBlendAttachmentState();
  565. }
  566. else if (vkBlend.ColorWriteMask == 0)
  567. {
  568. vkBlend = _storedBlend[i];
  569. }
  570. }
  571. vkBlend.ColorWriteMask = newMask;
  572. if (componentMask[i] != 0)
  573. {
  574. writtenAttachments++;
  575. }
  576. }
  577. SignalStateChange();
  578. if (writtenAttachments != _writtenAttachmentCount)
  579. {
  580. SignalAttachmentChange();
  581. _writtenAttachmentCount = writtenAttachments;
  582. }
  583. }
  584. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  585. {
  586. FramebufferParams?.UpdateModifications();
  587. CreateFramebuffer(colors, depthStencil);
  588. CreateRenderPass();
  589. SignalStateChange();
  590. SignalAttachmentChange();
  591. }
  592. public void SetRenderTargetScale(float scale)
  593. {
  594. _renderScale[0].X = scale;
  595. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  596. }
  597. public void SetScissors(ReadOnlySpan<Rectangle<int>> regions)
  598. {
  599. int maxScissors = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  600. int count = Math.Min(maxScissors, regions.Length);
  601. if (count > 0)
  602. {
  603. ClearScissor = regions[0];
  604. }
  605. for (int i = 0; i < count; i++)
  606. {
  607. var region = regions[i];
  608. var offset = new Offset2D(region.X, region.Y);
  609. var extent = new Extent2D((uint)region.Width, (uint)region.Height);
  610. DynamicState.SetScissor(i, new Rect2D(offset, extent));
  611. }
  612. DynamicState.ScissorsCount = count;
  613. _newState.ScissorsCount = (uint)count;
  614. SignalStateChange();
  615. }
  616. public void SetStencilTest(StencilTestDescriptor stencilTest)
  617. {
  618. DynamicState.SetStencilMasks(
  619. (uint)stencilTest.BackFuncMask,
  620. (uint)stencilTest.BackMask,
  621. (uint)stencilTest.BackFuncRef,
  622. (uint)stencilTest.FrontFuncMask,
  623. (uint)stencilTest.FrontMask,
  624. (uint)stencilTest.FrontFuncRef);
  625. _newState.StencilTestEnable = stencilTest.TestEnable;
  626. _newState.StencilBackFailOp = stencilTest.BackSFail.Convert();
  627. _newState.StencilBackPassOp = stencilTest.BackDpPass.Convert();
  628. _newState.StencilBackDepthFailOp = stencilTest.BackDpFail.Convert();
  629. _newState.StencilBackCompareOp = stencilTest.BackFunc.Convert();
  630. _newState.StencilFrontFailOp = stencilTest.FrontSFail.Convert();
  631. _newState.StencilFrontPassOp = stencilTest.FrontDpPass.Convert();
  632. _newState.StencilFrontDepthFailOp = stencilTest.FrontDpFail.Convert();
  633. _newState.StencilFrontCompareOp = stencilTest.FrontFunc.Convert();
  634. SignalStateChange();
  635. }
  636. public void SetStorageBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  637. {
  638. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, first, buffers);
  639. }
  640. public void SetStorageBuffers(int first, ReadOnlySpan<Auto<DisposableBuffer>> buffers)
  641. {
  642. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, first, buffers);
  643. }
  644. public void SetTextureAndSampler(ShaderStage stage, int binding, ITexture texture, ISampler sampler)
  645. {
  646. _descriptorSetUpdater.SetTextureAndSampler(Cbs, stage, binding, texture, sampler);
  647. }
  648. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  649. {
  650. PauseTransformFeedbackInternal();
  651. int count = Math.Min(Constants.MaxTransformFeedbackBuffers, buffers.Length);
  652. for (int i = 0; i < count; i++)
  653. {
  654. var range = buffers[i];
  655. _transformFeedbackBuffers[i].Dispose();
  656. if (range.Handle != BufferHandle.Null)
  657. {
  658. _transformFeedbackBuffers[i] =
  659. new BufferState(Gd.BufferManager.GetBuffer(CommandBuffer, range.Handle, range.Offset, range.Size, true), range.Offset, range.Size);
  660. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  661. }
  662. else
  663. {
  664. _transformFeedbackBuffers[i] = BufferState.Null;
  665. }
  666. }
  667. }
  668. public void SetUniformBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  669. {
  670. _descriptorSetUpdater.SetUniformBuffers(CommandBuffer, first, buffers);
  671. }
  672. public void SetUserClipDistance(int index, bool enableClip)
  673. {
  674. // TODO.
  675. }
  676. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  677. {
  678. var formatCapabilities = Gd.FormatCapabilities;
  679. Span<int> newVbScalarSizes = stackalloc int[Constants.MaxVertexBuffers];
  680. int count = Math.Min(Constants.MaxVertexAttributes, vertexAttribs.Length);
  681. uint dirtyVbSizes = 0;
  682. for (int i = 0; i < count; i++)
  683. {
  684. var attribute = vertexAttribs[i];
  685. var rawIndex = attribute.BufferIndex;
  686. var bufferIndex = attribute.IsZero ? 0 : rawIndex + 1;
  687. if (!attribute.IsZero)
  688. {
  689. newVbScalarSizes[rawIndex] = Math.Max(newVbScalarSizes[rawIndex], attribute.Format.GetScalarSize());
  690. dirtyVbSizes |= 1u << rawIndex;
  691. }
  692. _newState.Internal.VertexAttributeDescriptions[i] = new VertexInputAttributeDescription(
  693. (uint)i,
  694. (uint)bufferIndex,
  695. formatCapabilities.ConvertToVertexVkFormat(attribute.Format),
  696. (uint)attribute.Offset);
  697. }
  698. while (dirtyVbSizes != 0)
  699. {
  700. int dirtyBit = BitOperations.TrailingZeroCount(dirtyVbSizes);
  701. ref var buffer = ref _vertexBuffers[dirtyBit + 1];
  702. if (buffer.AttributeScalarAlignment != newVbScalarSizes[dirtyBit])
  703. {
  704. _vertexBuffersDirty |= 1UL << (dirtyBit + 1);
  705. buffer.AttributeScalarAlignment = newVbScalarSizes[dirtyBit];
  706. }
  707. dirtyVbSizes &= ~(1u << dirtyBit);
  708. }
  709. _newState.VertexAttributeDescriptionsCount = (uint)count;
  710. SignalStateChange();
  711. }
  712. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  713. {
  714. int count = Math.Min(Constants.MaxVertexBuffers, vertexBuffers.Length);
  715. _newState.Internal.VertexBindingDescriptions[0] = new VertexInputBindingDescription(0, 0, VertexInputRate.Vertex);
  716. int validCount = 1;
  717. for (int i = 0; i < count; i++)
  718. {
  719. var vertexBuffer = vertexBuffers[i];
  720. // TODO: Support divisor > 1
  721. var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex;
  722. if (vertexBuffer.Buffer.Handle != BufferHandle.Null)
  723. {
  724. var vb = Gd.BufferManager.GetBuffer(CommandBuffer, vertexBuffer.Buffer.Handle, false);
  725. if (vb != null)
  726. {
  727. int binding = i + 1;
  728. int descriptorIndex = validCount++;
  729. _newState.Internal.VertexBindingDescriptions[descriptorIndex] = new VertexInputBindingDescription(
  730. (uint)binding,
  731. (uint)vertexBuffer.Stride,
  732. inputRate);
  733. int vbSize = vertexBuffer.Buffer.Size;
  734. if (Gd.Vendor == Vendor.Amd && vertexBuffer.Stride > 0)
  735. {
  736. // AMD has a bug where if offset + stride * count is greater than
  737. // the size, then the last attribute will have the wrong value.
  738. // As a workaround, simply use the full buffer size.
  739. int remainder = vbSize % vertexBuffer.Stride;
  740. if (remainder != 0)
  741. {
  742. vbSize += vertexBuffer.Stride - remainder;
  743. }
  744. }
  745. ref var buffer = ref _vertexBuffers[binding];
  746. int oldScalarAlign = buffer.AttributeScalarAlignment;
  747. buffer.Dispose();
  748. if ((vertexBuffer.Stride % FormatExtensions.MaxBufferFormatScalarSize) == 0)
  749. {
  750. buffer = new VertexBufferState(
  751. vb,
  752. descriptorIndex,
  753. vertexBuffer.Buffer.Offset,
  754. vbSize,
  755. vertexBuffer.Stride);
  756. buffer.BindVertexBuffer(Gd, Cbs, (uint)binding, ref _newState);
  757. }
  758. else
  759. {
  760. // May need to be rewritten. Bind this buffer before draw.
  761. buffer = new VertexBufferState(
  762. vertexBuffer.Buffer.Handle,
  763. descriptorIndex,
  764. vertexBuffer.Buffer.Offset,
  765. vbSize,
  766. vertexBuffer.Stride);
  767. _vertexBuffersDirty |= 1UL << binding;
  768. }
  769. buffer.AttributeScalarAlignment = oldScalarAlign;
  770. }
  771. }
  772. }
  773. _newState.VertexBindingDescriptionsCount = (uint)validCount;
  774. SignalStateChange();
  775. }
  776. public void SetViewports(ReadOnlySpan<GAL.Viewport> viewports, bool disableTransform)
  777. {
  778. int maxViewports = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  779. int count = Math.Min(maxViewports, viewports.Length);
  780. static float Clamp(float value)
  781. {
  782. return Math.Clamp(value, 0f, 1f);
  783. }
  784. for (int i = 0; i < count; i++)
  785. {
  786. var viewport = viewports[i];
  787. DynamicState.SetViewport(i, new Silk.NET.Vulkan.Viewport(
  788. viewport.Region.X,
  789. viewport.Region.Y,
  790. viewport.Region.Width == 0f ? 1f : viewport.Region.Width,
  791. viewport.Region.Height == 0f ? 1f : viewport.Region.Height,
  792. Clamp(viewport.DepthNear),
  793. Clamp(viewport.DepthFar)));
  794. }
  795. DynamicState.ViewportsCount = count;
  796. float disableTransformF = disableTransform ? 1.0f : 0.0f;
  797. if (SupportBufferUpdater.Data.ViewportInverse.W != disableTransformF || disableTransform)
  798. {
  799. float scale = _renderScale[0].X;
  800. SupportBufferUpdater.UpdateViewportInverse(new Vector4<float>
  801. {
  802. X = scale * 2f / viewports[0].Region.Width,
  803. Y = scale * 2f / viewports[0].Region.Height,
  804. Z = 1,
  805. W = disableTransformF
  806. });
  807. }
  808. _newState.ViewportsCount = (uint)count;
  809. SignalStateChange();
  810. }
  811. public unsafe void TextureBarrier()
  812. {
  813. MemoryBarrier memoryBarrier = new MemoryBarrier()
  814. {
  815. SType = StructureType.MemoryBarrier,
  816. SrcAccessMask = AccessFlags.AccessMemoryReadBit | AccessFlags.AccessMemoryWriteBit,
  817. DstAccessMask = AccessFlags.AccessMemoryReadBit | AccessFlags.AccessMemoryWriteBit
  818. };
  819. Gd.Api.CmdPipelineBarrier(
  820. CommandBuffer,
  821. PipelineStageFlags.PipelineStageFragmentShaderBit,
  822. PipelineStageFlags.PipelineStageFragmentShaderBit,
  823. 0,
  824. 1,
  825. memoryBarrier,
  826. 0,
  827. null,
  828. 0,
  829. null);
  830. }
  831. public void TextureBarrierTiled()
  832. {
  833. TextureBarrier();
  834. }
  835. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  836. {
  837. bool changed = false;
  838. for (int index = 0; index < totalCount; index++)
  839. {
  840. if (_renderScale[1 + index].X != scales[index])
  841. {
  842. _renderScale[1 + index].X = scales[index];
  843. changed = true;
  844. }
  845. }
  846. // Only update fragment count if there are scales after it for the vertex stage.
  847. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  848. {
  849. _fragmentScaleCount = fragmentCount;
  850. SupportBufferUpdater.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  851. }
  852. if (changed)
  853. {
  854. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  855. }
  856. }
  857. protected void SignalCommandBufferChange()
  858. {
  859. _needsIndexBufferRebind = true;
  860. _needsTransformFeedbackBuffersRebind = true;
  861. _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length);
  862. _descriptorSetUpdater.SignalCommandBufferChange();
  863. DynamicState.ForceAllDirty();
  864. _currentPipelineHandle = 0;
  865. }
  866. private void CreateFramebuffer(ITexture[] colors, ITexture depthStencil)
  867. {
  868. FramebufferParams = new FramebufferParams(Device, colors, depthStencil);
  869. UpdatePipelineAttachmentFormats();
  870. _newState.SamplesCount = FramebufferParams.AttachmentSamples.Length != 0 ? FramebufferParams.AttachmentSamples[0] : 1;
  871. }
  872. protected void UpdatePipelineAttachmentFormats()
  873. {
  874. var dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan();
  875. FramebufferParams.AttachmentFormats.CopyTo(dstAttachmentFormats);
  876. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex + (FramebufferParams.HasDepthStencil ? 1 : 0);
  877. for (int i = FramebufferParams.AttachmentFormats.Length; i <= maxAttachmentIndex; i++)
  878. {
  879. dstAttachmentFormats[i] = 0;
  880. }
  881. _newState.ColorBlendAttachmentStateCount = (uint)(FramebufferParams.MaxColorAttachmentIndex + 1);
  882. _newState.HasDepthStencil = FramebufferParams.HasDepthStencil;
  883. }
  884. protected unsafe void CreateRenderPass()
  885. {
  886. const int MaxAttachments = Constants.MaxRenderTargets + 1;
  887. AttachmentDescription[] attachmentDescs = null;
  888. var subpass = new SubpassDescription()
  889. {
  890. PipelineBindPoint = PipelineBindPoint.Graphics
  891. };
  892. AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments];
  893. var hasFramebuffer = FramebufferParams != null;
  894. if (hasFramebuffer && FramebufferParams.AttachmentsCount != 0)
  895. {
  896. attachmentDescs = new AttachmentDescription[FramebufferParams.AttachmentsCount];
  897. for (int i = 0; i < FramebufferParams.AttachmentsCount; i++)
  898. {
  899. int bindIndex = FramebufferParams.AttachmentIndices[i];
  900. attachmentDescs[i] = new AttachmentDescription(
  901. 0,
  902. FramebufferParams.AttachmentFormats[i],
  903. TextureStorage.ConvertToSampleCountFlags(FramebufferParams.AttachmentSamples[i]),
  904. AttachmentLoadOp.Load,
  905. AttachmentStoreOp.Store,
  906. AttachmentLoadOp.Load,
  907. AttachmentStoreOp.Store,
  908. ImageLayout.General,
  909. ImageLayout.General);
  910. }
  911. int colorAttachmentsCount = FramebufferParams.ColorAttachmentsCount;
  912. if (colorAttachmentsCount > MaxAttachments - 1)
  913. {
  914. colorAttachmentsCount = MaxAttachments - 1;
  915. }
  916. if (colorAttachmentsCount != 0)
  917. {
  918. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex;
  919. subpass.ColorAttachmentCount = (uint)maxAttachmentIndex + 1;
  920. subpass.PColorAttachments = &attachmentReferences[0];
  921. // Fill with VK_ATTACHMENT_UNUSED to cover any gaps.
  922. for (int i = 0; i <= maxAttachmentIndex; i++)
  923. {
  924. subpass.PColorAttachments[i] = new AttachmentReference(Vk.AttachmentUnused, ImageLayout.Undefined);
  925. }
  926. for (int i = 0; i < colorAttachmentsCount; i++)
  927. {
  928. int bindIndex = FramebufferParams.AttachmentIndices[i];
  929. subpass.PColorAttachments[bindIndex] = new AttachmentReference((uint)i, ImageLayout.General);
  930. }
  931. }
  932. if (FramebufferParams.HasDepthStencil)
  933. {
  934. uint dsIndex = (uint)FramebufferParams.AttachmentsCount - 1;
  935. subpass.PDepthStencilAttachment = &attachmentReferences[MaxAttachments - 1];
  936. *subpass.PDepthStencilAttachment = new AttachmentReference(dsIndex, ImageLayout.General);
  937. }
  938. }
  939. var subpassDependency = new SubpassDependency(
  940. 0,
  941. 0,
  942. PipelineStageFlags.PipelineStageAllGraphicsBit,
  943. PipelineStageFlags.PipelineStageAllGraphicsBit,
  944. AccessFlags.AccessMemoryReadBit | AccessFlags.AccessMemoryWriteBit | AccessFlags.AccessColorAttachmentWriteBit,
  945. AccessFlags.AccessMemoryReadBit | AccessFlags.AccessMemoryWriteBit | AccessFlags.AccessShaderReadBit,
  946. 0);
  947. fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs)
  948. {
  949. var renderPassCreateInfo = new RenderPassCreateInfo()
  950. {
  951. SType = StructureType.RenderPassCreateInfo,
  952. PAttachments = pAttachmentDescs,
  953. AttachmentCount = attachmentDescs != null ? (uint)attachmentDescs.Length : 0,
  954. PSubpasses = &subpass,
  955. SubpassCount = 1,
  956. PDependencies = &subpassDependency,
  957. DependencyCount = 1
  958. };
  959. Gd.Api.CreateRenderPass(Device, renderPassCreateInfo, null, out var renderPass).ThrowOnError();
  960. _renderPass?.Dispose();
  961. _renderPass = new Auto<DisposableRenderPass>(new DisposableRenderPass(Gd.Api, Device, renderPass));
  962. }
  963. EndRenderPass();
  964. _framebuffer?.Dispose();
  965. _framebuffer = hasFramebuffer ? FramebufferParams.Create(Gd.Api, Cbs, _renderPass) : null;
  966. }
  967. protected void SignalStateChange()
  968. {
  969. _stateDirty = true;
  970. }
  971. private void RecreatePipelineIfNeeded(PipelineBindPoint pbp)
  972. {
  973. DynamicState.ReplayIfDirty(Gd.Api, CommandBuffer);
  974. // Commit changes to the support buffer before drawing.
  975. SupportBufferUpdater.Commit();
  976. if (_needsIndexBufferRebind && _indexBufferPattern == null)
  977. {
  978. _indexBuffer.BindIndexBuffer(Gd, Cbs);
  979. _needsIndexBufferRebind = false;
  980. }
  981. if (_needsTransformFeedbackBuffersRebind)
  982. {
  983. PauseTransformFeedbackInternal();
  984. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  985. {
  986. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  987. }
  988. _needsTransformFeedbackBuffersRebind = false;
  989. }
  990. if (_vertexBuffersDirty != 0)
  991. {
  992. while (_vertexBuffersDirty != 0)
  993. {
  994. int i = BitOperations.TrailingZeroCount(_vertexBuffersDirty);
  995. _vertexBuffers[i].BindVertexBuffer(Gd, Cbs, (uint)i, ref _newState);
  996. _vertexBuffersDirty &= ~(1UL << i);
  997. }
  998. }
  999. if (_stateDirty || Pbp != pbp)
  1000. {
  1001. CreatePipeline(pbp);
  1002. _stateDirty = false;
  1003. Pbp = pbp;
  1004. }
  1005. _descriptorSetUpdater.UpdateAndBindDescriptorSets(Cbs, pbp);
  1006. }
  1007. private void CreatePipeline(PipelineBindPoint pbp)
  1008. {
  1009. // We can only create a pipeline if the have the shader stages set.
  1010. if (_newState.Stages != null)
  1011. {
  1012. if (pbp == PipelineBindPoint.Graphics && _renderPass == null)
  1013. {
  1014. CreateRenderPass();
  1015. }
  1016. var pipeline = pbp == PipelineBindPoint.Compute
  1017. ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache)
  1018. : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass.Get(Cbs).Value);
  1019. ulong pipelineHandle = pipeline.GetUnsafe().Value.Handle;
  1020. if (_currentPipelineHandle != pipelineHandle)
  1021. {
  1022. _currentPipelineHandle = pipelineHandle;
  1023. Pipeline = pipeline;
  1024. PauseTransformFeedbackInternal();
  1025. Gd.Api.CmdBindPipeline(CommandBuffer, pbp, Pipeline.Get(Cbs).Value);
  1026. }
  1027. }
  1028. }
  1029. private unsafe void BeginRenderPass()
  1030. {
  1031. if (!_renderPassActive)
  1032. {
  1033. var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height));
  1034. var clearValue = new ClearValue();
  1035. var renderPassBeginInfo = new RenderPassBeginInfo()
  1036. {
  1037. SType = StructureType.RenderPassBeginInfo,
  1038. RenderPass = _renderPass.Get(Cbs).Value,
  1039. Framebuffer = _framebuffer.Get(Cbs).Value,
  1040. RenderArea = renderArea,
  1041. PClearValues = &clearValue,
  1042. ClearValueCount = 1
  1043. };
  1044. Gd.Api.CmdBeginRenderPass(CommandBuffer, renderPassBeginInfo, SubpassContents.Inline);
  1045. _renderPassActive = true;
  1046. }
  1047. }
  1048. public void EndRenderPass()
  1049. {
  1050. if (_renderPassActive)
  1051. {
  1052. PauseTransformFeedbackInternal();
  1053. Gd.Api.CmdEndRenderPass(CommandBuffer);
  1054. SignalRenderPassEnd();
  1055. _renderPassActive = false;
  1056. }
  1057. }
  1058. protected virtual void SignalRenderPassEnd()
  1059. {
  1060. }
  1061. private void PauseTransformFeedbackInternal()
  1062. {
  1063. if (_tfEnabled && _tfActive)
  1064. {
  1065. EndTransformFeedbackInternal();
  1066. _tfActive = false;
  1067. }
  1068. }
  1069. private void ResumeTransformFeedbackInternal()
  1070. {
  1071. if (_tfEnabled && !_tfActive)
  1072. {
  1073. BeginTransformFeedbackInternal();
  1074. _tfActive = true;
  1075. }
  1076. }
  1077. private unsafe void BeginTransformFeedbackInternal()
  1078. {
  1079. Gd.TransformFeedbackApi.CmdBeginTransformFeedback(CommandBuffer, 0, 0, null, null);
  1080. }
  1081. private unsafe void EndTransformFeedbackInternal()
  1082. {
  1083. Gd.TransformFeedbackApi.CmdEndTransformFeedback(CommandBuffer, 0, 0, null, null);
  1084. }
  1085. protected virtual void Dispose(bool disposing)
  1086. {
  1087. if (disposing)
  1088. {
  1089. _renderPass?.Dispose();
  1090. _framebuffer?.Dispose();
  1091. _newState.Dispose();
  1092. _descriptorSetUpdater.Dispose();
  1093. for (int i = 0; i < _vertexBuffers.Length; i++)
  1094. {
  1095. _vertexBuffers[i].Dispose();
  1096. }
  1097. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1098. {
  1099. _transformFeedbackBuffers[i].Dispose();
  1100. }
  1101. Pipeline?.Dispose();
  1102. unsafe
  1103. {
  1104. Gd.Api.DestroyPipelineCache(Device, PipelineCache, null);
  1105. }
  1106. SupportBufferUpdater.Dispose();
  1107. }
  1108. }
  1109. public void Dispose()
  1110. {
  1111. Dispose(true);
  1112. }
  1113. }
  1114. }