TextureBindingsManager.cs 21 KB

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