TextureBindingsManager.cs 36 KB

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