Pipeline.cs 41 KB

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