Pipeline.cs 36 KB

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