Pipeline.cs 48 KB

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