DrawManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Types;
  3. using Ryujinx.Graphics.Gpu.Memory;
  4. using System;
  5. namespace Ryujinx.Graphics.Gpu.Engine.Threed
  6. {
  7. /// <summary>
  8. /// Draw manager.
  9. /// </summary>
  10. class DrawManager
  11. {
  12. // Since we don't know the index buffer size for indirect draws,
  13. // we must assume a minimum and maximum size and use that for buffer data update purposes.
  14. private const int MinIndirectIndexCount = 0x10000;
  15. private const int MaxIndirectIndexCount = 0x4000000;
  16. private readonly GpuContext _context;
  17. private readonly GpuChannel _channel;
  18. private readonly DeviceStateWithShadow<ThreedClassState> _state;
  19. private readonly DrawState _drawState;
  20. private bool _topologySet;
  21. private bool _instancedDrawPending;
  22. private bool _instancedIndexed;
  23. private bool _instancedIndexedInline;
  24. private int _instancedFirstIndex;
  25. private int _instancedFirstVertex;
  26. private int _instancedFirstInstance;
  27. private int _instancedIndexCount;
  28. private int _instancedDrawStateFirst;
  29. private int _instancedDrawStateCount;
  30. private int _instanceIndex;
  31. private const int VertexBufferFirstMethodOffset = 0x35d;
  32. private const int IndexBufferCountMethodOffset = 0x5f8;
  33. /// <summary>
  34. /// Creates a new instance of the draw manager.
  35. /// </summary>
  36. /// <param name="context">GPU context</param>
  37. /// <param name="channel">GPU channel</param>
  38. /// <param name="state">Channel state</param>
  39. /// <param name="drawState">Draw state</param>
  40. public DrawManager(GpuContext context, GpuChannel channel, DeviceStateWithShadow<ThreedClassState> state, DrawState drawState)
  41. {
  42. _context = context;
  43. _channel = channel;
  44. _state = state;
  45. _drawState = drawState;
  46. }
  47. /// <summary>
  48. /// Marks the entire state as dirty, forcing a full host state update before the next draw.
  49. /// </summary>
  50. public void ForceStateDirty()
  51. {
  52. _topologySet = false;
  53. }
  54. /// <summary>
  55. /// Pushes four 8-bit index buffer elements.
  56. /// </summary>
  57. /// <param name="argument">Method call argument</param>
  58. public void VbElementU8(int argument)
  59. {
  60. _drawState.IbStreamer.VbElementU8(_context.Renderer, argument);
  61. }
  62. /// <summary>
  63. /// Pushes two 16-bit index buffer elements.
  64. /// </summary>
  65. /// <param name="argument">Method call argument</param>
  66. public void VbElementU16(int argument)
  67. {
  68. _drawState.IbStreamer.VbElementU16(_context.Renderer, argument);
  69. }
  70. /// <summary>
  71. /// Pushes one 32-bit index buffer element.
  72. /// </summary>
  73. /// <param name="argument">Method call argument</param>
  74. public void VbElementU32(int argument)
  75. {
  76. _drawState.IbStreamer.VbElementU32(_context.Renderer, argument);
  77. }
  78. /// <summary>
  79. /// Finishes the draw call.
  80. /// This draws geometry on the bound buffers based on the current GPU state.
  81. /// </summary>
  82. /// <param name="engine">3D engine where this method is being called</param>
  83. /// <param name="argument">Method call argument</param>
  84. public void DrawEnd(ThreedClass engine, int argument)
  85. {
  86. DrawEnd(engine, _state.State.IndexBufferState.First, (int)_state.State.IndexBufferCount);
  87. }
  88. /// <summary>
  89. /// Finishes the draw call.
  90. /// This draws geometry on the bound buffers based on the current GPU state.
  91. /// </summary>
  92. /// <param name="engine">3D engine where this method is being called</param>
  93. /// <param name="firstIndex">Index of the first index buffer element used on the draw</param>
  94. /// <param name="indexCount">Number of index buffer elements used on the draw</param>
  95. private void DrawEnd(ThreedClass engine, int firstIndex, int indexCount)
  96. {
  97. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  98. _context,
  99. _channel.MemoryManager,
  100. _state.State.RenderEnableAddress,
  101. _state.State.RenderEnableCondition);
  102. if (renderEnable == ConditionalRenderEnabled.False || _instancedDrawPending)
  103. {
  104. if (renderEnable == ConditionalRenderEnabled.False)
  105. {
  106. PerformDeferredDraws();
  107. }
  108. _drawState.DrawIndexed = false;
  109. if (renderEnable == ConditionalRenderEnabled.Host)
  110. {
  111. _context.Renderer.Pipeline.EndHostConditionalRendering();
  112. }
  113. return;
  114. }
  115. _drawState.FirstIndex = firstIndex;
  116. _drawState.IndexCount = indexCount;
  117. engine.UpdateState();
  118. bool instanced = _drawState.VsUsesInstanceId || _drawState.IsAnyVbInstanced;
  119. if (instanced)
  120. {
  121. _instancedDrawPending = true;
  122. int ibCount = _drawState.IbStreamer.InlineIndexCount;
  123. _instancedIndexed = _drawState.DrawIndexed;
  124. _instancedIndexedInline = ibCount != 0;
  125. _instancedFirstIndex = firstIndex;
  126. _instancedFirstVertex = (int)_state.State.FirstVertex;
  127. _instancedFirstInstance = (int)_state.State.FirstInstance;
  128. _instancedIndexCount = ibCount != 0 ? ibCount : indexCount;
  129. var drawState = _state.State.VertexBufferDrawState;
  130. _instancedDrawStateFirst = drawState.First;
  131. _instancedDrawStateCount = drawState.Count;
  132. _drawState.DrawIndexed = false;
  133. if (renderEnable == ConditionalRenderEnabled.Host)
  134. {
  135. _context.Renderer.Pipeline.EndHostConditionalRendering();
  136. }
  137. return;
  138. }
  139. int firstInstance = (int)_state.State.FirstInstance;
  140. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount();
  141. if (inlineIndexCount != 0)
  142. {
  143. int firstVertex = (int)_state.State.FirstVertex;
  144. BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  145. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  146. _context.Renderer.Pipeline.DrawIndexed(inlineIndexCount, 1, firstIndex, firstVertex, firstInstance);
  147. }
  148. else if (_drawState.DrawIndexed)
  149. {
  150. int firstVertex = (int)_state.State.FirstVertex;
  151. _context.Renderer.Pipeline.DrawIndexed(indexCount, 1, firstIndex, firstVertex, firstInstance);
  152. }
  153. else
  154. {
  155. var drawState = _state.State.VertexBufferDrawState;
  156. _context.Renderer.Pipeline.Draw(drawState.Count, 1, drawState.First, firstInstance);
  157. }
  158. _drawState.DrawIndexed = false;
  159. if (renderEnable == ConditionalRenderEnabled.Host)
  160. {
  161. _context.Renderer.Pipeline.EndHostConditionalRendering();
  162. }
  163. }
  164. /// <summary>
  165. /// Starts draw.
  166. /// This sets primitive type and instanced draw parameters.
  167. /// </summary>
  168. /// <param name="argument">Method call argument</param>
  169. public void DrawBegin(int argument)
  170. {
  171. bool incrementInstance = (argument & (1 << 26)) != 0;
  172. bool resetInstance = (argument & (1 << 27)) == 0;
  173. if (_state.State.PrimitiveTypeOverrideEnable)
  174. {
  175. PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
  176. DrawBegin(incrementInstance, resetInstance, typeOverride.Convert());
  177. }
  178. else
  179. {
  180. PrimitiveType type = (PrimitiveType)(argument & 0xffff);
  181. DrawBegin(incrementInstance, resetInstance, type.Convert());
  182. }
  183. }
  184. /// <summary>
  185. /// Starts draw.
  186. /// This sets primitive type and instanced draw parameters.
  187. /// </summary>
  188. /// <param name="incrementInstance">Indicates if the current instance should be incremented</param>
  189. /// <param name="resetInstance">Indicates if the current instance should be set to zero</param>
  190. /// <param name="topology">Primitive topology</param>
  191. private void DrawBegin(bool incrementInstance, bool resetInstance, PrimitiveTopology topology)
  192. {
  193. if (incrementInstance)
  194. {
  195. _instanceIndex++;
  196. }
  197. else if (resetInstance)
  198. {
  199. PerformDeferredDraws();
  200. _instanceIndex = 0;
  201. }
  202. UpdateTopology(topology);
  203. }
  204. /// <summary>
  205. /// Updates the current primitive topology if needed.
  206. /// </summary>
  207. /// <param name="topology">New primitive topology</param>
  208. private void UpdateTopology(PrimitiveTopology topology)
  209. {
  210. if (_drawState.Topology != topology || !_topologySet)
  211. {
  212. _context.Renderer.Pipeline.SetPrimitiveTopology(topology);
  213. _drawState.Topology = topology;
  214. _topologySet = true;
  215. }
  216. }
  217. /// <summary>
  218. /// Sets the index buffer count.
  219. /// This also sets internal state that indicates that the next draw is an indexed draw.
  220. /// </summary>
  221. /// <param name="argument">Method call argument</param>
  222. public void SetIndexBufferCount(int argument)
  223. {
  224. _drawState.DrawIndexed = true;
  225. }
  226. /// <summary>
  227. /// Performs a indexed draw with a low number of index buffer elements.
  228. /// </summary>
  229. /// <param name="engine">3D engine where this method is being called</param>
  230. /// <param name="argument">Method call argument</param>
  231. public void DrawIndexedSmall(ThreedClass engine, int argument)
  232. {
  233. DrawIndexedSmall(engine, argument, false);
  234. }
  235. /// <summary>
  236. /// Performs a indexed draw with a low number of index buffer elements.
  237. /// </summary>
  238. /// <param name="engine">3D engine where this method is being called</param>
  239. /// <param name="argument">Method call argument</param>
  240. public void DrawIndexedSmall2(ThreedClass engine, int argument)
  241. {
  242. DrawIndexedSmall(engine, argument);
  243. }
  244. /// <summary>
  245. /// Performs a indexed draw with a low number of index buffer elements,
  246. /// while also pre-incrementing the current instance value.
  247. /// </summary>
  248. /// <param name="engine">3D engine where this method is being called</param>
  249. /// <param name="argument">Method call argument</param>
  250. public void DrawIndexedSmallIncInstance(ThreedClass engine, int argument)
  251. {
  252. DrawIndexedSmall(engine, argument, true);
  253. }
  254. /// <summary>
  255. /// Performs a indexed draw with a low number of index buffer elements,
  256. /// while also pre-incrementing the current instance value.
  257. /// </summary>
  258. /// <param name="engine">3D engine where this method is being called</param>
  259. /// <param name="argument">Method call argument</param>
  260. public void DrawIndexedSmallIncInstance2(ThreedClass engine, int argument)
  261. {
  262. DrawIndexedSmallIncInstance(engine, argument);
  263. }
  264. /// <summary>
  265. /// Performs a indexed draw with a low number of index buffer elements,
  266. /// while optionally also pre-incrementing the current instance value.
  267. /// </summary>
  268. /// <param name="engine">3D engine where this method is being called</param>
  269. /// <param name="argument">Method call argument</param>
  270. /// <param name="instanced">True to increment the current instance value, false otherwise</param>
  271. private void DrawIndexedSmall(ThreedClass engine, int argument, bool instanced)
  272. {
  273. PrimitiveTypeOverride typeOverride = _state.State.PrimitiveTypeOverride;
  274. DrawBegin(instanced, !instanced, typeOverride.Convert());
  275. int firstIndex = argument & 0xffff;
  276. int indexCount = (argument >> 16) & 0xfff;
  277. bool oldDrawIndexed = _drawState.DrawIndexed;
  278. _drawState.DrawIndexed = true;
  279. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  280. DrawEnd(engine, firstIndex, indexCount);
  281. _drawState.DrawIndexed = oldDrawIndexed;
  282. }
  283. /// <summary>
  284. /// Performs a texture draw with a source texture and sampler ID, along with source
  285. /// and destination coordinates and sizes.
  286. /// </summary>
  287. /// <param name="engine">3D engine where this method is being called</param>
  288. /// <param name="argument">Method call argument</param>
  289. public void DrawTexture(ThreedClass engine, int argument)
  290. {
  291. static float FixedToFloat(int fixedValue)
  292. {
  293. return fixedValue * (1f / 4096);
  294. }
  295. float dstX0 = FixedToFloat(_state.State.DrawTextureDstX);
  296. float dstY0 = FixedToFloat(_state.State.DrawTextureDstY);
  297. float dstWidth = FixedToFloat(_state.State.DrawTextureDstWidth);
  298. float dstHeight = FixedToFloat(_state.State.DrawTextureDstHeight);
  299. // TODO: Confirm behaviour on hardware.
  300. // When this is active, the origin appears to be on the bottom.
  301. if (_state.State.YControl.HasFlag(YControl.NegateY))
  302. {
  303. dstY0 -= dstHeight;
  304. }
  305. float dstX1 = dstX0 + dstWidth;
  306. float dstY1 = dstY0 + dstHeight;
  307. float srcX0 = FixedToFloat(_state.State.DrawTextureSrcX);
  308. float srcY0 = FixedToFloat(_state.State.DrawTextureSrcY);
  309. float srcX1 = ((float)_state.State.DrawTextureDuDx / (1UL << 32)) * dstWidth + srcX0;
  310. float srcY1 = ((float)_state.State.DrawTextureDvDy / (1UL << 32)) * dstHeight + srcY0;
  311. engine.UpdateState();
  312. int textureId = _state.State.DrawTextureTextureId;
  313. int samplerId = _state.State.DrawTextureSamplerId;
  314. (var texture, var sampler) = _channel.TextureManager.GetGraphicsTextureAndSampler(textureId, samplerId);
  315. srcX0 *= texture.ScaleFactor;
  316. srcY0 *= texture.ScaleFactor;
  317. srcX1 *= texture.ScaleFactor;
  318. srcY1 *= texture.ScaleFactor;
  319. float dstScale = _channel.TextureManager.RenderTargetScale;
  320. dstX0 *= dstScale;
  321. dstY0 *= dstScale;
  322. dstX1 *= dstScale;
  323. dstY1 *= dstScale;
  324. _context.Renderer.Pipeline.DrawTexture(
  325. texture?.HostTexture,
  326. sampler?.GetHostSampler(texture),
  327. new Extents2DF(srcX0, srcY0, srcX1, srcY1),
  328. new Extents2DF(dstX0, dstY0, dstX1, dstY1));
  329. }
  330. /// <summary>
  331. /// Performs a indexed or non-indexed draw.
  332. /// </summary>
  333. /// <param name="engine">3D engine where this method is being called</param>
  334. /// <param name="topology">Primitive topology</param>
  335. /// <param name="count">Index count for indexed draws, vertex count for non-indexed draws</param>
  336. /// <param name="instanceCount">Instance count</param>
  337. /// <param name="firstIndex">First index on the index buffer for indexed draws, ignored for non-indexed draws</param>
  338. /// <param name="firstVertex">First vertex on the vertex buffer</param>
  339. /// <param name="firstInstance">First instance</param>
  340. /// <param name="indexed">True if the draw is indexed, false otherwise</param>
  341. public void Draw(
  342. ThreedClass engine,
  343. PrimitiveTopology topology,
  344. int count,
  345. int instanceCount,
  346. int firstIndex,
  347. int firstVertex,
  348. int firstInstance,
  349. bool indexed)
  350. {
  351. UpdateTopology(topology);
  352. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  353. _context,
  354. _channel.MemoryManager,
  355. _state.State.RenderEnableAddress,
  356. _state.State.RenderEnableCondition);
  357. if (renderEnable == ConditionalRenderEnabled.False)
  358. {
  359. _drawState.DrawIndexed = false;
  360. return;
  361. }
  362. if (indexed)
  363. {
  364. _drawState.FirstIndex = firstIndex;
  365. _drawState.IndexCount = count;
  366. _state.State.FirstVertex = (uint)firstVertex;
  367. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  368. }
  369. else
  370. {
  371. _state.State.VertexBufferDrawState.First = firstVertex;
  372. _state.State.VertexBufferDrawState.Count = count;
  373. engine.ForceStateDirty(VertexBufferFirstMethodOffset * 4);
  374. }
  375. _state.State.FirstInstance = (uint)firstInstance;
  376. _drawState.DrawIndexed = indexed;
  377. _drawState.HasConstantBufferDrawParameters = true;
  378. engine.UpdateState();
  379. if (indexed)
  380. {
  381. _context.Renderer.Pipeline.DrawIndexed(count, instanceCount, firstIndex, firstVertex, firstInstance);
  382. _state.State.FirstVertex = 0;
  383. }
  384. else
  385. {
  386. _context.Renderer.Pipeline.Draw(count, instanceCount, firstVertex, firstInstance);
  387. }
  388. _state.State.FirstInstance = 0;
  389. _drawState.DrawIndexed = false;
  390. _drawState.HasConstantBufferDrawParameters = false;
  391. if (renderEnable == ConditionalRenderEnabled.Host)
  392. {
  393. _context.Renderer.Pipeline.EndHostConditionalRendering();
  394. }
  395. }
  396. /// <summary>
  397. /// Performs a indirect draw, with parameters from a GPU buffer.
  398. /// </summary>
  399. /// <param name="engine">3D engine where this method is being called</param>
  400. /// <param name="topology">Primitive topology</param>
  401. /// <param name="indirectBufferAddress">Address of the buffer with the draw parameters, such as count, first index, etc</param>
  402. /// <param name="parameterBufferAddress">Address of the buffer with the draw count</param>
  403. /// <param name="maxDrawCount">Maximum number of draws that can be made</param>
  404. /// <param name="stride">Distance in bytes between each entry on the data pointed to by <paramref name="indirectBufferAddress"/></param>
  405. /// <param name="indexCount">Maximum number of indices that the draw can consume</param>
  406. /// <param name="drawType">Type of the indirect draw, which can be indexed or non-indexed, with or without a draw count</param>
  407. public void DrawIndirect(
  408. ThreedClass engine,
  409. PrimitiveTopology topology,
  410. ulong indirectBufferAddress,
  411. ulong parameterBufferAddress,
  412. int maxDrawCount,
  413. int stride,
  414. int indexCount,
  415. IndirectDrawType drawType)
  416. {
  417. UpdateTopology(topology);
  418. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  419. _context,
  420. _channel.MemoryManager,
  421. _state.State.RenderEnableAddress,
  422. _state.State.RenderEnableCondition);
  423. if (renderEnable == ConditionalRenderEnabled.False)
  424. {
  425. _drawState.DrawIndexed = false;
  426. return;
  427. }
  428. PhysicalMemory memory = _channel.MemoryManager.Physical;
  429. bool hasCount = (drawType & IndirectDrawType.Count) != 0;
  430. bool indexed = (drawType & IndirectDrawType.Indexed) != 0;
  431. if (indexed)
  432. {
  433. indexCount = Math.Clamp(indexCount, MinIndirectIndexCount, MaxIndirectIndexCount);
  434. _drawState.FirstIndex = 0;
  435. _drawState.IndexCount = indexCount;
  436. engine.ForceStateDirty(IndexBufferCountMethodOffset * 4);
  437. }
  438. _drawState.DrawIndexed = indexed;
  439. _drawState.DrawIndirect = true;
  440. _drawState.HasConstantBufferDrawParameters = true;
  441. engine.UpdateState();
  442. if (hasCount)
  443. {
  444. var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferAddress, (ulong)maxDrawCount * (ulong)stride);
  445. var parameterBuffer = memory.BufferCache.GetBufferRange(parameterBufferAddress, 4);
  446. if (indexed)
  447. {
  448. _context.Renderer.Pipeline.DrawIndexedIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  449. }
  450. else
  451. {
  452. _context.Renderer.Pipeline.DrawIndirectCount(indirectBuffer, parameterBuffer, maxDrawCount, stride);
  453. }
  454. }
  455. else
  456. {
  457. var indirectBuffer = memory.BufferCache.GetBufferRange(indirectBufferAddress, (ulong)stride);
  458. if (indexed)
  459. {
  460. _context.Renderer.Pipeline.DrawIndexedIndirect(indirectBuffer);
  461. }
  462. else
  463. {
  464. _context.Renderer.Pipeline.DrawIndirect(indirectBuffer);
  465. }
  466. }
  467. _drawState.DrawIndexed = false;
  468. _drawState.DrawIndirect = false;
  469. _drawState.HasConstantBufferDrawParameters = false;
  470. if (renderEnable == ConditionalRenderEnabled.Host)
  471. {
  472. _context.Renderer.Pipeline.EndHostConditionalRendering();
  473. }
  474. }
  475. /// <summary>
  476. /// Perform any deferred draws.
  477. /// This is used for instanced draws.
  478. /// Since each instance is a separate draw, we defer the draw and accumulate the instance count.
  479. /// Once we detect the last instanced draw, then we perform the host instanced draw,
  480. /// with the accumulated instance count.
  481. /// </summary>
  482. public void PerformDeferredDraws()
  483. {
  484. // Perform any pending instanced draw.
  485. if (_instancedDrawPending)
  486. {
  487. _instancedDrawPending = false;
  488. bool indexedInline = _instancedIndexedInline;
  489. if (_instancedIndexed || indexedInline)
  490. {
  491. if (indexedInline)
  492. {
  493. int inlineIndexCount = _drawState.IbStreamer.GetAndResetInlineIndexCount();
  494. BufferRange br = new BufferRange(_drawState.IbStreamer.GetInlineIndexBuffer(), 0, inlineIndexCount * 4);
  495. _channel.BufferManager.SetIndexBuffer(br, IndexType.UInt);
  496. }
  497. _context.Renderer.Pipeline.DrawIndexed(
  498. _instancedIndexCount,
  499. _instanceIndex + 1,
  500. _instancedFirstIndex,
  501. _instancedFirstVertex,
  502. _instancedFirstInstance);
  503. }
  504. else
  505. {
  506. _context.Renderer.Pipeline.Draw(
  507. _instancedDrawStateCount,
  508. _instanceIndex + 1,
  509. _instancedDrawStateFirst,
  510. _instancedFirstInstance);
  511. }
  512. }
  513. }
  514. /// <summary>
  515. /// Clears the current color and depth-stencil buffers.
  516. /// Which buffers should be cleared can also be specified with the argument.
  517. /// </summary>
  518. /// <param name="engine">3D engine where this method is being called</param>
  519. /// <param name="argument">Method call argument</param>
  520. public void Clear(ThreedClass engine, int argument)
  521. {
  522. Clear(engine, argument, 1);
  523. }
  524. /// <summary>
  525. /// Clears the current color and depth-stencil buffers.
  526. /// Which buffers should be cleared can also specified with the arguments.
  527. /// </summary>
  528. /// <param name="engine">3D engine where this method is being called</param>
  529. /// <param name="argument">Method call argument</param>
  530. /// <param name="layerCount">For array and 3D textures, indicates how many layers should be cleared</param>
  531. public void Clear(ThreedClass engine, int argument, int layerCount)
  532. {
  533. ConditionalRenderEnabled renderEnable = ConditionalRendering.GetRenderEnable(
  534. _context,
  535. _channel.MemoryManager,
  536. _state.State.RenderEnableAddress,
  537. _state.State.RenderEnableCondition);
  538. if (renderEnable == ConditionalRenderEnabled.False)
  539. {
  540. return;
  541. }
  542. int index = (argument >> 6) & 0xf;
  543. int layer = (argument >> 10) & 0x3ff;
  544. engine.UpdateRenderTargetState(useControl: false, layered: layer != 0 || layerCount > 1, singleUse: index);
  545. // If there is a mismatch on the host clip region and the one explicitly defined by the guest
  546. // on the screen scissor state, then we need to force only one texture to be bound to avoid
  547. // host clipping.
  548. var screenScissorState = _state.State.ScreenScissorState;
  549. // Must happen after UpdateRenderTargetState to have up-to-date clip region values.
  550. bool clipMismatch = (screenScissorState.X | screenScissorState.Y) != 0 ||
  551. screenScissorState.Width != _channel.TextureManager.ClipRegionWidth ||
  552. screenScissorState.Height != _channel.TextureManager.ClipRegionHeight;
  553. bool clearAffectedByStencilMask = (_state.State.ClearFlags & 1) != 0;
  554. bool clearAffectedByScissor = (_state.State.ClearFlags & 0x100) != 0;
  555. bool needsCustomScissor = !clearAffectedByScissor || clipMismatch;
  556. // Scissor and rasterizer discard also affect clears.
  557. ulong updateMask = 1UL << StateUpdater.RasterizerStateIndex;
  558. if (!needsCustomScissor)
  559. {
  560. updateMask |= 1UL << StateUpdater.ScissorStateIndex;
  561. }
  562. engine.UpdateState(updateMask);
  563. if (needsCustomScissor)
  564. {
  565. int scissorX = screenScissorState.X;
  566. int scissorY = screenScissorState.Y;
  567. int scissorW = screenScissorState.Width;
  568. int scissorH = screenScissorState.Height;
  569. if (clearAffectedByScissor && _state.State.ScissorState[0].Enable)
  570. {
  571. ref var scissorState = ref _state.State.ScissorState[0];
  572. scissorX = Math.Max(scissorX, scissorState.X1);
  573. scissorY = Math.Max(scissorY, scissorState.Y1);
  574. scissorW = Math.Min(scissorW, scissorState.X2 - scissorState.X1);
  575. scissorH = Math.Min(scissorH, scissorState.Y2 - scissorState.Y1);
  576. }
  577. float scale = _channel.TextureManager.RenderTargetScale;
  578. if (scale != 1f)
  579. {
  580. scissorX = (int)(scissorX * scale);
  581. scissorY = (int)(scissorY * scale);
  582. scissorW = (int)MathF.Ceiling(scissorW * scale);
  583. scissorH = (int)MathF.Ceiling(scissorH * scale);
  584. }
  585. Span<Rectangle<int>> scissors = stackalloc Rectangle<int>[]
  586. {
  587. new Rectangle<int>(scissorX, scissorY, scissorW, scissorH)
  588. };
  589. _context.Renderer.Pipeline.SetScissors(scissors);
  590. }
  591. if (clipMismatch)
  592. {
  593. _channel.TextureManager.UpdateRenderTarget(index);
  594. }
  595. else
  596. {
  597. _channel.TextureManager.UpdateRenderTargets();
  598. }
  599. bool clearDepth = (argument & 1) != 0;
  600. bool clearStencil = (argument & 2) != 0;
  601. uint componentMask = (uint)((argument >> 2) & 0xf);
  602. if (componentMask != 0)
  603. {
  604. var clearColor = _state.State.ClearColors;
  605. ColorF color = new ColorF(clearColor.Red, clearColor.Green, clearColor.Blue, clearColor.Alpha);
  606. _context.Renderer.Pipeline.ClearRenderTargetColor(index, layer, layerCount, componentMask, color);
  607. }
  608. if (clearDepth || clearStencil)
  609. {
  610. float depthValue = _state.State.ClearDepthValue;
  611. int stencilValue = (int)_state.State.ClearStencilValue;
  612. int stencilMask = 0;
  613. if (clearStencil)
  614. {
  615. stencilMask = clearAffectedByStencilMask ? _state.State.StencilTestState.FrontMask : 0xff;
  616. }
  617. if (clipMismatch)
  618. {
  619. _channel.TextureManager.UpdateRenderTargetDepthStencil();
  620. }
  621. _context.Renderer.Pipeline.ClearRenderTargetDepthStencil(
  622. layer,
  623. layerCount,
  624. depthValue,
  625. clearDepth,
  626. stencilValue,
  627. stencilMask);
  628. }
  629. if (needsCustomScissor)
  630. {
  631. engine.UpdateScissorState();
  632. }
  633. engine.UpdateRenderTargetState(useControl: true);
  634. if (renderEnable == ConditionalRenderEnabled.Host)
  635. {
  636. _context.Renderer.Pipeline.EndHostConditionalRendering();
  637. }
  638. }
  639. }
  640. }