TextureBindingsManager.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Engine.Types;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Gpu.Shader;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Gpu.Image
  11. {
  12. /// <summary>
  13. /// Texture bindings manager.
  14. /// </summary>
  15. class TextureBindingsManager
  16. {
  17. private const int InitialTextureStateSize = 32;
  18. private const int InitialImageStateSize = 8;
  19. private readonly GpuContext _context;
  20. private readonly bool _isCompute;
  21. private ulong _texturePoolGpuVa;
  22. private int _texturePoolMaximumId;
  23. private TexturePool _texturePool;
  24. private ulong _samplerPoolGpuVa;
  25. private int _samplerPoolMaximumId;
  26. private SamplerIndex _samplerIndex;
  27. private SamplerPool _samplerPool;
  28. private readonly GpuChannel _channel;
  29. private readonly TexturePoolCache _texturePoolCache;
  30. private readonly SamplerPoolCache _samplerPoolCache;
  31. private TexturePool _cachedTexturePool;
  32. private SamplerPool _cachedSamplerPool;
  33. private TextureBindingInfo[][] _textureBindings;
  34. private TextureBindingInfo[][] _imageBindings;
  35. private struct TextureState
  36. {
  37. public ITexture Texture;
  38. public ISampler Sampler;
  39. public int TextureHandle;
  40. public int SamplerHandle;
  41. public Format ImageFormat;
  42. public int InvalidatedSequence;
  43. public Texture CachedTexture;
  44. public Sampler CachedSampler;
  45. }
  46. private TextureState[] _textureState;
  47. private TextureState[] _imageState;
  48. private int _texturePoolSequence;
  49. private int _samplerPoolSequence;
  50. private int _textureBufferIndex;
  51. private int _lastFragmentTotal;
  52. /// <summary>
  53. /// Constructs a new instance of the texture bindings manager.
  54. /// </summary>
  55. /// <param name="context">The GPU context that the texture bindings manager belongs to</param>
  56. /// <param name="channel">The GPU channel that the texture bindings manager belongs to</param>
  57. /// <param name="texturePoolCache">Texture pools cache used to get texture pools from</param>
  58. /// <param name="samplerPoolCache">Sampler pools cache used to get sampler pools from</param>
  59. /// <param name="isCompute">True if the bindings manager is used for the compute engine</param>
  60. public TextureBindingsManager(
  61. GpuContext context,
  62. GpuChannel channel,
  63. TexturePoolCache texturePoolCache,
  64. SamplerPoolCache samplerPoolCache,
  65. bool isCompute)
  66. {
  67. _context = context;
  68. _channel = channel;
  69. _texturePoolCache = texturePoolCache;
  70. _samplerPoolCache = samplerPoolCache;
  71. _isCompute = isCompute;
  72. int stages = isCompute ? 1 : Constants.ShaderStages;
  73. _textureBindings = new TextureBindingInfo[stages][];
  74. _imageBindings = new TextureBindingInfo[stages][];
  75. _textureState = new TextureState[InitialTextureStateSize];
  76. _imageState = new TextureState[InitialImageStateSize];
  77. for (int stage = 0; stage < stages; stage++)
  78. {
  79. _textureBindings[stage] = new TextureBindingInfo[InitialTextureStateSize];
  80. _imageBindings[stage] = new TextureBindingInfo[InitialImageStateSize];
  81. }
  82. }
  83. /// <summary>
  84. /// Sets the texture and image bindings.
  85. /// </summary>
  86. /// <param name="bindings">Bindings for the active shader</param>
  87. public void SetBindings(CachedShaderBindings bindings)
  88. {
  89. _textureBindings = bindings.TextureBindings;
  90. _imageBindings = bindings.ImageBindings;
  91. SetMaxBindings(bindings.MaxTextureBinding, bindings.MaxImageBinding);
  92. }
  93. /// <summary>
  94. /// Sets the max binding indexes for textures and images.
  95. /// </summary>
  96. /// <param name="maxTextureBinding">The maximum texture binding</param>
  97. /// <param name="maxImageBinding">The maximum image binding</param>
  98. public void SetMaxBindings(int maxTextureBinding, int maxImageBinding)
  99. {
  100. if (maxTextureBinding >= _textureState.Length)
  101. {
  102. Array.Resize(ref _textureState, maxTextureBinding + 1);
  103. }
  104. if (maxImageBinding >= _imageState.Length)
  105. {
  106. Array.Resize(ref _imageState, maxImageBinding + 1);
  107. }
  108. }
  109. /// <summary>
  110. /// Sets the textures constant buffer index.
  111. /// The constant buffer specified holds the texture handles.
  112. /// </summary>
  113. /// <param name="index">Constant buffer index</param>
  114. public void SetTextureBufferIndex(int index)
  115. {
  116. _textureBufferIndex = index;
  117. }
  118. /// <summary>
  119. /// Sets the current texture sampler pool to be used.
  120. /// </summary>
  121. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  122. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  123. /// <param name="samplerIndex">Type of the sampler pool indexing used for bound samplers</param>
  124. public void SetSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  125. {
  126. _samplerPoolGpuVa = gpuVa;
  127. _samplerPoolMaximumId = maximumId;
  128. _samplerIndex = samplerIndex;
  129. _samplerPool = null;
  130. }
  131. /// <summary>
  132. /// Sets the current texture pool to be used.
  133. /// </summary>
  134. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  135. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  136. public void SetTexturePool(ulong gpuVa, int maximumId)
  137. {
  138. _texturePoolGpuVa = gpuVa;
  139. _texturePoolMaximumId = maximumId;
  140. _texturePool = null;
  141. }
  142. /// <summary>
  143. /// Gets a texture and a sampler from their respective pools from a texture ID and a sampler ID.
  144. /// </summary>
  145. /// <param name="textureId">ID of the texture</param>
  146. /// <param name="samplerId">ID of the sampler</param>
  147. public (Texture, Sampler) GetTextureAndSampler(int textureId, int samplerId)
  148. {
  149. (TexturePool texturePool, SamplerPool samplerPool) = GetPools();
  150. return (texturePool.Get(textureId), samplerPool.Get(samplerId));
  151. }
  152. /// <summary>
  153. /// Updates the texture scale for a given texture or image.
  154. /// </summary>
  155. /// <param name="texture">Start GPU virtual address of the pool</param>
  156. /// <param name="usageFlags">The related texture usage flags</param>
  157. /// <param name="index">The texture/image binding index</param>
  158. /// <param name="stage">The active shader stage</param>
  159. /// <returns>True if the given texture has become blacklisted, indicating that its host texture may have changed.</returns>
  160. private bool UpdateScale(Texture texture, TextureUsageFlags usageFlags, int index, ShaderStage stage)
  161. {
  162. float result = 1f;
  163. bool changed = false;
  164. if ((usageFlags & TextureUsageFlags.NeedsScaleValue) != 0 && texture != null)
  165. {
  166. if ((usageFlags & TextureUsageFlags.ResScaleUnsupported) != 0)
  167. {
  168. changed = texture.ScaleMode != TextureScaleMode.Blacklisted;
  169. texture.BlacklistScale();
  170. }
  171. else
  172. {
  173. switch (stage)
  174. {
  175. case ShaderStage.Fragment:
  176. float scale = texture.ScaleFactor;
  177. if (scale != 1)
  178. {
  179. Texture activeTarget = _channel.TextureManager.GetAnyRenderTarget();
  180. if (activeTarget != null && (activeTarget.Info.Width / (float)texture.Info.Width) == (activeTarget.Info.Height / (float)texture.Info.Height))
  181. {
  182. // 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)
  183. result = -scale;
  184. break;
  185. }
  186. }
  187. result = scale;
  188. break;
  189. case ShaderStage.Vertex:
  190. int fragmentIndex = (int)ShaderStage.Fragment - 1;
  191. index += _textureBindings[fragmentIndex].Length + _imageBindings[fragmentIndex].Length;
  192. result = texture.ScaleFactor;
  193. break;
  194. case ShaderStage.Compute:
  195. result = texture.ScaleFactor;
  196. break;
  197. }
  198. }
  199. }
  200. _context.SupportBufferUpdater.UpdateRenderScale(index, result);
  201. return changed;
  202. }
  203. /// <summary>
  204. /// Determines if the vertex stage requires a scale value.
  205. /// </summary>
  206. private bool VertexRequiresScale()
  207. {
  208. for (int i = 0; i < _textureBindings[0].Length; i++)
  209. {
  210. if ((_textureBindings[0][i].Flags & TextureUsageFlags.NeedsScaleValue) != 0)
  211. {
  212. return true;
  213. }
  214. }
  215. for (int i = 0; i < _imageBindings[0].Length; i++)
  216. {
  217. if ((_imageBindings[0][i].Flags & TextureUsageFlags.NeedsScaleValue) != 0)
  218. {
  219. return true;
  220. }
  221. }
  222. return false;
  223. }
  224. /// <summary>
  225. /// Uploads texture and image scales to the backend when they are used.
  226. /// </summary>
  227. private void CommitRenderScale()
  228. {
  229. // Stage 0 total: Compute or Vertex.
  230. int total = _textureBindings[0].Length + _imageBindings[0].Length;
  231. int fragmentIndex = (int)ShaderStage.Fragment - 1;
  232. int fragmentTotal = _isCompute ? 0 : (_textureBindings[fragmentIndex].Length + _imageBindings[fragmentIndex].Length);
  233. if (total != 0 && fragmentTotal != _lastFragmentTotal && VertexRequiresScale())
  234. {
  235. // Must update scales in the support buffer if:
  236. // - Vertex stage has bindings that require scale.
  237. // - Fragment stage binding count has been updated since last render scale update.
  238. if (!_isCompute)
  239. {
  240. total += fragmentTotal; // Add the fragment bindings to the total.
  241. }
  242. _lastFragmentTotal = fragmentTotal;
  243. _context.SupportBufferUpdater.UpdateRenderScaleFragmentCount(total, fragmentTotal);
  244. }
  245. }
  246. /// <summary>
  247. /// Ensures that the bindings are visible to the host GPU.
  248. /// Note: this actually performs the binding using the host graphics API.
  249. /// </summary>
  250. /// <param name="specState">Specialization state for the bound shader</param>
  251. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  252. public bool CommitBindings(ShaderSpecializationState specState)
  253. {
  254. (TexturePool texturePool, SamplerPool samplerPool) = GetPools();
  255. // Check if the texture pool has been modified since bindings were last committed.
  256. // If it wasn't, then it's possible to avoid looking up textures again when the handle remains the same.
  257. if (_cachedTexturePool != texturePool || _cachedSamplerPool != samplerPool)
  258. {
  259. Rebind();
  260. _cachedTexturePool = texturePool;
  261. _cachedSamplerPool = samplerPool;
  262. }
  263. bool poolModified = false;
  264. if (texturePool != null)
  265. {
  266. int texturePoolSequence = texturePool.CheckModified();
  267. if (_texturePoolSequence != texturePoolSequence)
  268. {
  269. poolModified = true;
  270. _texturePoolSequence = texturePoolSequence;
  271. }
  272. }
  273. if (samplerPool != null)
  274. {
  275. int samplerPoolSequence = samplerPool.CheckModified();
  276. if (_samplerPoolSequence != samplerPoolSequence)
  277. {
  278. poolModified = true;
  279. _samplerPoolSequence = samplerPoolSequence;
  280. }
  281. }
  282. bool specStateMatches = true;
  283. if (_isCompute)
  284. {
  285. specStateMatches &= CommitTextureBindings(texturePool, samplerPool, ShaderStage.Compute, 0, poolModified, specState);
  286. specStateMatches &= CommitImageBindings(texturePool, ShaderStage.Compute, 0, poolModified, specState);
  287. }
  288. else
  289. {
  290. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  291. {
  292. int stageIndex = (int)stage - 1;
  293. specStateMatches &= CommitTextureBindings(texturePool, samplerPool, stage, stageIndex, poolModified, specState);
  294. specStateMatches &= CommitImageBindings(texturePool, stage, stageIndex, poolModified, specState);
  295. }
  296. }
  297. CommitRenderScale();
  298. return specStateMatches;
  299. }
  300. /// <summary>
  301. /// Fetch the constant buffers used for a texture to cache.
  302. /// </summary>
  303. /// <param name="stageIndex">Stage index of the constant buffer</param>
  304. /// <param name="cachedTextureBufferIndex">The currently cached texture buffer index</param>
  305. /// <param name="cachedSamplerBufferIndex">The currently cached sampler buffer index</param>
  306. /// <param name="cachedTextureBuffer">The currently cached texture buffer data</param>
  307. /// <param name="cachedSamplerBuffer">The currently cached sampler buffer data</param>
  308. /// <param name="textureBufferIndex">The new texture buffer index</param>
  309. /// <param name="samplerBufferIndex">The new sampler buffer index</param>
  310. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  311. private void UpdateCachedBuffer(
  312. int stageIndex,
  313. scoped ref int cachedTextureBufferIndex,
  314. scoped ref int cachedSamplerBufferIndex,
  315. scoped ref ReadOnlySpan<int> cachedTextureBuffer,
  316. scoped ref ReadOnlySpan<int> cachedSamplerBuffer,
  317. int textureBufferIndex,
  318. int samplerBufferIndex)
  319. {
  320. if (textureBufferIndex != cachedTextureBufferIndex)
  321. {
  322. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, textureBufferIndex);
  323. cachedTextureBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Range));
  324. cachedTextureBufferIndex = textureBufferIndex;
  325. if (samplerBufferIndex == textureBufferIndex)
  326. {
  327. cachedSamplerBuffer = cachedTextureBuffer;
  328. cachedSamplerBufferIndex = samplerBufferIndex;
  329. }
  330. }
  331. if (samplerBufferIndex != cachedSamplerBufferIndex)
  332. {
  333. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, samplerBufferIndex);
  334. cachedSamplerBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Range));
  335. cachedSamplerBufferIndex = samplerBufferIndex;
  336. }
  337. }
  338. #pragma warning disable IDE0051 // Remove unused private member
  339. /// <summary>
  340. /// Counts the total number of texture bindings used by all shader stages.
  341. /// </summary>
  342. /// <returns>The total amount of textures used</returns>
  343. private int GetTextureBindingsCount()
  344. {
  345. int count = 0;
  346. foreach (TextureBindingInfo[] textureInfo in _textureBindings)
  347. {
  348. if (textureInfo != null)
  349. {
  350. count += textureInfo.Length;
  351. }
  352. }
  353. return count;
  354. }
  355. #pragma warning restore IDE0051
  356. /// <summary>
  357. /// Ensures that the texture bindings are visible to the host GPU.
  358. /// Note: this actually performs the binding using the host graphics API.
  359. /// </summary>
  360. /// <param name="texturePool">The current texture pool</param>
  361. /// <param name="samplerPool">The current sampler pool</param>
  362. /// <param name="stage">The shader stage using the textures to be bound</param>
  363. /// <param name="stageIndex">The stage number of the specified shader stage</param
  364. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  365. /// <param name="specState">Specialization state for the bound shader</param>
  366. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  367. private bool CommitTextureBindings(
  368. TexturePool texturePool,
  369. SamplerPool samplerPool,
  370. ShaderStage stage,
  371. int stageIndex,
  372. bool poolModified,
  373. ShaderSpecializationState specState)
  374. {
  375. int textureCount = _textureBindings[stageIndex].Length;
  376. if (textureCount == 0)
  377. {
  378. return true;
  379. }
  380. if (texturePool == null)
  381. {
  382. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses textures, but texture pool was not set.");
  383. return true;
  384. }
  385. bool specStateMatches = true;
  386. int cachedTextureBufferIndex = -1;
  387. int cachedSamplerBufferIndex = -1;
  388. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  389. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  390. for (int index = 0; index < textureCount; index++)
  391. {
  392. TextureBindingInfo bindingInfo = _textureBindings[stageIndex][index];
  393. TextureUsageFlags usageFlags = bindingInfo.Flags;
  394. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  395. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  396. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  397. int textureId = TextureHandle.UnpackTextureId(packedId);
  398. int samplerId;
  399. if (_samplerIndex == SamplerIndex.ViaHeaderIndex)
  400. {
  401. samplerId = textureId;
  402. }
  403. else
  404. {
  405. samplerId = TextureHandle.UnpackSamplerId(packedId);
  406. }
  407. ref TextureState state = ref _textureState[bindingInfo.Binding];
  408. if (!poolModified &&
  409. state.TextureHandle == textureId &&
  410. state.SamplerHandle == samplerId &&
  411. state.CachedTexture != null &&
  412. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence &&
  413. state.CachedSampler?.IsDisposed != true)
  414. {
  415. // The texture is already bound.
  416. state.CachedTexture.SynchronizeMemory();
  417. if ((usageFlags & TextureUsageFlags.NeedsScaleValue) != 0 &&
  418. UpdateScale(state.CachedTexture, usageFlags, index, stage))
  419. {
  420. ITexture hostTextureRebind = state.CachedTexture.GetTargetTexture(bindingInfo.Target);
  421. state.Texture = hostTextureRebind;
  422. _context.Renderer.Pipeline.SetTextureAndSampler(stage, bindingInfo.Binding, hostTextureRebind, state.Sampler);
  423. }
  424. continue;
  425. }
  426. state.TextureHandle = textureId;
  427. state.SamplerHandle = samplerId;
  428. ref readonly TextureDescriptor descriptor = ref texturePool.GetForBinding(textureId, out Texture texture);
  429. specStateMatches &= specState.MatchesTexture(stage, index, descriptor);
  430. Sampler sampler = samplerPool?.Get(samplerId);
  431. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  432. ISampler hostSampler = sampler?.GetHostSampler(texture);
  433. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  434. {
  435. // Ensure that the buffer texture is using the correct buffer as storage.
  436. // Buffers are frequently re-created to accommodate larger data, so we need to re-bind
  437. // to ensure we're not using a old buffer that was already deleted.
  438. _channel.BufferManager.SetBufferTextureStorage(stage, hostTexture, texture.Range, bindingInfo, bindingInfo.Format, false);
  439. // Cache is not used for buffer texture, it must always rebind.
  440. state.CachedTexture = null;
  441. }
  442. else
  443. {
  444. bool textureOrSamplerChanged = state.Texture != hostTexture || state.Sampler != hostSampler;
  445. if ((usageFlags & TextureUsageFlags.NeedsScaleValue) != 0 &&
  446. UpdateScale(texture, usageFlags, index, stage))
  447. {
  448. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  449. textureOrSamplerChanged = true;
  450. }
  451. if (textureOrSamplerChanged)
  452. {
  453. state.Texture = hostTexture;
  454. state.Sampler = hostSampler;
  455. _context.Renderer.Pipeline.SetTextureAndSampler(stage, bindingInfo.Binding, hostTexture, hostSampler);
  456. }
  457. state.CachedTexture = texture;
  458. state.CachedSampler = sampler;
  459. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  460. }
  461. }
  462. return specStateMatches;
  463. }
  464. /// <summary>
  465. /// Ensures that the image bindings are visible to the host GPU.
  466. /// Note: this actually performs the binding using the host graphics API.
  467. /// </summary>
  468. /// <param name="pool">The current texture pool</param>
  469. /// <param name="stage">The shader stage using the textures to be bound</param>
  470. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  471. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  472. /// <param name="specState">Specialization state for the bound shader</param>
  473. /// <returns>True if all bound images match the current shader specialiation state, false otherwise</returns>
  474. private bool CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex, bool poolModified, ShaderSpecializationState specState)
  475. {
  476. int imageCount = _imageBindings[stageIndex].Length;
  477. if (imageCount == 0)
  478. {
  479. return true;
  480. }
  481. if (pool == null)
  482. {
  483. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses images, but texture pool was not set.");
  484. return true;
  485. }
  486. // Scales for images appear after the texture ones.
  487. int baseScaleIndex = _textureBindings[stageIndex].Length;
  488. int cachedTextureBufferIndex = -1;
  489. int cachedSamplerBufferIndex = -1;
  490. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  491. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  492. bool specStateMatches = true;
  493. for (int index = 0; index < imageCount; index++)
  494. {
  495. TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];
  496. TextureUsageFlags usageFlags = bindingInfo.Flags;
  497. int scaleIndex = baseScaleIndex + index;
  498. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  499. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  500. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  501. int textureId = TextureHandle.UnpackTextureId(packedId);
  502. ref TextureState state = ref _imageState[bindingInfo.Binding];
  503. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  504. if (!poolModified &&
  505. state.TextureHandle == textureId &&
  506. state.CachedTexture != null &&
  507. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence)
  508. {
  509. Texture cachedTexture = state.CachedTexture;
  510. // The texture is already bound.
  511. cachedTexture.SynchronizeMemory();
  512. if (isStore)
  513. {
  514. cachedTexture?.SignalModified();
  515. }
  516. Format format = bindingInfo.Format == 0 ? cachedTexture.Format : bindingInfo.Format;
  517. if (state.ImageFormat != format ||
  518. ((usageFlags & TextureUsageFlags.NeedsScaleValue) != 0 &&
  519. UpdateScale(state.CachedTexture, usageFlags, scaleIndex, stage)))
  520. {
  521. ITexture hostTextureRebind = state.CachedTexture.GetTargetTexture(bindingInfo.Target);
  522. state.Texture = hostTextureRebind;
  523. state.ImageFormat = format;
  524. _context.Renderer.Pipeline.SetImage(stage, bindingInfo.Binding, hostTextureRebind, format);
  525. }
  526. continue;
  527. }
  528. state.TextureHandle = textureId;
  529. ref readonly TextureDescriptor descriptor = ref pool.GetForBinding(textureId, out Texture texture);
  530. specStateMatches &= specState.MatchesImage(stage, index, descriptor);
  531. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  532. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  533. {
  534. // Ensure that the buffer texture is using the correct buffer as storage.
  535. // Buffers are frequently re-created to accommodate larger data, so we need to re-bind
  536. // to ensure we're not using a old buffer that was already deleted.
  537. Format format = bindingInfo.Format;
  538. if (format == 0 && texture != null)
  539. {
  540. format = texture.Format;
  541. }
  542. _channel.BufferManager.SetBufferTextureStorage(stage, hostTexture, texture.Range, bindingInfo, format, true);
  543. // Cache is not used for buffer texture, it must always rebind.
  544. state.CachedTexture = null;
  545. }
  546. else
  547. {
  548. if (isStore)
  549. {
  550. texture?.SignalModified();
  551. }
  552. if ((usageFlags & TextureUsageFlags.NeedsScaleValue) != 0 &&
  553. UpdateScale(texture, usageFlags, scaleIndex, stage))
  554. {
  555. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  556. }
  557. if (state.Texture != hostTexture)
  558. {
  559. state.Texture = hostTexture;
  560. Format format = bindingInfo.Format;
  561. if (format == 0 && texture != null)
  562. {
  563. format = texture.Format;
  564. }
  565. state.ImageFormat = format;
  566. _context.Renderer.Pipeline.SetImage(stage, bindingInfo.Binding, hostTexture, format);
  567. }
  568. state.CachedTexture = texture;
  569. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  570. }
  571. }
  572. return specStateMatches;
  573. }
  574. /// <summary>
  575. /// Gets the texture descriptor for a given texture handle.
  576. /// </summary>
  577. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  578. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  579. /// <param name="maximumId">Maximum ID of the texture pool</param>
  580. /// <param name="stageIndex">The stage number where the texture is bound</param>
  581. /// <param name="handle">The texture handle</param>
  582. /// <param name="cbufSlot">The texture handle's constant buffer slot</param>
  583. /// <returns>The texture descriptor for the specified texture</returns>
  584. public TextureDescriptor GetTextureDescriptor(
  585. ulong poolGpuVa,
  586. int bufferIndex,
  587. int maximumId,
  588. int stageIndex,
  589. int handle,
  590. int cbufSlot)
  591. {
  592. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(cbufSlot, bufferIndex);
  593. int packedId = ReadPackedId(stageIndex, handle, textureBufferIndex, samplerBufferIndex);
  594. int textureId = TextureHandle.UnpackTextureId(packedId);
  595. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  596. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  597. TextureDescriptor descriptor;
  598. if (texturePool.IsValidId(textureId))
  599. {
  600. descriptor = texturePool.GetDescriptor(textureId);
  601. }
  602. else
  603. {
  604. // If the ID is not valid, we just return a default descriptor with the most common state.
  605. // Since this is used for shader specialization, doing so might avoid the need for recompilations.
  606. descriptor = new TextureDescriptor();
  607. descriptor.Word4 |= (uint)TextureTarget.Texture2D << 23;
  608. descriptor.Word5 |= 1u << 31; // Coords normalized.
  609. }
  610. return descriptor;
  611. }
  612. /// <summary>
  613. /// Reads a packed texture and sampler ID (basically, the real texture handle)
  614. /// from the texture constant buffer.
  615. /// </summary>
  616. /// <param name="stageIndex">The number of the shader stage where the texture is bound</param>
  617. /// <param name="wordOffset">A word offset of the handle on the buffer (the "fake" shader handle)</param>
  618. /// <param name="textureBufferIndex">Index of the constant buffer holding the texture handles</param>
  619. /// <param name="samplerBufferIndex">Index of the constant buffer holding the sampler handles</param>
  620. /// <returns>The packed texture and sampler ID (the real texture handle)</returns>
  621. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  622. private int ReadPackedId(int stageIndex, int wordOffset, int textureBufferIndex, int samplerBufferIndex)
  623. {
  624. (int textureWordOffset, int samplerWordOffset, TextureHandleType handleType) = TextureHandle.UnpackOffsets(wordOffset);
  625. ulong textureBufferAddress = _isCompute
  626. ? _channel.BufferManager.GetComputeUniformBufferAddress(textureBufferIndex)
  627. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, textureBufferIndex);
  628. int handle = textureBufferAddress != 0
  629. ? _channel.MemoryManager.Physical.Read<int>(textureBufferAddress + (uint)textureWordOffset * 4)
  630. : 0;
  631. // The "wordOffset" (which is really the immediate value used on texture instructions on the shader)
  632. // is a 13-bit value. However, in order to also support separate samplers and textures (which uses
  633. // bindless textures on the shader), we extend it with another value on the higher 16 bits with
  634. // another offset for the sampler.
  635. // The shader translator has code to detect separate texture and sampler uses with a bindless texture,
  636. // turn that into a regular texture access and produce those special handles with values on the higher 16 bits.
  637. if (handleType != TextureHandleType.CombinedSampler)
  638. {
  639. int samplerHandle;
  640. if (handleType != TextureHandleType.SeparateConstantSamplerHandle)
  641. {
  642. ulong samplerBufferAddress = _isCompute
  643. ? _channel.BufferManager.GetComputeUniformBufferAddress(samplerBufferIndex)
  644. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, samplerBufferIndex);
  645. samplerHandle = samplerBufferAddress != 0
  646. ? _channel.MemoryManager.Physical.Read<int>(samplerBufferAddress + (uint)samplerWordOffset * 4)
  647. : 0;
  648. }
  649. else
  650. {
  651. samplerHandle = samplerWordOffset;
  652. }
  653. if (handleType == TextureHandleType.SeparateSamplerId ||
  654. handleType == TextureHandleType.SeparateConstantSamplerHandle)
  655. {
  656. samplerHandle <<= 20;
  657. }
  658. handle |= samplerHandle;
  659. }
  660. return handle;
  661. }
  662. /// <summary>
  663. /// Gets the texture and sampler pool for the GPU virtual address that are currently set.
  664. /// </summary>
  665. /// <returns>The texture and sampler pools</returns>
  666. private (TexturePool, SamplerPool) GetPools()
  667. {
  668. MemoryManager memoryManager = _channel.MemoryManager;
  669. TexturePool texturePool = _texturePool;
  670. SamplerPool samplerPool = _samplerPool;
  671. if (texturePool == null)
  672. {
  673. ulong poolAddress = memoryManager.Translate(_texturePoolGpuVa);
  674. if (poolAddress != MemoryManager.PteUnmapped)
  675. {
  676. texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, _texturePoolMaximumId);
  677. _texturePool = texturePool;
  678. }
  679. }
  680. if (samplerPool == null)
  681. {
  682. ulong poolAddress = memoryManager.Translate(_samplerPoolGpuVa);
  683. if (poolAddress != MemoryManager.PteUnmapped)
  684. {
  685. samplerPool = _samplerPoolCache.FindOrCreate(_channel, poolAddress, _samplerPoolMaximumId);
  686. _samplerPool = samplerPool;
  687. }
  688. }
  689. return (texturePool, samplerPool);
  690. }
  691. /// <summary>
  692. /// Forces the texture and sampler pools to be re-loaded from the cache on next use.
  693. /// </summary>
  694. /// <remarks>
  695. /// This should be called if the memory mappings change, to ensure the correct pools are being used.
  696. /// </remarks>
  697. public void ReloadPools()
  698. {
  699. _samplerPool = null;
  700. _texturePool = null;
  701. }
  702. /// <summary>
  703. /// Force all bound textures and images to be rebound the next time CommitBindings is called.
  704. /// </summary>
  705. public void Rebind()
  706. {
  707. Array.Clear(_textureState);
  708. Array.Clear(_imageState);
  709. }
  710. }
  711. }