Pipeline.cs 40 KB

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