TextureBindingsManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.State;
  3. using Ryujinx.Graphics.Shader;
  4. namespace Ryujinx.Graphics.Gpu.Image
  5. {
  6. /// <summary>
  7. /// Texture bindings manager.
  8. /// </summary>
  9. class TextureBindingsManager
  10. {
  11. private const int HandleHigh = 16;
  12. private const int HandleMask = (1 << HandleHigh) - 1;
  13. private GpuContext _context;
  14. private bool _isCompute;
  15. private SamplerPool _samplerPool;
  16. private SamplerIndex _samplerIndex;
  17. private ulong _texturePoolAddress;
  18. private int _texturePoolMaximumId;
  19. private TexturePoolCache _texturePoolCache;
  20. private TextureBindingInfo[][] _textureBindings;
  21. private TextureBindingInfo[][] _imageBindings;
  22. private struct TextureStatePerStage
  23. {
  24. public ITexture Texture;
  25. public ISampler Sampler;
  26. }
  27. private TextureStatePerStage[][] _textureState;
  28. private TextureStatePerStage[][] _imageState;
  29. private int _textureBufferIndex;
  30. private bool _rebind;
  31. private float[] _scales;
  32. private bool _scaleChanged;
  33. /// <summary>
  34. /// Constructs a new instance of the texture bindings manager.
  35. /// </summary>
  36. /// <param name="context">The GPU context that the texture bindings manager belongs to</param>
  37. /// <param name="texturePoolCache">Texture pools cache used to get texture pools from</param>
  38. /// <param name="isCompute">True if the bindings manager is used for the compute engine</param>
  39. public TextureBindingsManager(GpuContext context, TexturePoolCache texturePoolCache, bool isCompute)
  40. {
  41. _context = context;
  42. _texturePoolCache = texturePoolCache;
  43. _isCompute = isCompute;
  44. int stages = isCompute ? 1 : Constants.ShaderStages;
  45. _textureBindings = new TextureBindingInfo[stages][];
  46. _imageBindings = new TextureBindingInfo[stages][];
  47. _textureState = new TextureStatePerStage[stages][];
  48. _imageState = new TextureStatePerStage[stages][];
  49. _scales = new float[64];
  50. for (int i = 0; i < 64; i++)
  51. {
  52. _scales[i] = 1f;
  53. }
  54. }
  55. /// <summary>
  56. /// Binds textures for a given shader stage.
  57. /// </summary>
  58. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  59. /// <param name="bindings">Texture bindings</param>
  60. public void SetTextures(int stage, TextureBindingInfo[] bindings)
  61. {
  62. _textureBindings[stage] = bindings;
  63. _textureState[stage] = new TextureStatePerStage[bindings.Length];
  64. }
  65. /// <summary>
  66. /// Binds images for a given shader stage.
  67. /// </summary>
  68. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  69. /// <param name="bindings">Image bindings</param>
  70. public void SetImages(int stage, TextureBindingInfo[] bindings)
  71. {
  72. _imageBindings[stage] = bindings;
  73. _imageState[stage] = new TextureStatePerStage[bindings.Length];
  74. }
  75. /// <summary>
  76. /// Sets the textures constant buffer index.
  77. /// The constant buffer specified holds the texture handles.
  78. /// </summary>
  79. /// <param name="index">Constant buffer index</param>
  80. public void SetTextureBufferIndex(int index)
  81. {
  82. _textureBufferIndex = index;
  83. }
  84. /// <summary>
  85. /// Sets the current texture sampler pool to be used.
  86. /// </summary>
  87. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  88. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  89. /// <param name="samplerIndex">Type of the sampler pool indexing used for bound samplers</param>
  90. public void SetSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  91. {
  92. ulong address = _context.MemoryManager.Translate(gpuVa);
  93. if (_samplerPool != null)
  94. {
  95. if (_samplerPool.Address == address && _samplerPool.MaximumId >= maximumId)
  96. {
  97. return;
  98. }
  99. _samplerPool.Dispose();
  100. }
  101. _samplerPool = new SamplerPool(_context, address, maximumId);
  102. _samplerIndex = samplerIndex;
  103. }
  104. /// <summary>
  105. /// Sets the current texture pool to be used.
  106. /// </summary>
  107. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  108. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  109. public void SetTexturePool(ulong gpuVa, int maximumId)
  110. {
  111. ulong address = _context.MemoryManager.Translate(gpuVa);
  112. _texturePoolAddress = address;
  113. _texturePoolMaximumId = maximumId;
  114. }
  115. /// <summary>
  116. /// Updates the texture scale for a given texture or image.
  117. /// </summary>
  118. /// <param name="texture">Start GPU virtual address of the pool</param>
  119. /// <param name="binding">The related texture binding</param>
  120. /// <param name="index">The texture/image binding index</param>
  121. /// <param name="stage">The active shader stage</param>
  122. /// <returns>True if the given texture has become blacklisted, indicating that its host texture may have changed.</returns>
  123. private bool UpdateScale(Texture texture, TextureBindingInfo binding, int index, ShaderStage stage)
  124. {
  125. float result = 1f;
  126. bool changed = false;
  127. if ((binding.Flags & TextureUsageFlags.NeedsScaleValue) != 0 && texture != null)
  128. {
  129. _scaleChanged |= true;
  130. switch (stage)
  131. {
  132. case ShaderStage.Fragment:
  133. if ((binding.Flags & TextureUsageFlags.ResScaleUnsupported) != 0)
  134. {
  135. changed |= texture.ScaleMode != TextureScaleMode.Blacklisted;
  136. texture.BlacklistScale();
  137. break;
  138. }
  139. float scale = texture.ScaleFactor;
  140. TextureManager manager = _context.Methods.TextureManager;
  141. if (scale != 1)
  142. {
  143. Texture activeTarget = manager.GetAnyRenderTarget();
  144. if (activeTarget != null && activeTarget.Info.Width / (float)texture.Info.Width == activeTarget.Info.Height / (float)texture.Info.Height)
  145. {
  146. // If the texture's size is a multiple of the sampler size, enable interpolation using gl_FragCoord. (helps "invent" new integer values between scaled pixels)
  147. result = -scale;
  148. break;
  149. }
  150. }
  151. result = scale;
  152. break;
  153. case ShaderStage.Compute:
  154. if ((binding.Flags & TextureUsageFlags.ResScaleUnsupported) != 0)
  155. {
  156. changed |= texture.ScaleMode != TextureScaleMode.Blacklisted;
  157. texture.BlacklistScale();
  158. }
  159. result = texture.ScaleFactor;
  160. break;
  161. }
  162. }
  163. _scales[index] = result;
  164. return changed;
  165. }
  166. /// <summary>
  167. /// Uploads texture and image scales to the backend when they are used.
  168. /// </summary>
  169. /// <param name="stage">Current shader stage</param>
  170. /// <param name="stageIndex">Shader stage index</param>
  171. private void CommitRenderScale(ShaderStage stage, int stageIndex)
  172. {
  173. if (_scaleChanged)
  174. {
  175. _context.Renderer.Pipeline.UpdateRenderScale(stage, _scales, _textureBindings[stageIndex]?.Length ?? 0, _imageBindings[stageIndex]?.Length ?? 0);
  176. }
  177. }
  178. /// <summary>
  179. /// Ensures that the bindings are visible to the host GPU.
  180. /// Note: this actually performs the binding using the host graphics API.
  181. /// </summary>
  182. public void CommitBindings()
  183. {
  184. TexturePool texturePool = _texturePoolCache.FindOrCreate(
  185. _texturePoolAddress,
  186. _texturePoolMaximumId);
  187. if (_isCompute)
  188. {
  189. CommitTextureBindings(texturePool, ShaderStage.Compute, 0);
  190. CommitImageBindings (texturePool, ShaderStage.Compute, 0);
  191. CommitRenderScale(ShaderStage.Compute, 0);
  192. }
  193. else
  194. {
  195. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  196. {
  197. int stageIndex = (int)stage - 1;
  198. CommitTextureBindings(texturePool, stage, stageIndex);
  199. CommitImageBindings (texturePool, stage, stageIndex);
  200. CommitRenderScale(stage, stageIndex);
  201. }
  202. }
  203. _rebind = false;
  204. }
  205. /// <summary>
  206. /// Ensures that the texture bindings are visible to the host GPU.
  207. /// Note: this actually performs the binding using the host graphics API.
  208. /// </summary>
  209. /// <param name="pool">The current texture pool</param>
  210. /// <param name="stage">The shader stage using the textures to be bound</param>
  211. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  212. private void CommitTextureBindings(TexturePool pool, ShaderStage stage, int stageIndex)
  213. {
  214. if (_textureBindings[stageIndex] == null)
  215. {
  216. return;
  217. }
  218. for (int index = 0; index < _textureBindings[stageIndex].Length; index++)
  219. {
  220. TextureBindingInfo bindingInfo = _textureBindings[stageIndex][index];
  221. int textureBufferIndex = bindingInfo.CbufSlot < 0 ? _textureBufferIndex : bindingInfo.CbufSlot;
  222. int packedId = ReadPackedId(stageIndex, bindingInfo.Handle, textureBufferIndex);
  223. int textureId = UnpackTextureId(packedId);
  224. int samplerId;
  225. if (_samplerIndex == SamplerIndex.ViaHeaderIndex)
  226. {
  227. samplerId = textureId;
  228. }
  229. else
  230. {
  231. samplerId = UnpackSamplerId(packedId);
  232. }
  233. Texture texture = pool.Get(textureId);
  234. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  235. if (_textureState[stageIndex][index].Texture != hostTexture || _rebind)
  236. {
  237. if (UpdateScale(texture, bindingInfo, index, stage))
  238. {
  239. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  240. }
  241. _textureState[stageIndex][index].Texture = hostTexture;
  242. _context.Renderer.Pipeline.SetTexture(bindingInfo.Binding, hostTexture);
  243. }
  244. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  245. {
  246. // Ensure that the buffer texture is using the correct buffer as storage.
  247. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  248. // to ensure we're not using a old buffer that was already deleted.
  249. _context.Methods.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, bindingInfo.Format, false);
  250. }
  251. Sampler sampler = _samplerPool.Get(samplerId);
  252. ISampler hostSampler = sampler?.HostSampler;
  253. if (_textureState[stageIndex][index].Sampler != hostSampler || _rebind)
  254. {
  255. _textureState[stageIndex][index].Sampler = hostSampler;
  256. _context.Renderer.Pipeline.SetSampler(bindingInfo.Binding, hostSampler);
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Ensures that the image bindings are visible to the host GPU.
  262. /// Note: this actually performs the binding using the host graphics API.
  263. /// </summary>
  264. /// <param name="pool">The current texture pool</param>
  265. /// <param name="stage">The shader stage using the textures to be bound</param>
  266. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  267. private void CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex)
  268. {
  269. if (_imageBindings[stageIndex] == null)
  270. {
  271. return;
  272. }
  273. // Scales for images appear after the texture ones.
  274. int baseScaleIndex = _textureBindings[stageIndex]?.Length ?? 0;
  275. for (int index = 0; index < _imageBindings[stageIndex].Length; index++)
  276. {
  277. TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];
  278. int textureBufferIndex = bindingInfo.CbufSlot < 0 ? _textureBufferIndex : bindingInfo.CbufSlot;
  279. int packedId = ReadPackedId(stageIndex, bindingInfo.Handle, textureBufferIndex);
  280. int textureId = UnpackTextureId(packedId);
  281. Texture texture = pool.Get(textureId);
  282. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  283. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  284. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  285. {
  286. // Ensure that the buffer texture is using the correct buffer as storage.
  287. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  288. // to ensure we're not using a old buffer that was already deleted.
  289. Format format = bindingInfo.Format;
  290. if (format == 0 && texture != null)
  291. {
  292. format = texture.Format;
  293. }
  294. _context.Methods.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, format, true);
  295. }
  296. else if (isStore)
  297. {
  298. texture?.SignalModified();
  299. }
  300. if (_imageState[stageIndex][index].Texture != hostTexture || _rebind)
  301. {
  302. if (UpdateScale(texture, bindingInfo, baseScaleIndex + index, stage))
  303. {
  304. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  305. }
  306. _imageState[stageIndex][index].Texture = hostTexture;
  307. Format format = bindingInfo.Format;
  308. if (format == 0 && texture != null)
  309. {
  310. format = texture.Format;
  311. }
  312. _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTexture, format);
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// Gets the texture descriptor for a given texture handle.
  318. /// </summary>
  319. /// <param name="state">The current GPU state</param>
  320. /// <param name="stageIndex">The stage number where the texture is bound</param>
  321. /// <param name="handle">The texture handle</param>
  322. /// <returns>The texture descriptor for the specified texture</returns>
  323. public TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int handle)
  324. {
  325. int packedId = ReadPackedId(stageIndex, handle, state.Get<int>(MethodOffset.TextureBufferIndex));
  326. int textureId = UnpackTextureId(packedId);
  327. var poolState = state.Get<PoolState>(MethodOffset.TexturePoolState);
  328. ulong poolAddress = _context.MemoryManager.Translate(poolState.Address.Pack());
  329. TexturePool texturePool = _texturePoolCache.FindOrCreate(poolAddress, poolState.MaximumId);
  330. return texturePool.GetDescriptor(textureId);
  331. }
  332. /// <summary>
  333. /// Reads a packed texture and sampler ID (basically, the real texture handle)
  334. /// from the texture constant buffer.
  335. /// </summary>
  336. /// <param name="stageIndex">The number of the shader stage where the texture is bound</param>
  337. /// <param name="wordOffset">A word offset of the handle on the buffer (the "fake" shader handle)</param>
  338. /// <param name="textureBufferIndex">Index of the constant buffer holding the texture handles</param>
  339. /// <returns>The packed texture and sampler ID (the real texture handle)</returns>
  340. private int ReadPackedId(int stageIndex, int wordOffset, int textureBufferIndex)
  341. {
  342. ulong address;
  343. var bufferManager = _context.Methods.BufferManager;
  344. if (_isCompute)
  345. {
  346. address = bufferManager.GetComputeUniformBufferAddress(textureBufferIndex);
  347. }
  348. else
  349. {
  350. address = bufferManager.GetGraphicsUniformBufferAddress(stageIndex, textureBufferIndex);
  351. }
  352. int handle = _context.PhysicalMemory.Read<int>(address + (ulong)(wordOffset & HandleMask) * 4);
  353. // The "wordOffset" (which is really the immediate value used on texture instructions on the shader)
  354. // is a 13-bit value. However, in order to also support separate samplers and textures (which uses
  355. // bindless textures on the shader), we extend it with another value on the higher 16 bits with
  356. // another offset for the sampler.
  357. // The shader translator has code to detect separate texture and sampler uses with a bindless texture,
  358. // turn that into a regular texture access and produce those special handles with values on the higher 16 bits.
  359. if (wordOffset >> HandleHigh != 0)
  360. {
  361. handle |= _context.PhysicalMemory.Read<int>(address + (ulong)(wordOffset >> HandleHigh) * 4);
  362. }
  363. return handle;
  364. }
  365. /// <summary>
  366. /// Unpacks the texture ID from the real texture handle.
  367. /// </summary>
  368. /// <param name="packedId">The real texture handle</param>
  369. /// <returns>The texture ID</returns>
  370. private static int UnpackTextureId(int packedId)
  371. {
  372. return (packedId >> 0) & 0xfffff;
  373. }
  374. /// <summary>
  375. /// Unpacks the sampler ID from the real texture handle.
  376. /// </summary>
  377. /// <param name="packedId">The real texture handle</param>
  378. /// <returns>The sampler ID</returns>
  379. private static int UnpackSamplerId(int packedId)
  380. {
  381. return (packedId >> 20) & 0xfff;
  382. }
  383. /// <summary>
  384. /// Force all bound textures and images to be rebound the next time CommitBindings is called.
  385. /// </summary>
  386. public void Rebind()
  387. {
  388. _rebind = true;
  389. }
  390. }
  391. }