Pipeline.cs 39 KB

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