Pipeline.cs 37 KB

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