Pipeline.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.OpenGL.Image;
  5. using Ryujinx.Graphics.OpenGL.Queries;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.OpenGL
  11. {
  12. class Pipeline : IPipeline, IDisposable
  13. {
  14. internal ulong DrawCount { get; private set; }
  15. private Program _program;
  16. private bool _rasterizerDiscard;
  17. private VertexArray _vertexArray;
  18. private Framebuffer _framebuffer;
  19. private IntPtr _indexBaseOffset;
  20. private DrawElementsType _elementsType;
  21. private PrimitiveType _primitiveType;
  22. private int _stencilFrontMask;
  23. private bool _depthMask;
  24. private int _boundDrawFramebuffer;
  25. private int _boundReadFramebuffer;
  26. private CounterQueueEvent _activeConditionalRender;
  27. private struct Vector4<T>
  28. {
  29. public T X;
  30. public T Y;
  31. public T Z;
  32. public T W;
  33. }
  34. private Vector4<int>[] _fpIsBgra = new Vector4<int>[SupportBuffer.FragmentIsBgraCount];
  35. private Vector4<float>[] _renderScale = new Vector4<float>[65];
  36. private TextureBase _unit0Texture;
  37. private FrontFaceDirection _frontFace;
  38. private ClipOrigin _clipOrigin;
  39. private ClipDepthMode _clipDepthMode;
  40. private readonly uint[] _componentMasks;
  41. private uint _scissorEnables;
  42. private bool _tfEnabled;
  43. private TransformFeedbackPrimitiveType _tfTopology;
  44. private BufferHandle _supportBuffer;
  45. private readonly BufferHandle[] _tfbs;
  46. private readonly BufferRange[] _tfbTargets;
  47. private ColorF _blendConstant;
  48. internal Pipeline()
  49. {
  50. _rasterizerDiscard = false;
  51. _clipOrigin = ClipOrigin.LowerLeft;
  52. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  53. _componentMasks = new uint[Constants.MaxRenderTargets];
  54. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  55. {
  56. _componentMasks[index] = 0xf;
  57. }
  58. var defaultScale = new Vector4<float> { X = 1f, Y = 0f, Z = 0f, W = 0f };
  59. new Span<Vector4<float>>(_renderScale).Fill(defaultScale);
  60. _tfbs = new BufferHandle[Constants.MaxTransformFeedbackBuffers];
  61. _tfbTargets = new BufferRange[Constants.MaxTransformFeedbackBuffers];
  62. }
  63. public void Initialize()
  64. {
  65. _supportBuffer = Buffer.Create(SupportBuffer.RequiredSize);
  66. GL.BindBufferBase(BufferRangeTarget.UniformBuffer, 0, Unsafe.As<BufferHandle, int>(ref _supportBuffer));
  67. SetSupportBufferData<Vector4<int>>(SupportBuffer.FragmentIsBgraOffset, _fpIsBgra, SupportBuffer.FragmentIsBgraCount);
  68. SetSupportBufferData<Vector4<float>>(SupportBuffer.FragmentRenderScaleOffset, _renderScale, SupportBuffer.RenderScaleMaxCount);
  69. }
  70. public void Barrier()
  71. {
  72. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  73. }
  74. public void BeginTransformFeedback(PrimitiveTopology topology)
  75. {
  76. GL.BeginTransformFeedback(_tfTopology = topology.ConvertToTfType());
  77. _tfEnabled = true;
  78. }
  79. public void ClearBuffer(BufferHandle destination, int offset, int size, uint value)
  80. {
  81. Buffer.Clear(destination, offset, size, value);
  82. }
  83. public void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
  84. {
  85. GL.ColorMask(
  86. index,
  87. (componentMask & 1) != 0,
  88. (componentMask & 2) != 0,
  89. (componentMask & 4) != 0,
  90. (componentMask & 8) != 0);
  91. float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
  92. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Color, index, colors);
  93. RestoreComponentMask(index);
  94. }
  95. public void ClearRenderTargetDepthStencil(float depthValue, bool depthMask, int stencilValue, int stencilMask)
  96. {
  97. bool stencilMaskChanged =
  98. stencilMask != 0 &&
  99. stencilMask != _stencilFrontMask;
  100. bool depthMaskChanged = depthMask && depthMask != _depthMask;
  101. if (stencilMaskChanged)
  102. {
  103. GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
  104. }
  105. if (depthMaskChanged)
  106. {
  107. GL.DepthMask(depthMask);
  108. }
  109. if (depthMask && stencilMask != 0)
  110. {
  111. GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
  112. }
  113. else if (depthMask)
  114. {
  115. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Depth, 0, ref depthValue);
  116. }
  117. else if (stencilMask != 0)
  118. {
  119. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Stencil, 0, ref stencilValue);
  120. }
  121. if (stencilMaskChanged)
  122. {
  123. GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
  124. }
  125. if (depthMaskChanged)
  126. {
  127. GL.DepthMask(_depthMask);
  128. }
  129. }
  130. public void CommandBufferBarrier()
  131. {
  132. GL.MemoryBarrier(MemoryBarrierFlags.CommandBarrierBit);
  133. }
  134. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  135. {
  136. Buffer.Copy(source, destination, srcOffset, dstOffset, size);
  137. }
  138. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  139. {
  140. if (!_program.IsLinked)
  141. {
  142. Logger.Debug?.Print(LogClass.Gpu, "Dispatch error, shader not linked.");
  143. return;
  144. }
  145. PrepareForDispatch();
  146. GL.DispatchCompute(groupsX, groupsY, groupsZ);
  147. }
  148. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  149. {
  150. if (!_program.IsLinked)
  151. {
  152. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  153. return;
  154. }
  155. PreDraw();
  156. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  157. {
  158. DrawQuadsImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  159. }
  160. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  161. {
  162. DrawQuadStripImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  163. }
  164. else
  165. {
  166. DrawImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  167. }
  168. PostDraw();
  169. }
  170. private void DrawQuadsImpl(
  171. int vertexCount,
  172. int instanceCount,
  173. int firstVertex,
  174. int firstInstance)
  175. {
  176. // TODO: Instanced rendering.
  177. int quadsCount = vertexCount / 4;
  178. int[] firsts = new int[quadsCount];
  179. int[] counts = new int[quadsCount];
  180. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  181. {
  182. firsts[quadIndex] = firstVertex + quadIndex * 4;
  183. counts[quadIndex] = 4;
  184. }
  185. GL.MultiDrawArrays(
  186. PrimitiveType.TriangleFan,
  187. firsts,
  188. counts,
  189. quadsCount);
  190. }
  191. private void DrawQuadStripImpl(
  192. int vertexCount,
  193. int instanceCount,
  194. int firstVertex,
  195. int firstInstance)
  196. {
  197. int quadsCount = (vertexCount - 2) / 2;
  198. if (firstInstance != 0 || instanceCount != 1)
  199. {
  200. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  201. {
  202. GL.DrawArraysInstancedBaseInstance(PrimitiveType.TriangleFan, firstVertex + quadIndex * 2, 4, instanceCount, firstInstance);
  203. }
  204. }
  205. else
  206. {
  207. int[] firsts = new int[quadsCount];
  208. int[] counts = new int[quadsCount];
  209. firsts[0] = firstVertex;
  210. counts[0] = 4;
  211. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  212. {
  213. firsts[quadIndex] = firstVertex + quadIndex * 2;
  214. counts[quadIndex] = 4;
  215. }
  216. GL.MultiDrawArrays(
  217. PrimitiveType.TriangleFan,
  218. firsts,
  219. counts,
  220. quadsCount);
  221. }
  222. }
  223. private void DrawImpl(
  224. int vertexCount,
  225. int instanceCount,
  226. int firstVertex,
  227. int firstInstance)
  228. {
  229. if (firstInstance == 0 && instanceCount == 1)
  230. {
  231. GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
  232. }
  233. else if (firstInstance == 0)
  234. {
  235. GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
  236. }
  237. else
  238. {
  239. GL.DrawArraysInstancedBaseInstance(
  240. _primitiveType,
  241. firstVertex,
  242. vertexCount,
  243. instanceCount,
  244. firstInstance);
  245. }
  246. }
  247. public void DrawIndexed(
  248. int indexCount,
  249. int instanceCount,
  250. int firstIndex,
  251. int firstVertex,
  252. int firstInstance)
  253. {
  254. if (!_program.IsLinked)
  255. {
  256. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  257. return;
  258. }
  259. PreDraw();
  260. int indexElemSize = 1;
  261. switch (_elementsType)
  262. {
  263. case DrawElementsType.UnsignedShort: indexElemSize = 2; break;
  264. case DrawElementsType.UnsignedInt: indexElemSize = 4; break;
  265. }
  266. IntPtr indexBaseOffset = _indexBaseOffset + firstIndex * indexElemSize;
  267. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  268. {
  269. DrawQuadsIndexedImpl(
  270. indexCount,
  271. instanceCount,
  272. indexBaseOffset,
  273. indexElemSize,
  274. firstVertex,
  275. firstInstance);
  276. }
  277. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  278. {
  279. DrawQuadStripIndexedImpl(
  280. indexCount,
  281. instanceCount,
  282. indexBaseOffset,
  283. indexElemSize,
  284. firstVertex,
  285. firstInstance);
  286. }
  287. else
  288. {
  289. DrawIndexedImpl(
  290. indexCount,
  291. instanceCount,
  292. indexBaseOffset,
  293. firstVertex,
  294. firstInstance);
  295. }
  296. PostDraw();
  297. }
  298. private void DrawQuadsIndexedImpl(
  299. int indexCount,
  300. int instanceCount,
  301. IntPtr indexBaseOffset,
  302. int indexElemSize,
  303. int firstVertex,
  304. int firstInstance)
  305. {
  306. int quadsCount = indexCount / 4;
  307. if (firstInstance != 0 || instanceCount != 1)
  308. {
  309. if (firstVertex != 0 && firstInstance != 0)
  310. {
  311. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  312. {
  313. GL.DrawElementsInstancedBaseVertexBaseInstance(
  314. PrimitiveType.TriangleFan,
  315. 4,
  316. _elementsType,
  317. indexBaseOffset + quadIndex * 4 * indexElemSize,
  318. instanceCount,
  319. firstVertex,
  320. firstInstance);
  321. }
  322. }
  323. else if (firstInstance != 0)
  324. {
  325. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  326. {
  327. GL.DrawElementsInstancedBaseInstance(
  328. PrimitiveType.TriangleFan,
  329. 4,
  330. _elementsType,
  331. indexBaseOffset + quadIndex * 4 * indexElemSize,
  332. instanceCount,
  333. firstInstance);
  334. }
  335. }
  336. else
  337. {
  338. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  339. {
  340. GL.DrawElementsInstanced(
  341. PrimitiveType.TriangleFan,
  342. 4,
  343. _elementsType,
  344. indexBaseOffset + quadIndex * 4 * indexElemSize,
  345. instanceCount);
  346. }
  347. }
  348. }
  349. else
  350. {
  351. IntPtr[] indices = new IntPtr[quadsCount];
  352. int[] counts = new int[quadsCount];
  353. int[] baseVertices = new int[quadsCount];
  354. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  355. {
  356. indices[quadIndex] = indexBaseOffset + quadIndex * 4 * indexElemSize;
  357. counts[quadIndex] = 4;
  358. baseVertices[quadIndex] = firstVertex;
  359. }
  360. GL.MultiDrawElementsBaseVertex(
  361. PrimitiveType.TriangleFan,
  362. counts,
  363. _elementsType,
  364. indices,
  365. quadsCount,
  366. baseVertices);
  367. }
  368. }
  369. private void DrawQuadStripIndexedImpl(
  370. int indexCount,
  371. int instanceCount,
  372. IntPtr indexBaseOffset,
  373. int indexElemSize,
  374. int firstVertex,
  375. int firstInstance)
  376. {
  377. // TODO: Instanced rendering.
  378. int quadsCount = (indexCount - 2) / 2;
  379. IntPtr[] indices = new IntPtr[quadsCount];
  380. int[] counts = new int[quadsCount];
  381. int[] baseVertices = new int[quadsCount];
  382. indices[0] = indexBaseOffset;
  383. counts[0] = 4;
  384. baseVertices[0] = firstVertex;
  385. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  386. {
  387. indices[quadIndex] = indexBaseOffset + quadIndex * 2 * indexElemSize;
  388. counts[quadIndex] = 4;
  389. baseVertices[quadIndex] = firstVertex;
  390. }
  391. GL.MultiDrawElementsBaseVertex(
  392. PrimitiveType.TriangleFan,
  393. counts,
  394. _elementsType,
  395. indices,
  396. quadsCount,
  397. baseVertices);
  398. }
  399. private void DrawIndexedImpl(
  400. int indexCount,
  401. int instanceCount,
  402. IntPtr indexBaseOffset,
  403. int firstVertex,
  404. int firstInstance)
  405. {
  406. if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
  407. {
  408. GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
  409. }
  410. else if (firstInstance == 0 && instanceCount == 1)
  411. {
  412. GL.DrawElementsBaseVertex(
  413. _primitiveType,
  414. indexCount,
  415. _elementsType,
  416. indexBaseOffset,
  417. firstVertex);
  418. }
  419. else if (firstInstance == 0 && firstVertex == 0)
  420. {
  421. GL.DrawElementsInstanced(
  422. _primitiveType,
  423. indexCount,
  424. _elementsType,
  425. indexBaseOffset,
  426. instanceCount);
  427. }
  428. else if (firstInstance == 0)
  429. {
  430. GL.DrawElementsInstancedBaseVertex(
  431. _primitiveType,
  432. indexCount,
  433. _elementsType,
  434. indexBaseOffset,
  435. instanceCount,
  436. firstVertex);
  437. }
  438. else if (firstVertex == 0)
  439. {
  440. GL.DrawElementsInstancedBaseInstance(
  441. _primitiveType,
  442. indexCount,
  443. _elementsType,
  444. indexBaseOffset,
  445. instanceCount,
  446. firstInstance);
  447. }
  448. else
  449. {
  450. GL.DrawElementsInstancedBaseVertexBaseInstance(
  451. _primitiveType,
  452. indexCount,
  453. _elementsType,
  454. indexBaseOffset,
  455. instanceCount,
  456. firstVertex,
  457. firstInstance);
  458. }
  459. }
  460. public void EndTransformFeedback()
  461. {
  462. GL.EndTransformFeedback();
  463. _tfEnabled = false;
  464. }
  465. public void MultiDrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  466. {
  467. if (!_program.IsLinked)
  468. {
  469. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  470. return;
  471. }
  472. PreDraw();
  473. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  474. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  475. GL.MultiDrawArraysIndirectCount(
  476. _primitiveType,
  477. (IntPtr)indirectBuffer.Offset,
  478. (IntPtr)parameterBuffer.Offset,
  479. maxDrawCount,
  480. stride);
  481. PostDraw();
  482. }
  483. public void MultiDrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  484. {
  485. if (!_program.IsLinked)
  486. {
  487. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  488. return;
  489. }
  490. PreDraw();
  491. _vertexArray.SetRangeOfIndexBuffer();
  492. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  493. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  494. GL.MultiDrawElementsIndirectCount(
  495. _primitiveType,
  496. (Version46)_elementsType,
  497. (IntPtr)indirectBuffer.Offset,
  498. (IntPtr)parameterBuffer.Offset,
  499. maxDrawCount,
  500. stride);
  501. _vertexArray.RestoreIndexBuffer();
  502. PostDraw();
  503. }
  504. public void SetAlphaTest(bool enable, float reference, CompareOp op)
  505. {
  506. if (!enable)
  507. {
  508. GL.Disable(EnableCap.AlphaTest);
  509. return;
  510. }
  511. GL.AlphaFunc((AlphaFunction)op.Convert(), reference);
  512. GL.Enable(EnableCap.AlphaTest);
  513. }
  514. public void SetBlendState(int index, BlendDescriptor blend)
  515. {
  516. if (!blend.Enable)
  517. {
  518. GL.Disable(IndexedEnableCap.Blend, index);
  519. return;
  520. }
  521. GL.BlendEquationSeparate(
  522. index,
  523. blend.ColorOp.Convert(),
  524. blend.AlphaOp.Convert());
  525. GL.BlendFuncSeparate(
  526. index,
  527. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  528. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  529. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  530. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  531. static bool IsDualSource(BlendFactor factor)
  532. {
  533. switch (factor)
  534. {
  535. case BlendFactor.Src1Color:
  536. case BlendFactor.Src1ColorGl:
  537. case BlendFactor.Src1Alpha:
  538. case BlendFactor.Src1AlphaGl:
  539. case BlendFactor.OneMinusSrc1Color:
  540. case BlendFactor.OneMinusSrc1ColorGl:
  541. case BlendFactor.OneMinusSrc1Alpha:
  542. case BlendFactor.OneMinusSrc1AlphaGl:
  543. return true;
  544. }
  545. return false;
  546. }
  547. EnsureFramebuffer();
  548. _framebuffer.SetDualSourceBlend(
  549. IsDualSource(blend.ColorSrcFactor) ||
  550. IsDualSource(blend.ColorDstFactor) ||
  551. IsDualSource(blend.AlphaSrcFactor) ||
  552. IsDualSource(blend.AlphaDstFactor));
  553. if (_blendConstant != blend.BlendConstant)
  554. {
  555. _blendConstant = blend.BlendConstant;
  556. GL.BlendColor(
  557. blend.BlendConstant.Red,
  558. blend.BlendConstant.Green,
  559. blend.BlendConstant.Blue,
  560. blend.BlendConstant.Alpha);
  561. }
  562. GL.Enable(IndexedEnableCap.Blend, index);
  563. }
  564. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  565. {
  566. if ((enables & PolygonModeMask.Point) != 0)
  567. {
  568. GL.Enable(EnableCap.PolygonOffsetPoint);
  569. }
  570. else
  571. {
  572. GL.Disable(EnableCap.PolygonOffsetPoint);
  573. }
  574. if ((enables & PolygonModeMask.Line) != 0)
  575. {
  576. GL.Enable(EnableCap.PolygonOffsetLine);
  577. }
  578. else
  579. {
  580. GL.Disable(EnableCap.PolygonOffsetLine);
  581. }
  582. if ((enables & PolygonModeMask.Fill) != 0)
  583. {
  584. GL.Enable(EnableCap.PolygonOffsetFill);
  585. }
  586. else
  587. {
  588. GL.Disable(EnableCap.PolygonOffsetFill);
  589. }
  590. if (enables == 0)
  591. {
  592. return;
  593. }
  594. if (HwCapabilities.SupportsPolygonOffsetClamp)
  595. {
  596. GL.PolygonOffsetClamp(factor, units, clamp);
  597. }
  598. else
  599. {
  600. GL.PolygonOffset(factor, units);
  601. }
  602. }
  603. public void SetDepthClamp(bool clamp)
  604. {
  605. if (!clamp)
  606. {
  607. GL.Disable(EnableCap.DepthClamp);
  608. return;
  609. }
  610. GL.Enable(EnableCap.DepthClamp);
  611. }
  612. public void SetDepthMode(DepthMode mode)
  613. {
  614. ClipDepthMode depthMode = mode.Convert();
  615. if (_clipDepthMode != depthMode)
  616. {
  617. _clipDepthMode = depthMode;
  618. GL.ClipControl(_clipOrigin, depthMode);
  619. }
  620. }
  621. public void SetDepthTest(DepthTestDescriptor depthTest)
  622. {
  623. if (depthTest.TestEnable)
  624. {
  625. GL.Enable(EnableCap.DepthTest);
  626. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  627. }
  628. else
  629. {
  630. GL.Disable(EnableCap.DepthTest);
  631. }
  632. GL.DepthMask(depthTest.WriteEnable);
  633. _depthMask = depthTest.WriteEnable;
  634. }
  635. public void SetFaceCulling(bool enable, Face face)
  636. {
  637. if (!enable)
  638. {
  639. GL.Disable(EnableCap.CullFace);
  640. return;
  641. }
  642. GL.CullFace(face.Convert());
  643. GL.Enable(EnableCap.CullFace);
  644. }
  645. public void SetFrontFace(FrontFace frontFace)
  646. {
  647. SetFrontFace(_frontFace = frontFace.Convert());
  648. }
  649. public void SetImage(int binding, ITexture texture, Format imageFormat)
  650. {
  651. if (texture == null)
  652. {
  653. return;
  654. }
  655. TextureBase texBase = (TextureBase)texture;
  656. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  657. if (format != 0)
  658. {
  659. GL.BindImageTexture(binding, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  660. }
  661. }
  662. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  663. {
  664. _elementsType = type.Convert();
  665. _indexBaseOffset = (IntPtr)buffer.Offset;
  666. EnsureVertexArray();
  667. _vertexArray.SetIndexBuffer(buffer);
  668. }
  669. public void SetLogicOpState(bool enable, LogicalOp op)
  670. {
  671. if (enable)
  672. {
  673. GL.Enable(EnableCap.ColorLogicOp);
  674. GL.LogicOp((LogicOp)op.Convert());
  675. }
  676. else
  677. {
  678. GL.Disable(EnableCap.ColorLogicOp);
  679. }
  680. }
  681. public void SetLineParameters(float width, bool smooth)
  682. {
  683. if (smooth)
  684. {
  685. GL.Enable(EnableCap.LineSmooth);
  686. }
  687. else
  688. {
  689. GL.Disable(EnableCap.LineSmooth);
  690. }
  691. GL.LineWidth(width);
  692. }
  693. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  694. {
  695. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  696. // As we don't know if the current context is core or compat, it's safer to keep this code.
  697. if (enablePointSprite)
  698. {
  699. GL.Enable(EnableCap.PointSprite);
  700. }
  701. else
  702. {
  703. GL.Disable(EnableCap.PointSprite);
  704. }
  705. if (isProgramPointSize)
  706. {
  707. GL.Enable(EnableCap.ProgramPointSize);
  708. }
  709. else
  710. {
  711. GL.Disable(EnableCap.ProgramPointSize);
  712. }
  713. GL.PointParameter(origin == Origin.LowerLeft
  714. ? PointSpriteCoordOriginParameter.LowerLeft
  715. : PointSpriteCoordOriginParameter.UpperLeft);
  716. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  717. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  718. GL.PointSize(Math.Max(float.Epsilon, size));
  719. }
  720. public void SetPrimitiveRestart(bool enable, int index)
  721. {
  722. if (!enable)
  723. {
  724. GL.Disable(EnableCap.PrimitiveRestart);
  725. return;
  726. }
  727. GL.PrimitiveRestartIndex(index);
  728. GL.Enable(EnableCap.PrimitiveRestart);
  729. }
  730. public void SetPrimitiveTopology(PrimitiveTopology topology)
  731. {
  732. _primitiveType = topology.Convert();
  733. }
  734. public void SetProgram(IProgram program)
  735. {
  736. _program = (Program)program;
  737. if (_tfEnabled)
  738. {
  739. GL.EndTransformFeedback();
  740. _program.Bind();
  741. GL.BeginTransformFeedback(_tfTopology);
  742. }
  743. else
  744. {
  745. _program.Bind();
  746. }
  747. }
  748. public void SetRasterizerDiscard(bool discard)
  749. {
  750. if (discard)
  751. {
  752. GL.Enable(EnableCap.RasterizerDiscard);
  753. }
  754. else
  755. {
  756. GL.Disable(EnableCap.RasterizerDiscard);
  757. }
  758. _rasterizerDiscard = discard;
  759. }
  760. public void SetRenderTargetScale(float scale)
  761. {
  762. _renderScale[0].X = scale;
  763. SetSupportBufferData<Vector4<float>>(SupportBuffer.FragmentRenderScaleOffset, _renderScale, 1); // Just the first element.
  764. }
  765. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  766. {
  767. for (int index = 0; index < componentMasks.Length; index++)
  768. {
  769. _componentMasks[index] = componentMasks[index];
  770. RestoreComponentMask(index);
  771. }
  772. }
  773. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  774. {
  775. EnsureFramebuffer();
  776. bool isBgraChanged = false;
  777. for (int index = 0; index < colors.Length; index++)
  778. {
  779. TextureView color = (TextureView)colors[index];
  780. _framebuffer.AttachColor(index, color);
  781. int isBgra = color != null && color.Format.IsBgr() ? 1 : 0;
  782. if (_fpIsBgra[index].X != isBgra)
  783. {
  784. _fpIsBgra[index].X = isBgra;
  785. isBgraChanged = true;
  786. RestoreComponentMask(index);
  787. }
  788. }
  789. if (isBgraChanged)
  790. {
  791. SetSupportBufferData<Vector4<int>>(SupportBuffer.FragmentIsBgraOffset, _fpIsBgra, SupportBuffer.FragmentIsBgraCount);
  792. }
  793. TextureView depthStencilView = (TextureView)depthStencil;
  794. _framebuffer.AttachDepthStencil(depthStencilView);
  795. _framebuffer.SetDrawBuffers(colors.Length);
  796. }
  797. public void SetSampler(int binding, ISampler sampler)
  798. {
  799. if (sampler == null)
  800. {
  801. return;
  802. }
  803. ((Sampler)sampler).Bind(binding);
  804. }
  805. public void SetScissor(int index, bool enable, int x, int y, int width, int height)
  806. {
  807. uint mask = 1u << index;
  808. if (!enable)
  809. {
  810. if ((_scissorEnables & mask) != 0)
  811. {
  812. _scissorEnables &= ~mask;
  813. GL.Disable(IndexedEnableCap.ScissorTest, index);
  814. }
  815. return;
  816. }
  817. if ((_scissorEnables & mask) == 0)
  818. {
  819. _scissorEnables |= mask;
  820. GL.Enable(IndexedEnableCap.ScissorTest, index);
  821. }
  822. GL.ScissorIndexed(index, x, y, width, height);
  823. }
  824. public void SetStencilTest(StencilTestDescriptor stencilTest)
  825. {
  826. if (!stencilTest.TestEnable)
  827. {
  828. GL.Disable(EnableCap.StencilTest);
  829. return;
  830. }
  831. GL.StencilOpSeparate(
  832. StencilFace.Front,
  833. stencilTest.FrontSFail.Convert(),
  834. stencilTest.FrontDpFail.Convert(),
  835. stencilTest.FrontDpPass.Convert());
  836. GL.StencilFuncSeparate(
  837. StencilFace.Front,
  838. (StencilFunction)stencilTest.FrontFunc.Convert(),
  839. stencilTest.FrontFuncRef,
  840. stencilTest.FrontFuncMask);
  841. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  842. GL.StencilOpSeparate(
  843. StencilFace.Back,
  844. stencilTest.BackSFail.Convert(),
  845. stencilTest.BackDpFail.Convert(),
  846. stencilTest.BackDpPass.Convert());
  847. GL.StencilFuncSeparate(
  848. StencilFace.Back,
  849. (StencilFunction)stencilTest.BackFunc.Convert(),
  850. stencilTest.BackFuncRef,
  851. stencilTest.BackFuncMask);
  852. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  853. GL.Enable(EnableCap.StencilTest);
  854. _stencilFrontMask = stencilTest.FrontMask;
  855. }
  856. public void SetStorageBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  857. {
  858. SetBuffers(first, buffers, isStorage: true);
  859. }
  860. public void SetTexture(int binding, ITexture texture)
  861. {
  862. if (texture == null)
  863. {
  864. return;
  865. }
  866. if (binding == 0)
  867. {
  868. _unit0Texture = (TextureBase)texture;
  869. }
  870. else
  871. {
  872. ((TextureBase)texture).Bind(binding);
  873. }
  874. }
  875. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  876. {
  877. if (_tfEnabled)
  878. {
  879. GL.EndTransformFeedback();
  880. }
  881. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  882. for (int i = 0; i < count; i++)
  883. {
  884. BufferRange buffer = buffers[i];
  885. _tfbTargets[i] = buffer;
  886. if (buffer.Handle == BufferHandle.Null)
  887. {
  888. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  889. continue;
  890. }
  891. if (_tfbs[i] == BufferHandle.Null)
  892. {
  893. _tfbs[i] = Buffer.Create();
  894. }
  895. Buffer.Resize(_tfbs[i], buffer.Size);
  896. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  897. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  898. }
  899. if (_tfEnabled)
  900. {
  901. GL.BeginTransformFeedback(_tfTopology);
  902. }
  903. }
  904. public void SetUniformBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  905. {
  906. SetBuffers(first, buffers, isStorage: false);
  907. }
  908. public void SetUserClipDistance(int index, bool enableClip)
  909. {
  910. if (!enableClip)
  911. {
  912. GL.Disable(EnableCap.ClipDistance0 + index);
  913. return;
  914. }
  915. GL.Enable(EnableCap.ClipDistance0 + index);
  916. }
  917. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  918. {
  919. EnsureVertexArray();
  920. _vertexArray.SetVertexAttributes(vertexAttribs);
  921. }
  922. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  923. {
  924. EnsureVertexArray();
  925. _vertexArray.SetVertexBuffers(vertexBuffers);
  926. }
  927. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  928. {
  929. float[] viewportArray = new float[viewports.Length * 4];
  930. double[] depthRangeArray = new double[viewports.Length * 2];
  931. for (int index = 0; index < viewports.Length; index++)
  932. {
  933. int viewportElemIndex = index * 4;
  934. Viewport viewport = viewports[index];
  935. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  936. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  937. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  938. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  939. if (HwCapabilities.SupportsViewportSwizzle)
  940. {
  941. GL.NV.ViewportSwizzle(
  942. index,
  943. viewport.SwizzleX.Convert(),
  944. viewport.SwizzleY.Convert(),
  945. viewport.SwizzleZ.Convert(),
  946. viewport.SwizzleW.Convert());
  947. }
  948. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  949. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  950. }
  951. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  952. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  953. GL.ViewportArray(first, viewports.Length, viewportArray);
  954. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  955. }
  956. public void TextureBarrier()
  957. {
  958. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  959. }
  960. public void TextureBarrierTiled()
  961. {
  962. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  963. }
  964. private void SetBuffers(int first, ReadOnlySpan<BufferRange> buffers, bool isStorage)
  965. {
  966. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  967. for (int index = 0; index < buffers.Length; index++)
  968. {
  969. BufferRange buffer = buffers[index];
  970. if (buffer.Handle == BufferHandle.Null)
  971. {
  972. GL.BindBufferRange(target, first + index, 0, IntPtr.Zero, 0);
  973. continue;
  974. }
  975. GL.BindBufferRange(target, first + index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  976. }
  977. }
  978. private void SetOrigin(ClipOrigin origin)
  979. {
  980. if (_clipOrigin != origin)
  981. {
  982. _clipOrigin = origin;
  983. GL.ClipControl(origin, _clipDepthMode);
  984. SetFrontFace(_frontFace);
  985. }
  986. }
  987. private void SetFrontFace(FrontFaceDirection frontFace)
  988. {
  989. // Changing clip origin will also change the front face to compensate
  990. // for the flipped viewport, we flip it again here to compensate as
  991. // this effect is undesirable for us.
  992. if (_clipOrigin == ClipOrigin.UpperLeft)
  993. {
  994. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  995. }
  996. GL.FrontFace(frontFace);
  997. }
  998. private void EnsureVertexArray()
  999. {
  1000. if (_vertexArray == null)
  1001. {
  1002. _vertexArray = new VertexArray();
  1003. _vertexArray.Bind();
  1004. }
  1005. }
  1006. private void EnsureFramebuffer()
  1007. {
  1008. if (_framebuffer == null)
  1009. {
  1010. _framebuffer = new Framebuffer();
  1011. int boundHandle = _framebuffer.Bind();
  1012. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  1013. GL.Enable(EnableCap.FramebufferSrgb);
  1014. }
  1015. }
  1016. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  1017. {
  1018. if (BackgroundContextWorker.InBackground)
  1019. {
  1020. return (0, 0);
  1021. }
  1022. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  1023. }
  1024. public void UpdateRenderScale(ShaderStage stage, ReadOnlySpan<float> scales, int textureCount, int imageCount)
  1025. {
  1026. if (stage != ShaderStage.Compute && stage != ShaderStage.Fragment)
  1027. {
  1028. return;
  1029. }
  1030. bool changed = false;
  1031. for (int index = 0; index < textureCount + imageCount; index++)
  1032. {
  1033. if (_renderScale[1 + index].X != scales[index])
  1034. {
  1035. _renderScale[1 + index].X = scales[index];
  1036. changed = true;
  1037. }
  1038. }
  1039. if (changed)
  1040. {
  1041. SetSupportBufferData<Vector4<float>>(SupportBuffer.FragmentRenderScaleOffset, _renderScale, 1 + textureCount + imageCount);
  1042. }
  1043. }
  1044. private void SetSupportBufferData<T>(int offset, ReadOnlySpan<T> data, int count) where T : unmanaged
  1045. {
  1046. Buffer.SetData(_supportBuffer, offset, MemoryMarshal.Cast<T, byte>(data.Slice(0, count)));
  1047. }
  1048. private void PrepareForDispatch()
  1049. {
  1050. if (_unit0Texture != null)
  1051. {
  1052. _unit0Texture.Bind(0);
  1053. }
  1054. }
  1055. private void PreDraw()
  1056. {
  1057. DrawCount++;
  1058. _vertexArray.Validate();
  1059. if (_unit0Texture != null)
  1060. {
  1061. _unit0Texture.Bind(0);
  1062. }
  1063. }
  1064. private void PostDraw()
  1065. {
  1066. if (_tfEnabled)
  1067. {
  1068. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1069. {
  1070. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1071. {
  1072. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1073. }
  1074. }
  1075. }
  1076. }
  1077. public void RestoreComponentMask(int index)
  1078. {
  1079. // If the bound render target is bgra, swap the red and blue masks.
  1080. uint redMask = _fpIsBgra[index].X == 0 ? 1u : 4u;
  1081. uint blueMask = _fpIsBgra[index].X == 0 ? 4u : 1u;
  1082. GL.ColorMask(
  1083. index,
  1084. (_componentMasks[index] & redMask) != 0,
  1085. (_componentMasks[index] & 2u) != 0,
  1086. (_componentMasks[index] & blueMask) != 0,
  1087. (_componentMasks[index] & 8u) != 0);
  1088. }
  1089. public void RestoreScissor0Enable()
  1090. {
  1091. if ((_scissorEnables & 1u) != 0)
  1092. {
  1093. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1094. }
  1095. }
  1096. public void RestoreRasterizerDiscard()
  1097. {
  1098. if (_rasterizerDiscard)
  1099. {
  1100. GL.Enable(EnableCap.RasterizerDiscard);
  1101. }
  1102. }
  1103. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1104. {
  1105. if (value is CounterQueueEvent)
  1106. {
  1107. // Compare an event and a constant value.
  1108. CounterQueueEvent evt = (CounterQueueEvent)value;
  1109. // Easy host conditional rendering when the check matches what GL can do:
  1110. // - Event is of type samples passed.
  1111. // - Result is not a combination of multiple queries.
  1112. // - Comparing against 0.
  1113. // - Event has not already been flushed.
  1114. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1115. {
  1116. if (!value.ReserveForHostAccess())
  1117. {
  1118. // If the event has been flushed, then just use the values on the CPU.
  1119. // The query object may already be repurposed for another draw (eg. begin + end).
  1120. return false;
  1121. }
  1122. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1123. _activeConditionalRender = evt;
  1124. return true;
  1125. }
  1126. }
  1127. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1128. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1129. return false;
  1130. }
  1131. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1132. {
  1133. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1134. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1135. }
  1136. public void EndHostConditionalRendering()
  1137. {
  1138. GL.EndConditionalRender();
  1139. _activeConditionalRender?.ReleaseHostAccess();
  1140. _activeConditionalRender = null;
  1141. }
  1142. public void Dispose()
  1143. {
  1144. if (_supportBuffer != BufferHandle.Null)
  1145. {
  1146. Buffer.Delete(_supportBuffer);
  1147. _supportBuffer = BufferHandle.Null;
  1148. }
  1149. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1150. {
  1151. if (_tfbs[i] != BufferHandle.Null)
  1152. {
  1153. Buffer.Delete(_tfbs[i]);
  1154. _tfbs[i] = BufferHandle.Null;
  1155. }
  1156. }
  1157. _activeConditionalRender?.ReleaseHostAccess();
  1158. _framebuffer?.Dispose();
  1159. _vertexArray?.Dispose();
  1160. }
  1161. }
  1162. }