Pipeline.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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. GL.ClipControl(ClipOrigin.UpperLeft, ClipDepthMode.NegativeOneToOne);
  508. _drawTexture.Draw(
  509. view,
  510. samp,
  511. dstRegion.X1,
  512. dstRegion.Y1,
  513. dstRegion.X2,
  514. dstRegion.Y2,
  515. srcRegion.X1 / view.Width,
  516. srcRegion.Y1 / view.Height,
  517. srcRegion.X2 / view.Width,
  518. srcRegion.Y2 / view.Height);
  519. _program?.Bind();
  520. _unit0Sampler?.Bind(0);
  521. RestoreViewport0();
  522. Enable(EnableCap.CullFace, _cullEnable);
  523. Enable(EnableCap.StencilTest, _stencilTestEnable);
  524. Enable(EnableCap.DepthTest, _depthTestEnable);
  525. if (_depthMask)
  526. {
  527. GL.DepthMask(true);
  528. }
  529. if (_tfEnabled)
  530. {
  531. GL.BeginTransformFeedback(_tfTopology);
  532. }
  533. RestoreClipControl();
  534. }
  535. }
  536. }
  537. public void EndTransformFeedback()
  538. {
  539. GL.EndTransformFeedback();
  540. _tfEnabled = false;
  541. }
  542. public void MultiDrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  543. {
  544. if (!_program.IsLinked)
  545. {
  546. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  547. return;
  548. }
  549. PreDraw();
  550. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  551. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  552. GL.MultiDrawArraysIndirectCount(
  553. _primitiveType,
  554. (IntPtr)indirectBuffer.Offset,
  555. (IntPtr)parameterBuffer.Offset,
  556. maxDrawCount,
  557. stride);
  558. PostDraw();
  559. }
  560. public void MultiDrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  561. {
  562. if (!_program.IsLinked)
  563. {
  564. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  565. return;
  566. }
  567. PreDraw();
  568. _vertexArray.SetRangeOfIndexBuffer();
  569. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  570. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  571. GL.MultiDrawElementsIndirectCount(
  572. _primitiveType,
  573. (All)_elementsType,
  574. (IntPtr)indirectBuffer.Offset,
  575. (IntPtr)parameterBuffer.Offset,
  576. maxDrawCount,
  577. stride);
  578. _vertexArray.RestoreIndexBuffer();
  579. PostDraw();
  580. }
  581. public void SetAlphaTest(bool enable, float reference, CompareOp op)
  582. {
  583. if (!enable)
  584. {
  585. GL.Disable(EnableCap.AlphaTest);
  586. return;
  587. }
  588. GL.AlphaFunc((AlphaFunction)op.Convert(), reference);
  589. GL.Enable(EnableCap.AlphaTest);
  590. }
  591. public void SetBlendState(int index, BlendDescriptor blend)
  592. {
  593. if (!blend.Enable)
  594. {
  595. GL.Disable(IndexedEnableCap.Blend, index);
  596. return;
  597. }
  598. GL.BlendEquationSeparate(
  599. index,
  600. blend.ColorOp.Convert(),
  601. blend.AlphaOp.Convert());
  602. GL.BlendFuncSeparate(
  603. index,
  604. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  605. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  606. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  607. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  608. static bool IsDualSource(BlendFactor factor)
  609. {
  610. switch (factor)
  611. {
  612. case BlendFactor.Src1Color:
  613. case BlendFactor.Src1ColorGl:
  614. case BlendFactor.Src1Alpha:
  615. case BlendFactor.Src1AlphaGl:
  616. case BlendFactor.OneMinusSrc1Color:
  617. case BlendFactor.OneMinusSrc1ColorGl:
  618. case BlendFactor.OneMinusSrc1Alpha:
  619. case BlendFactor.OneMinusSrc1AlphaGl:
  620. return true;
  621. }
  622. return false;
  623. }
  624. EnsureFramebuffer();
  625. _framebuffer.SetDualSourceBlend(
  626. IsDualSource(blend.ColorSrcFactor) ||
  627. IsDualSource(blend.ColorDstFactor) ||
  628. IsDualSource(blend.AlphaSrcFactor) ||
  629. IsDualSource(blend.AlphaDstFactor));
  630. if (_blendConstant != blend.BlendConstant)
  631. {
  632. _blendConstant = blend.BlendConstant;
  633. GL.BlendColor(
  634. blend.BlendConstant.Red,
  635. blend.BlendConstant.Green,
  636. blend.BlendConstant.Blue,
  637. blend.BlendConstant.Alpha);
  638. }
  639. GL.Enable(IndexedEnableCap.Blend, index);
  640. }
  641. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  642. {
  643. if ((enables & PolygonModeMask.Point) != 0)
  644. {
  645. GL.Enable(EnableCap.PolygonOffsetPoint);
  646. }
  647. else
  648. {
  649. GL.Disable(EnableCap.PolygonOffsetPoint);
  650. }
  651. if ((enables & PolygonModeMask.Line) != 0)
  652. {
  653. GL.Enable(EnableCap.PolygonOffsetLine);
  654. }
  655. else
  656. {
  657. GL.Disable(EnableCap.PolygonOffsetLine);
  658. }
  659. if ((enables & PolygonModeMask.Fill) != 0)
  660. {
  661. GL.Enable(EnableCap.PolygonOffsetFill);
  662. }
  663. else
  664. {
  665. GL.Disable(EnableCap.PolygonOffsetFill);
  666. }
  667. if (enables == 0)
  668. {
  669. return;
  670. }
  671. if (HwCapabilities.SupportsPolygonOffsetClamp)
  672. {
  673. GL.PolygonOffsetClamp(factor, units, clamp);
  674. }
  675. else
  676. {
  677. GL.PolygonOffset(factor, units);
  678. }
  679. }
  680. public void SetDepthClamp(bool clamp)
  681. {
  682. if (!clamp)
  683. {
  684. GL.Disable(EnableCap.DepthClamp);
  685. return;
  686. }
  687. GL.Enable(EnableCap.DepthClamp);
  688. }
  689. public void SetDepthMode(DepthMode mode)
  690. {
  691. ClipDepthMode depthMode = mode.Convert();
  692. if (_clipDepthMode != depthMode)
  693. {
  694. _clipDepthMode = depthMode;
  695. GL.ClipControl(_clipOrigin, depthMode);
  696. }
  697. }
  698. public void SetDepthTest(DepthTestDescriptor depthTest)
  699. {
  700. if (depthTest.TestEnable)
  701. {
  702. GL.Enable(EnableCap.DepthTest);
  703. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  704. }
  705. else
  706. {
  707. GL.Disable(EnableCap.DepthTest);
  708. }
  709. GL.DepthMask(depthTest.WriteEnable);
  710. _depthMask = depthTest.WriteEnable;
  711. _depthTestEnable = depthTest.TestEnable;
  712. }
  713. public void SetFaceCulling(bool enable, Face face)
  714. {
  715. _cullEnable = enable;
  716. if (!enable)
  717. {
  718. GL.Disable(EnableCap.CullFace);
  719. return;
  720. }
  721. GL.CullFace(face.Convert());
  722. GL.Enable(EnableCap.CullFace);
  723. }
  724. public void SetFrontFace(FrontFace frontFace)
  725. {
  726. SetFrontFace(_frontFace = frontFace.Convert());
  727. }
  728. public void SetImage(int binding, ITexture texture, Format imageFormat)
  729. {
  730. if (texture == null)
  731. {
  732. return;
  733. }
  734. TextureBase texBase = (TextureBase)texture;
  735. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  736. if (format != 0)
  737. {
  738. GL.BindImageTexture(binding, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  739. }
  740. }
  741. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  742. {
  743. _elementsType = type.Convert();
  744. _indexBaseOffset = (IntPtr)buffer.Offset;
  745. EnsureVertexArray();
  746. _vertexArray.SetIndexBuffer(buffer);
  747. }
  748. public void SetLogicOpState(bool enable, LogicalOp op)
  749. {
  750. if (enable)
  751. {
  752. GL.Enable(EnableCap.ColorLogicOp);
  753. GL.LogicOp((LogicOp)op.Convert());
  754. }
  755. else
  756. {
  757. GL.Disable(EnableCap.ColorLogicOp);
  758. }
  759. }
  760. public void SetLineParameters(float width, bool smooth)
  761. {
  762. if (smooth)
  763. {
  764. GL.Enable(EnableCap.LineSmooth);
  765. }
  766. else
  767. {
  768. GL.Disable(EnableCap.LineSmooth);
  769. }
  770. GL.LineWidth(width);
  771. }
  772. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  773. {
  774. GL.PatchParameter(PatchParameterInt.PatchVertices, vertices);
  775. fixed (float* pOuterLevel = defaultOuterLevel)
  776. {
  777. GL.PatchParameter(PatchParameterFloat.PatchDefaultOuterLevel, pOuterLevel);
  778. }
  779. fixed (float* pInnerLevel = defaultInnerLevel)
  780. {
  781. GL.PatchParameter(PatchParameterFloat.PatchDefaultInnerLevel, pInnerLevel);
  782. }
  783. }
  784. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  785. {
  786. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  787. // As we don't know if the current context is core or compat, it's safer to keep this code.
  788. if (enablePointSprite)
  789. {
  790. GL.Enable(EnableCap.PointSprite);
  791. }
  792. else
  793. {
  794. GL.Disable(EnableCap.PointSprite);
  795. }
  796. if (isProgramPointSize)
  797. {
  798. GL.Enable(EnableCap.ProgramPointSize);
  799. }
  800. else
  801. {
  802. GL.Disable(EnableCap.ProgramPointSize);
  803. }
  804. GL.PointParameter(origin == Origin.LowerLeft
  805. ? PointSpriteCoordOriginParameter.LowerLeft
  806. : PointSpriteCoordOriginParameter.UpperLeft);
  807. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  808. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  809. GL.PointSize(Math.Max(float.Epsilon, size));
  810. }
  811. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  812. {
  813. if (frontMode == backMode)
  814. {
  815. GL.PolygonMode(MaterialFace.FrontAndBack, frontMode.Convert());
  816. }
  817. else
  818. {
  819. GL.PolygonMode(MaterialFace.Front, frontMode.Convert());
  820. GL.PolygonMode(MaterialFace.Back, backMode.Convert());
  821. }
  822. }
  823. public void SetPrimitiveRestart(bool enable, int index)
  824. {
  825. if (!enable)
  826. {
  827. GL.Disable(EnableCap.PrimitiveRestart);
  828. return;
  829. }
  830. GL.PrimitiveRestartIndex(index);
  831. GL.Enable(EnableCap.PrimitiveRestart);
  832. }
  833. public void SetPrimitiveTopology(PrimitiveTopology topology)
  834. {
  835. _primitiveType = topology.Convert();
  836. }
  837. public void SetProgram(IProgram program)
  838. {
  839. Program prg = (Program)program;
  840. if (_tfEnabled)
  841. {
  842. GL.EndTransformFeedback();
  843. prg.Bind();
  844. GL.BeginTransformFeedback(_tfTopology);
  845. }
  846. else
  847. {
  848. prg.Bind();
  849. }
  850. if (prg.HasFragmentShader && _fragmentOutputMap != (uint)prg.FragmentOutputMap)
  851. {
  852. _fragmentOutputMap = (uint)prg.FragmentOutputMap;
  853. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  854. {
  855. RestoreComponentMask(index, force: false);
  856. }
  857. }
  858. _program = prg;
  859. }
  860. public void SetRasterizerDiscard(bool discard)
  861. {
  862. if (discard)
  863. {
  864. GL.Enable(EnableCap.RasterizerDiscard);
  865. }
  866. else
  867. {
  868. GL.Disable(EnableCap.RasterizerDiscard);
  869. }
  870. _rasterizerDiscard = discard;
  871. }
  872. public void SetRenderTargetScale(float scale)
  873. {
  874. _renderScale[0].X = scale;
  875. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  876. }
  877. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  878. {
  879. _componentMasks = 0;
  880. for (int index = 0; index < componentMasks.Length; index++)
  881. {
  882. _componentMasks |= componentMasks[index] << (index * 4);
  883. RestoreComponentMask(index, force: false);
  884. }
  885. }
  886. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  887. {
  888. EnsureFramebuffer();
  889. bool isBgraChanged = false;
  890. for (int index = 0; index < colors.Length; index++)
  891. {
  892. TextureView color = (TextureView)colors[index];
  893. _framebuffer.AttachColor(index, color);
  894. if (color != null)
  895. {
  896. int isBgra = color.Format.IsBgr() ? 1 : 0;
  897. if (_fpIsBgra[index].X != isBgra)
  898. {
  899. _fpIsBgra[index].X = isBgra;
  900. isBgraChanged = true;
  901. RestoreComponentMask(index);
  902. }
  903. }
  904. }
  905. if (isBgraChanged)
  906. {
  907. _supportBuffer.UpdateFragmentIsBgra(_fpIsBgra, 0, SupportBuffer.FragmentIsBgraCount);
  908. }
  909. TextureView depthStencilView = (TextureView)depthStencil;
  910. _framebuffer.AttachDepthStencil(depthStencilView);
  911. _framebuffer.SetDrawBuffers(colors.Length);
  912. }
  913. public void SetSampler(int binding, ISampler sampler)
  914. {
  915. if (sampler == null)
  916. {
  917. return;
  918. }
  919. Sampler samp = (Sampler)sampler;
  920. if (binding == 0)
  921. {
  922. _unit0Sampler = samp;
  923. }
  924. samp.Bind(binding);
  925. }
  926. public void SetScissor(int index, bool enable, int x, int y, int width, int height)
  927. {
  928. uint mask = 1u << index;
  929. if (!enable)
  930. {
  931. if ((_scissorEnables & mask) != 0)
  932. {
  933. _scissorEnables &= ~mask;
  934. GL.Disable(IndexedEnableCap.ScissorTest, index);
  935. }
  936. return;
  937. }
  938. if ((_scissorEnables & mask) == 0)
  939. {
  940. _scissorEnables |= mask;
  941. GL.Enable(IndexedEnableCap.ScissorTest, index);
  942. }
  943. GL.ScissorIndexed(index, x, y, width, height);
  944. }
  945. public void SetStencilTest(StencilTestDescriptor stencilTest)
  946. {
  947. _stencilTestEnable = stencilTest.TestEnable;
  948. if (!stencilTest.TestEnable)
  949. {
  950. GL.Disable(EnableCap.StencilTest);
  951. return;
  952. }
  953. GL.StencilOpSeparate(
  954. StencilFace.Front,
  955. stencilTest.FrontSFail.Convert(),
  956. stencilTest.FrontDpFail.Convert(),
  957. stencilTest.FrontDpPass.Convert());
  958. GL.StencilFuncSeparate(
  959. StencilFace.Front,
  960. (StencilFunction)stencilTest.FrontFunc.Convert(),
  961. stencilTest.FrontFuncRef,
  962. stencilTest.FrontFuncMask);
  963. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  964. GL.StencilOpSeparate(
  965. StencilFace.Back,
  966. stencilTest.BackSFail.Convert(),
  967. stencilTest.BackDpFail.Convert(),
  968. stencilTest.BackDpPass.Convert());
  969. GL.StencilFuncSeparate(
  970. StencilFace.Back,
  971. (StencilFunction)stencilTest.BackFunc.Convert(),
  972. stencilTest.BackFuncRef,
  973. stencilTest.BackFuncMask);
  974. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  975. GL.Enable(EnableCap.StencilTest);
  976. _stencilFrontMask = stencilTest.FrontMask;
  977. }
  978. public void SetStorageBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  979. {
  980. SetBuffers(first, buffers, isStorage: true);
  981. }
  982. public void SetTexture(int binding, ITexture texture)
  983. {
  984. if (texture == null)
  985. {
  986. return;
  987. }
  988. if (binding == 0)
  989. {
  990. _unit0Texture = (TextureBase)texture;
  991. }
  992. else
  993. {
  994. ((TextureBase)texture).Bind(binding);
  995. }
  996. }
  997. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  998. {
  999. if (_tfEnabled)
  1000. {
  1001. GL.EndTransformFeedback();
  1002. }
  1003. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  1004. for (int i = 0; i < count; i++)
  1005. {
  1006. BufferRange buffer = buffers[i];
  1007. _tfbTargets[i] = buffer;
  1008. if (buffer.Handle == BufferHandle.Null)
  1009. {
  1010. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  1011. continue;
  1012. }
  1013. if (_tfbs[i] == BufferHandle.Null)
  1014. {
  1015. _tfbs[i] = Buffer.Create();
  1016. }
  1017. Buffer.Resize(_tfbs[i], buffer.Size);
  1018. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  1019. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  1020. }
  1021. if (_tfEnabled)
  1022. {
  1023. GL.BeginTransformFeedback(_tfTopology);
  1024. }
  1025. }
  1026. public void SetUniformBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  1027. {
  1028. SetBuffers(first, buffers, isStorage: false);
  1029. }
  1030. public void SetUserClipDistance(int index, bool enableClip)
  1031. {
  1032. if (!enableClip)
  1033. {
  1034. GL.Disable(EnableCap.ClipDistance0 + index);
  1035. return;
  1036. }
  1037. GL.Enable(EnableCap.ClipDistance0 + index);
  1038. }
  1039. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  1040. {
  1041. EnsureVertexArray();
  1042. _vertexArray.SetVertexAttributes(vertexAttribs);
  1043. }
  1044. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  1045. {
  1046. EnsureVertexArray();
  1047. _vertexArray.SetVertexBuffers(vertexBuffers);
  1048. }
  1049. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports, bool disableTransform)
  1050. {
  1051. Array.Resize(ref _viewportArray, viewports.Length * 4);
  1052. Array.Resize(ref _depthRangeArray, viewports.Length * 2);
  1053. float[] viewportArray = _viewportArray;
  1054. double[] depthRangeArray = _depthRangeArray;
  1055. for (int index = 0; index < viewports.Length; index++)
  1056. {
  1057. int viewportElemIndex = index * 4;
  1058. Viewport viewport = viewports[index];
  1059. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  1060. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  1061. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  1062. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  1063. if (HwCapabilities.SupportsViewportSwizzle)
  1064. {
  1065. GL.NV.ViewportSwizzle(
  1066. index,
  1067. viewport.SwizzleX.Convert(),
  1068. viewport.SwizzleY.Convert(),
  1069. viewport.SwizzleZ.Convert(),
  1070. viewport.SwizzleW.Convert());
  1071. }
  1072. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  1073. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  1074. }
  1075. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  1076. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  1077. GL.ViewportArray(first, viewports.Length, viewportArray);
  1078. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  1079. float disableTransformF = disableTransform ? 1.0f : 0.0f;
  1080. if (_supportBuffer.Data.ViewportInverse.W != disableTransformF || disableTransform)
  1081. {
  1082. float scale = _renderScale[0].X;
  1083. _supportBuffer.UpdateViewportInverse(new Vector4<float>
  1084. {
  1085. X = scale * 2f / viewports[first].Region.Width,
  1086. Y = scale * 2f / viewports[first].Region.Height,
  1087. Z = 1,
  1088. W = disableTransformF
  1089. });
  1090. }
  1091. }
  1092. public void TextureBarrier()
  1093. {
  1094. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1095. }
  1096. public void TextureBarrierTiled()
  1097. {
  1098. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1099. }
  1100. private void SetBuffers(int first, ReadOnlySpan<BufferRange> buffers, bool isStorage)
  1101. {
  1102. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  1103. for (int index = 0; index < buffers.Length; index++)
  1104. {
  1105. BufferRange buffer = buffers[index];
  1106. if (buffer.Handle == BufferHandle.Null)
  1107. {
  1108. GL.BindBufferRange(target, first + index, 0, IntPtr.Zero, 0);
  1109. continue;
  1110. }
  1111. GL.BindBufferRange(target, first + index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  1112. }
  1113. }
  1114. private void SetOrigin(ClipOrigin origin)
  1115. {
  1116. if (_clipOrigin != origin)
  1117. {
  1118. _clipOrigin = origin;
  1119. GL.ClipControl(origin, _clipDepthMode);
  1120. SetFrontFace(_frontFace);
  1121. }
  1122. }
  1123. private void SetFrontFace(FrontFaceDirection frontFace)
  1124. {
  1125. // Changing clip origin will also change the front face to compensate
  1126. // for the flipped viewport, we flip it again here to compensate as
  1127. // this effect is undesirable for us.
  1128. if (_clipOrigin == ClipOrigin.UpperLeft)
  1129. {
  1130. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  1131. }
  1132. GL.FrontFace(frontFace);
  1133. }
  1134. private void EnsureVertexArray()
  1135. {
  1136. if (_vertexArray == null)
  1137. {
  1138. _vertexArray = new VertexArray();
  1139. _vertexArray.Bind();
  1140. }
  1141. }
  1142. private void EnsureFramebuffer()
  1143. {
  1144. if (_framebuffer == null)
  1145. {
  1146. _framebuffer = new Framebuffer();
  1147. int boundHandle = _framebuffer.Bind();
  1148. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  1149. GL.Enable(EnableCap.FramebufferSrgb);
  1150. }
  1151. }
  1152. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  1153. {
  1154. if (BackgroundContextWorker.InBackground)
  1155. {
  1156. return (0, 0);
  1157. }
  1158. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  1159. }
  1160. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  1161. {
  1162. bool changed = false;
  1163. for (int index = 0; index < totalCount; index++)
  1164. {
  1165. if (_renderScale[1 + index].X != scales[index])
  1166. {
  1167. _renderScale[1 + index].X = scales[index];
  1168. changed = true;
  1169. }
  1170. }
  1171. // Only update fragment count if there are scales after it for the vertex stage.
  1172. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  1173. {
  1174. _fragmentScaleCount = fragmentCount;
  1175. _supportBuffer.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  1176. }
  1177. if (changed)
  1178. {
  1179. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  1180. }
  1181. }
  1182. private void PrepareForDispatch()
  1183. {
  1184. _unit0Texture?.Bind(0);
  1185. _supportBuffer.Commit();
  1186. }
  1187. private void PreDraw()
  1188. {
  1189. DrawCount++;
  1190. _vertexArray.Validate();
  1191. _unit0Texture?.Bind(0);
  1192. _supportBuffer.Commit();
  1193. }
  1194. private void PostDraw()
  1195. {
  1196. if (_tfEnabled)
  1197. {
  1198. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1199. {
  1200. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1201. {
  1202. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. public void RestoreComponentMask(int index, bool force = true)
  1208. {
  1209. // If the bound render target is bgra, swap the red and blue masks.
  1210. uint redMask = _fpIsBgra[index].X == 0 ? 1u : 4u;
  1211. uint blueMask = _fpIsBgra[index].X == 0 ? 4u : 1u;
  1212. int shift = index * 4;
  1213. uint componentMask = _componentMasks & _fragmentOutputMap;
  1214. uint checkMask = 0xfu << shift;
  1215. uint componentMaskAtIndex = componentMask & checkMask;
  1216. if (!force && componentMaskAtIndex == (_currentComponentMasks & checkMask))
  1217. {
  1218. return;
  1219. }
  1220. componentMask >>= shift;
  1221. componentMask &= 0xfu;
  1222. GL.ColorMask(
  1223. index,
  1224. (componentMask & redMask) != 0,
  1225. (componentMask & 2u) != 0,
  1226. (componentMask & blueMask) != 0,
  1227. (componentMask & 8u) != 0);
  1228. _currentComponentMasks &= ~checkMask;
  1229. _currentComponentMasks |= componentMaskAtIndex;
  1230. }
  1231. public void RestoreClipControl()
  1232. {
  1233. GL.ClipControl(_clipOrigin, _clipDepthMode);
  1234. }
  1235. public void RestoreScissor0Enable()
  1236. {
  1237. if ((_scissorEnables & 1u) != 0)
  1238. {
  1239. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1240. }
  1241. }
  1242. public void RestoreRasterizerDiscard()
  1243. {
  1244. if (_rasterizerDiscard)
  1245. {
  1246. GL.Enable(EnableCap.RasterizerDiscard);
  1247. }
  1248. }
  1249. public void RestoreViewport0()
  1250. {
  1251. if (_viewportArray.Length > 0)
  1252. {
  1253. GL.ViewportArray(0, 1, _viewportArray);
  1254. }
  1255. }
  1256. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1257. {
  1258. if (value is CounterQueueEvent)
  1259. {
  1260. // Compare an event and a constant value.
  1261. CounterQueueEvent evt = (CounterQueueEvent)value;
  1262. // Easy host conditional rendering when the check matches what GL can do:
  1263. // - Event is of type samples passed.
  1264. // - Result is not a combination of multiple queries.
  1265. // - Comparing against 0.
  1266. // - Event has not already been flushed.
  1267. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1268. {
  1269. if (!value.ReserveForHostAccess())
  1270. {
  1271. // If the event has been flushed, then just use the values on the CPU.
  1272. // The query object may already be repurposed for another draw (eg. begin + end).
  1273. return false;
  1274. }
  1275. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1276. _activeConditionalRender = evt;
  1277. return true;
  1278. }
  1279. }
  1280. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1281. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1282. return false;
  1283. }
  1284. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1285. {
  1286. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1287. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1288. }
  1289. public void EndHostConditionalRendering()
  1290. {
  1291. GL.EndConditionalRender();
  1292. _activeConditionalRender?.ReleaseHostAccess();
  1293. _activeConditionalRender = null;
  1294. }
  1295. public void Dispose()
  1296. {
  1297. _supportBuffer?.Dispose();
  1298. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1299. {
  1300. if (_tfbs[i] != BufferHandle.Null)
  1301. {
  1302. Buffer.Delete(_tfbs[i]);
  1303. _tfbs[i] = BufferHandle.Null;
  1304. }
  1305. }
  1306. _activeConditionalRender?.ReleaseHostAccess();
  1307. _framebuffer?.Dispose();
  1308. _vertexArray?.Dispose();
  1309. _drawTexture.Dispose();
  1310. }
  1311. }
  1312. }