TextureBindingsManager.cs 21 KB

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