PipelineBase.cs 50 KB

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