PipelineBase.cs 50 KB

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