TextureBindingsManager.cs 37 KB

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