DrawManager.cs 30 KB

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