TextureManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Types;
  3. using Ryujinx.Graphics.Gpu.Shader;
  4. using System;
  5. namespace Ryujinx.Graphics.Gpu.Image
  6. {
  7. /// <summary>
  8. /// Texture manager.
  9. /// </summary>
  10. class TextureManager : IDisposable
  11. {
  12. private readonly GpuContext _context;
  13. private readonly GpuChannel _channel;
  14. private readonly TextureBindingsManager _cpBindingsManager;
  15. private readonly TextureBindingsManager _gpBindingsManager;
  16. private readonly TexturePoolCache _texturePoolCache;
  17. private readonly Texture[] _rtColors;
  18. private readonly ITexture[] _rtHostColors;
  19. private Texture _rtDepthStencil;
  20. private ITexture _rtHostDs;
  21. public int ClipRegionWidth { get; private set; }
  22. public int ClipRegionHeight { get; private set; }
  23. /// <summary>
  24. /// The scaling factor applied to all currently bound render targets.
  25. /// </summary>
  26. public float RenderTargetScale { get; private set; } = 1f;
  27. /// <summary>
  28. /// Creates a new instance of the texture manager.
  29. /// </summary>
  30. /// <param name="context">GPU context that the texture manager belongs to</param>
  31. /// <param name="channel">GPU channel that the texture manager belongs to</param>
  32. public TextureManager(GpuContext context, GpuChannel channel)
  33. {
  34. _context = context;
  35. _channel = channel;
  36. TexturePoolCache texturePoolCache = new TexturePoolCache(context);
  37. float[] scales = new float[64];
  38. new Span<float>(scales).Fill(1f);
  39. _cpBindingsManager = new TextureBindingsManager(context, channel, texturePoolCache, scales, isCompute: true);
  40. _gpBindingsManager = new TextureBindingsManager(context, channel, texturePoolCache, scales, isCompute: false);
  41. _texturePoolCache = texturePoolCache;
  42. _rtColors = new Texture[Constants.TotalRenderTargets];
  43. _rtHostColors = new ITexture[Constants.TotalRenderTargets];
  44. }
  45. /// <summary>
  46. /// Rents the texture bindings array of the compute pipeline.
  47. /// </summary>
  48. /// <param name="count">The number of bindings needed</param>
  49. /// <returns>The texture bindings array</returns>
  50. public TextureBindingInfo[] RentComputeTextureBindings(int count)
  51. {
  52. return _cpBindingsManager.RentTextureBindings(0, count);
  53. }
  54. /// <summary>
  55. /// Rents the texture bindings array for a given stage on the graphics pipeline.
  56. /// </summary>
  57. /// <param name="stage">The index of the shader stage to bind the textures</param>
  58. /// <param name="count">The number of bindings needed</param>
  59. /// <returns>The texture bindings array</returns>
  60. public TextureBindingInfo[] RentGraphicsTextureBindings(int stage, int count)
  61. {
  62. return _gpBindingsManager.RentTextureBindings(stage, count);
  63. }
  64. /// <summary>
  65. /// Rents the image bindings array of the compute pipeline.
  66. /// </summary>
  67. /// <param name="count">The number of bindings needed</param>
  68. /// <returns>The image bindings array</returns>
  69. public TextureBindingInfo[] RentComputeImageBindings(int count)
  70. {
  71. return _cpBindingsManager.RentImageBindings(0, count);
  72. }
  73. /// <summary>
  74. /// Rents the image bindings array for a given stage on the graphics pipeline.
  75. /// </summary>
  76. /// <param name="stage">The index of the shader stage to bind the images</param>
  77. /// <param name="count">The number of bindings needed</param>
  78. /// <returns>The image bindings array</returns>
  79. public TextureBindingInfo[] RentGraphicsImageBindings(int stage, int count)
  80. {
  81. return _gpBindingsManager.RentImageBindings(stage, count);
  82. }
  83. /// <summary>
  84. /// Sets the texture constant buffer index on the compute pipeline.
  85. /// </summary>
  86. /// <param name="index">The texture constant buffer index</param>
  87. public void SetComputeTextureBufferIndex(int index)
  88. {
  89. _cpBindingsManager.SetTextureBufferIndex(index);
  90. }
  91. /// <summary>
  92. /// Sets the max binding indexes on the compute pipeline.
  93. /// </summary>
  94. /// <param name="maxTextureBinding">The maximum texture binding</param>
  95. /// <param name="maxImageBinding">The maximum image binding</param>
  96. public void SetComputeMaxBindings(int maxTextureBinding, int maxImageBinding)
  97. {
  98. _cpBindingsManager.SetMaxBindings(maxTextureBinding, maxImageBinding);
  99. }
  100. /// <summary>
  101. /// Sets the texture constant buffer index on the graphics pipeline.
  102. /// </summary>
  103. /// <param name="index">The texture constant buffer index</param>
  104. public void SetGraphicsTextureBufferIndex(int index)
  105. {
  106. _gpBindingsManager.SetTextureBufferIndex(index);
  107. }
  108. /// <summary>
  109. /// Sets the max binding indexes on the graphics pipeline.
  110. /// </summary>
  111. /// <param name="maxTextureBinding">The maximum texture binding</param>
  112. /// <param name="maxImageBinding">The maximum image binding</param>
  113. public void SetGraphicsMaxBindings(int maxTextureBinding, int maxImageBinding)
  114. {
  115. _gpBindingsManager.SetMaxBindings(maxTextureBinding, maxImageBinding);
  116. }
  117. /// <summary>
  118. /// Sets the current sampler pool on the compute pipeline.
  119. /// </summary>
  120. /// <param name="gpuVa">The start GPU virtual address of the sampler pool</param>
  121. /// <param name="maximumId">The maximum ID of the sampler pool</param>
  122. /// <param name="samplerIndex">The indexing type of the sampler pool</param>
  123. public void SetComputeSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  124. {
  125. _cpBindingsManager.SetSamplerPool(gpuVa, maximumId, samplerIndex);
  126. }
  127. /// <summary>
  128. /// Sets the current sampler pool on the graphics pipeline.
  129. /// </summary>
  130. /// <param name="gpuVa">The start GPU virtual address of the sampler pool</param>
  131. /// <param name="maximumId">The maximum ID of the sampler pool</param>
  132. /// <param name="samplerIndex">The indexing type of the sampler pool</param>
  133. public void SetGraphicsSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  134. {
  135. _gpBindingsManager.SetSamplerPool(gpuVa, maximumId, samplerIndex);
  136. }
  137. /// <summary>
  138. /// Sets the current texture pool on the compute pipeline.
  139. /// </summary>
  140. /// <param name="gpuVa">The start GPU virtual address of the texture pool</param>
  141. /// <param name="maximumId">The maximum ID of the texture pool</param>
  142. public void SetComputeTexturePool(ulong gpuVa, int maximumId)
  143. {
  144. _cpBindingsManager.SetTexturePool(gpuVa, maximumId);
  145. }
  146. /// <summary>
  147. /// Sets the current texture pool on the graphics pipeline.
  148. /// </summary>
  149. /// <param name="gpuVa">The start GPU virtual address of the texture pool</param>
  150. /// <param name="maximumId">The maximum ID of the texture pool</param>
  151. public void SetGraphicsTexturePool(ulong gpuVa, int maximumId)
  152. {
  153. _gpBindingsManager.SetTexturePool(gpuVa, maximumId);
  154. }
  155. /// <summary>
  156. /// Check if a texture's scale must be updated to match the configured resolution scale.
  157. /// </summary>
  158. /// <param name="texture">The texture to check</param>
  159. /// <returns>True if the scale needs updating, false if the scale is up to date</returns>
  160. private bool ScaleNeedsUpdated(Texture texture)
  161. {
  162. return texture != null && !(texture.ScaleMode == TextureScaleMode.Blacklisted || texture.ScaleMode == TextureScaleMode.Undesired) && texture.ScaleFactor != GraphicsConfig.ResScale;
  163. }
  164. /// <summary>
  165. /// Sets the render target color buffer.
  166. /// </summary>
  167. /// <param name="index">The index of the color buffer to set (up to 8)</param>
  168. /// <param name="color">The color buffer texture</param>
  169. /// <returns>True if render target scale must be updated.</returns>
  170. public bool SetRenderTargetColor(int index, Texture color)
  171. {
  172. bool hasValue = color != null;
  173. bool changesScale = (hasValue != (_rtColors[index] != null)) || (hasValue && RenderTargetScale != color.ScaleFactor);
  174. if (_rtColors[index] != color)
  175. {
  176. _rtColors[index]?.SignalModifying(false);
  177. if (color != null)
  178. {
  179. color.SynchronizeMemory();
  180. color.SignalModifying(true);
  181. }
  182. _rtColors[index] = color;
  183. }
  184. return changesScale || ScaleNeedsUpdated(color);
  185. }
  186. /// <summary>
  187. /// Sets the render target depth-stencil buffer.
  188. /// </summary>
  189. /// <param name="depthStencil">The depth-stencil buffer texture</param>
  190. /// <returns>True if render target scale must be updated.</returns>
  191. public bool SetRenderTargetDepthStencil(Texture depthStencil)
  192. {
  193. bool hasValue = depthStencil != null;
  194. bool changesScale = (hasValue != (_rtDepthStencil != null)) || (hasValue && RenderTargetScale != depthStencil.ScaleFactor);
  195. if (_rtDepthStencil != depthStencil)
  196. {
  197. _rtDepthStencil?.SignalModifying(false);
  198. if (depthStencil != null)
  199. {
  200. depthStencil.SynchronizeMemory();
  201. depthStencil.SignalModifying(true);
  202. }
  203. _rtDepthStencil = depthStencil;
  204. }
  205. return changesScale || ScaleNeedsUpdated(depthStencil);
  206. }
  207. /// <summary>
  208. /// Sets the host clip region, which should be the intersection of all render target texture sizes.
  209. /// </summary>
  210. /// <param name="width">Width of the clip region, defined as the minimum width across all bound textures</param>
  211. /// <param name="height">Height of the clip region, defined as the minimum height across all bound textures</param>
  212. public void SetClipRegion(int width, int height)
  213. {
  214. ClipRegionWidth = width;
  215. ClipRegionHeight = height;
  216. }
  217. /// <summary>
  218. /// Gets the first available bound colour target, or the depth stencil target if not present.
  219. /// </summary>
  220. /// <returns>The first bound colour target, otherwise the depth stencil target</returns>
  221. public Texture GetAnyRenderTarget()
  222. {
  223. return _rtColors[0] ?? _rtDepthStencil;
  224. }
  225. /// <summary>
  226. /// Updates the Render Target scale, given the currently bound render targets.
  227. /// This will update scale to match the configured scale, scale textures that are eligible but not scaled,
  228. /// and propagate blacklisted status from one texture to the ones bound with it.
  229. /// </summary>
  230. /// <param name="singleUse">If this is not -1, it indicates that only the given indexed target will be used.</param>
  231. public void UpdateRenderTargetScale(int singleUse)
  232. {
  233. // Make sure all scales for render targets are at the highest they should be. Blacklisted targets should propagate their scale to the other targets.
  234. bool mismatch = false;
  235. bool blacklisted = false;
  236. bool hasUpscaled = false;
  237. bool hasUndesired = false;
  238. float targetScale = GraphicsConfig.ResScale;
  239. void ConsiderTarget(Texture target)
  240. {
  241. if (target == null) return;
  242. float scale = target.ScaleFactor;
  243. switch (target.ScaleMode)
  244. {
  245. case TextureScaleMode.Blacklisted:
  246. mismatch |= scale != 1f;
  247. blacklisted = true;
  248. break;
  249. case TextureScaleMode.Eligible:
  250. mismatch = true; // We must make a decision.
  251. break;
  252. case TextureScaleMode.Undesired:
  253. hasUndesired = true;
  254. mismatch |= scale != 1f || hasUpscaled; // If another target is upscaled, scale this one up too.
  255. break;
  256. case TextureScaleMode.Scaled:
  257. hasUpscaled = true;
  258. mismatch |= hasUndesired || scale != targetScale; // If the target scale has changed, reset the scale for all targets.
  259. break;
  260. }
  261. }
  262. if (singleUse != -1)
  263. {
  264. // If only one target is in use (by a clear, for example) the others do not need to be checked for mismatching scale.
  265. ConsiderTarget(_rtColors[singleUse]);
  266. }
  267. else
  268. {
  269. foreach (Texture color in _rtColors)
  270. {
  271. ConsiderTarget(color);
  272. }
  273. }
  274. ConsiderTarget(_rtDepthStencil);
  275. mismatch |= blacklisted && hasUpscaled;
  276. if (blacklisted || (hasUndesired && !hasUpscaled))
  277. {
  278. targetScale = 1f;
  279. }
  280. if (mismatch)
  281. {
  282. if (blacklisted)
  283. {
  284. // Propagate the blacklisted state to the other textures.
  285. foreach (Texture color in _rtColors)
  286. {
  287. color?.BlacklistScale();
  288. }
  289. _rtDepthStencil?.BlacklistScale();
  290. }
  291. else
  292. {
  293. // Set the scale of the other textures.
  294. foreach (Texture color in _rtColors)
  295. {
  296. color?.SetScale(targetScale);
  297. }
  298. _rtDepthStencil?.SetScale(targetScale);
  299. }
  300. }
  301. RenderTargetScale = targetScale;
  302. }
  303. /// <summary>
  304. /// Gets a texture and a sampler from their respective pools from a texture ID and a sampler ID.
  305. /// </summary>
  306. /// <param name="textureId">ID of the texture</param>
  307. /// <param name="samplerId">ID of the sampler</param>
  308. public (Texture, Sampler) GetGraphicsTextureAndSampler(int textureId, int samplerId)
  309. {
  310. return _gpBindingsManager.GetTextureAndSampler(textureId, samplerId);
  311. }
  312. /// <summary>
  313. /// Commits bindings on the compute pipeline.
  314. /// </summary>
  315. /// <param name="specState">Specialization state for the bound shader</param>
  316. /// <returns>True if all bound textures match the current shader specialization state, false otherwise</returns>
  317. public bool CommitComputeBindings(ShaderSpecializationState specState)
  318. {
  319. // Every time we switch between graphics and compute work,
  320. // we must rebind everything.
  321. // Since compute work happens less often, we always do that
  322. // before and after the compute dispatch.
  323. _cpBindingsManager.Rebind();
  324. bool result = _cpBindingsManager.CommitBindings(specState);
  325. _gpBindingsManager.Rebind();
  326. return result;
  327. }
  328. /// <summary>
  329. /// Commits bindings on the graphics pipeline.
  330. /// </summary>
  331. /// <param name="specState">Specialization state for the bound shader</param>
  332. /// <returns>True if all bound textures match the current shader specialization state, false otherwise</returns>
  333. public bool CommitGraphicsBindings(ShaderSpecializationState specState)
  334. {
  335. bool result = _gpBindingsManager.CommitBindings(specState);
  336. UpdateRenderTargets();
  337. return result;
  338. }
  339. /// <summary>
  340. /// Returns a texture pool from the cache, with the given address and maximum id.
  341. /// </summary>
  342. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  343. /// <param name="maximumId">Maximum ID of the texture pool</param>
  344. /// <returns>The texture pool</returns>
  345. public TexturePool GetTexturePool(ulong poolGpuVa, int maximumId)
  346. {
  347. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  348. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  349. return texturePool;
  350. }
  351. /// <summary>
  352. /// Gets a texture descriptor used on the compute pipeline.
  353. /// </summary>
  354. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  355. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  356. /// <param name="maximumId">Maximum ID of the texture pool</param>
  357. /// <param name="handle">Shader "fake" handle of the texture</param>
  358. /// <param name="cbufSlot">Shader constant buffer slot of the texture</param>
  359. /// <returns>The texture descriptor</returns>
  360. public TextureDescriptor GetComputeTextureDescriptor(ulong poolGpuVa, int bufferIndex, int maximumId, int handle, int cbufSlot)
  361. {
  362. return _cpBindingsManager.GetTextureDescriptor(poolGpuVa, bufferIndex, maximumId, 0, handle, cbufSlot);
  363. }
  364. /// <summary>
  365. /// Gets a texture descriptor used on the graphics pipeline.
  366. /// </summary>
  367. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  368. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  369. /// <param name="maximumId">Maximum ID of the texture pool</param>
  370. /// <param name="stageIndex">Index of the shader stage where the texture is bound</param>
  371. /// <param name="handle">Shader "fake" handle of the texture</param>
  372. /// <param name="cbufSlot">Shader constant buffer slot of the texture</param>
  373. /// <returns>The texture descriptor</returns>
  374. public TextureDescriptor GetGraphicsTextureDescriptor(
  375. ulong poolGpuVa,
  376. int bufferIndex,
  377. int maximumId,
  378. int stageIndex,
  379. int handle,
  380. int cbufSlot)
  381. {
  382. return _gpBindingsManager.GetTextureDescriptor(poolGpuVa, bufferIndex, maximumId, stageIndex, handle, cbufSlot);
  383. }
  384. /// <summary>
  385. /// Update host framebuffer attachments based on currently bound render target buffers.
  386. /// </summary>
  387. public void UpdateRenderTargets()
  388. {
  389. bool anyChanged = false;
  390. if (_rtHostDs != _rtDepthStencil?.HostTexture)
  391. {
  392. _rtHostDs = _rtDepthStencil?.HostTexture;
  393. anyChanged = true;
  394. }
  395. for (int index = 0; index < _rtColors.Length; index++)
  396. {
  397. ITexture hostTexture = _rtColors[index]?.HostTexture;
  398. if (_rtHostColors[index] != hostTexture)
  399. {
  400. _rtHostColors[index] = hostTexture;
  401. anyChanged = true;
  402. }
  403. }
  404. if (anyChanged)
  405. {
  406. _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, _rtHostDs);
  407. }
  408. }
  409. /// <summary>
  410. /// Update host framebuffer attachments based on currently bound render target buffers.
  411. /// </summary>
  412. /// <remarks>
  413. /// All attachments other than <paramref name="index"/> will be unbound.
  414. /// </remarks>
  415. /// <param name="index">Index of the render target color to be updated</param>
  416. public void UpdateRenderTarget(int index)
  417. {
  418. new Span<ITexture>(_rtHostColors).Fill(null);
  419. _rtHostColors[index] = _rtColors[index]?.HostTexture;
  420. _rtHostDs = null;
  421. _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, null);
  422. }
  423. /// <summary>
  424. /// Update host framebuffer attachments based on currently bound render target buffers.
  425. /// </summary>
  426. /// <remarks>
  427. /// All color attachments will be unbound.
  428. /// </remarks>
  429. public void UpdateRenderTargetDepthStencil()
  430. {
  431. new Span<ITexture>(_rtHostColors).Fill(null);
  432. _rtHostDs = _rtDepthStencil?.HostTexture;
  433. _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, _rtHostDs);
  434. }
  435. /// <summary>
  436. /// Forces all textures, samplers, images and render targets to be rebound the next time
  437. /// CommitGraphicsBindings is called.
  438. /// </summary>
  439. public void Rebind()
  440. {
  441. _gpBindingsManager.Rebind();
  442. for (int index = 0; index < _rtHostColors.Length; index++)
  443. {
  444. _rtHostColors[index] = null;
  445. }
  446. _rtHostDs = null;
  447. }
  448. /// <summary>
  449. /// Disposes the texture manager.
  450. /// It's an error to use the texture manager after disposal.
  451. /// </summary>
  452. public void Dispose()
  453. {
  454. _cpBindingsManager.Dispose();
  455. _gpBindingsManager.Dispose();
  456. for (int i = 0; i < _rtColors.Length; i++)
  457. {
  458. _rtColors[i]?.DecrementReferenceCount();
  459. _rtColors[i] = null;
  460. }
  461. _rtDepthStencil?.DecrementReferenceCount();
  462. _rtDepthStencil = null;
  463. }
  464. }
  465. }