Pipeline.cs 40 KB

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