Pipeline.cs 49 KB

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