Pipeline.cs 42 KB

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