Pipeline.cs 38 KB

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