PipelineBase.cs 44 KB

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