Pipeline.cs 40 KB

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