TextureBindingsManager.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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. /// Determines if the vertex stage requires a scale value.
  239. /// </summary>
  240. private bool VertexRequiresScale()
  241. {
  242. for (int i = 0; i < _textureBindingsCount[0]; i++)
  243. {
  244. if ((_textureBindings[0][i].Flags & TextureUsageFlags.NeedsScaleValue) != 0)
  245. {
  246. return true;
  247. }
  248. }
  249. for (int i = 0; i < _imageBindingsCount[0]; i++)
  250. {
  251. if ((_imageBindings[0][i].Flags & TextureUsageFlags.NeedsScaleValue) != 0)
  252. {
  253. return true;
  254. }
  255. }
  256. return false;
  257. }
  258. /// <summary>
  259. /// Uploads texture and image scales to the backend when they are used.
  260. /// </summary>
  261. private void CommitRenderScale()
  262. {
  263. // Stage 0 total: Compute or Vertex.
  264. int total = _textureBindingsCount[0] + _imageBindingsCount[0];
  265. int fragmentIndex = (int)ShaderStage.Fragment - 1;
  266. int fragmentTotal = _isCompute ? 0 : (_textureBindingsCount[fragmentIndex] + _imageBindingsCount[fragmentIndex]);
  267. if (total != 0 && fragmentTotal != _lastFragmentTotal && VertexRequiresScale())
  268. {
  269. // Must update scales in the support buffer if:
  270. // - Vertex stage has bindings that require scale.
  271. // - Fragment stage binding count has been updated since last render scale update.
  272. _scaleChanged = true;
  273. }
  274. if (_scaleChanged)
  275. {
  276. if (!_isCompute)
  277. {
  278. total += fragmentTotal; // Add the fragment bindings to the total.
  279. }
  280. _lastFragmentTotal = fragmentTotal;
  281. _context.Renderer.Pipeline.UpdateRenderScale(_scales, total, fragmentTotal);
  282. _scaleChanged = false;
  283. }
  284. }
  285. /// <summary>
  286. /// Ensures that the bindings are visible to the host GPU.
  287. /// Note: this actually performs the binding using the host graphics API.
  288. /// </summary>
  289. /// <param name="specState">Specialization state for the bound shader</param>
  290. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  291. public bool CommitBindings(ShaderSpecializationState specState)
  292. {
  293. (TexturePool texturePool, SamplerPool samplerPool) = GetPools();
  294. // Check if the texture pool has been modified since bindings were last committed.
  295. // If it wasn't, then it's possible to avoid looking up textures again when the handle remains the same.
  296. bool poolModified = _cachedTexturePool != texturePool || _cachedSamplerPool != samplerPool;
  297. _cachedTexturePool = texturePool;
  298. _cachedSamplerPool = samplerPool;
  299. if (texturePool != null)
  300. {
  301. int texturePoolSequence = texturePool.CheckModified();
  302. if (_texturePoolSequence != texturePoolSequence)
  303. {
  304. poolModified = true;
  305. _texturePoolSequence = texturePoolSequence;
  306. }
  307. }
  308. if (samplerPool != null)
  309. {
  310. int samplerPoolSequence = samplerPool.CheckModified();
  311. if (_samplerPoolSequence != samplerPoolSequence)
  312. {
  313. poolModified = true;
  314. _samplerPoolSequence = samplerPoolSequence;
  315. }
  316. }
  317. bool specStateMatches = true;
  318. if (_isCompute)
  319. {
  320. specStateMatches &= CommitTextureBindings(texturePool, samplerPool, ShaderStage.Compute, 0, poolModified, specState);
  321. specStateMatches &= CommitImageBindings(texturePool, ShaderStage.Compute, 0, poolModified, specState);
  322. }
  323. else
  324. {
  325. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  326. {
  327. int stageIndex = (int)stage - 1;
  328. specStateMatches &= CommitTextureBindings(texturePool, samplerPool, stage, stageIndex, poolModified, specState);
  329. specStateMatches &= CommitImageBindings(texturePool, stage, stageIndex, poolModified, specState);
  330. }
  331. }
  332. CommitRenderScale();
  333. return specStateMatches;
  334. }
  335. /// <summary>
  336. /// Fetch the constant buffers used for a texture to cache.
  337. /// </summary>
  338. /// <param name="stageIndex">Stage index of the constant buffer</param>
  339. /// <param name="cachedTextureBufferIndex">The currently cached texture buffer index</param>
  340. /// <param name="cachedSamplerBufferIndex">The currently cached sampler buffer index</param>
  341. /// <param name="cachedTextureBuffer">The currently cached texture buffer data</param>
  342. /// <param name="cachedSamplerBuffer">The currently cached sampler buffer data</param>
  343. /// <param name="textureBufferIndex">The new texture buffer index</param>
  344. /// <param name="samplerBufferIndex">The new sampler buffer index</param>
  345. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  346. private void UpdateCachedBuffer(
  347. int stageIndex,
  348. ref int cachedTextureBufferIndex,
  349. ref int cachedSamplerBufferIndex,
  350. ref ReadOnlySpan<int> cachedTextureBuffer,
  351. ref ReadOnlySpan<int> cachedSamplerBuffer,
  352. int textureBufferIndex,
  353. int samplerBufferIndex)
  354. {
  355. if (textureBufferIndex != cachedTextureBufferIndex)
  356. {
  357. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, textureBufferIndex);
  358. cachedTextureBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Address, (int)bounds.Size));
  359. cachedTextureBufferIndex = textureBufferIndex;
  360. if (samplerBufferIndex == textureBufferIndex)
  361. {
  362. cachedSamplerBuffer = cachedTextureBuffer;
  363. cachedSamplerBufferIndex = samplerBufferIndex;
  364. }
  365. }
  366. if (samplerBufferIndex != cachedSamplerBufferIndex)
  367. {
  368. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, samplerBufferIndex);
  369. cachedSamplerBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Address, (int)bounds.Size));
  370. cachedSamplerBufferIndex = samplerBufferIndex;
  371. }
  372. }
  373. /// <summary>
  374. /// Counts the total number of texture bindings used by all shader stages.
  375. /// </summary>
  376. /// <returns>The total amount of textures used</returns>
  377. private int GetTextureBindingsCount()
  378. {
  379. int count = 0;
  380. for (int i = 0; i < _textureBindings.Length; i++)
  381. {
  382. if (_textureBindings[i] != null)
  383. {
  384. count += _textureBindings[i].Length;
  385. }
  386. }
  387. return count;
  388. }
  389. /// <summary>
  390. /// Ensures that the texture bindings are visible to the host GPU.
  391. /// Note: this actually performs the binding using the host graphics API.
  392. /// </summary>
  393. /// <param name="texturePool">The current texture pool</param>
  394. /// <param name="samplerPool">The current sampler pool</param>
  395. /// <param name="stage">The shader stage using the textures to be bound</param>
  396. /// <param name="stageIndex">The stage number of the specified shader stage</param
  397. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  398. /// <param name="specState">Specialization state for the bound shader</param>
  399. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  400. private bool CommitTextureBindings(
  401. TexturePool texturePool,
  402. SamplerPool samplerPool,
  403. ShaderStage stage,
  404. int stageIndex,
  405. bool poolModified,
  406. ShaderSpecializationState specState)
  407. {
  408. int textureCount = _textureBindingsCount[stageIndex];
  409. if (textureCount == 0)
  410. {
  411. return true;
  412. }
  413. if (texturePool == null)
  414. {
  415. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses textures, but texture pool was not set.");
  416. return true;
  417. }
  418. bool specStateMatches = true;
  419. int cachedTextureBufferIndex = -1;
  420. int cachedSamplerBufferIndex = -1;
  421. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  422. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  423. for (int index = 0; index < textureCount; index++)
  424. {
  425. TextureBindingInfo bindingInfo = _textureBindings[stageIndex][index];
  426. TextureUsageFlags usageFlags = bindingInfo.Flags;
  427. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  428. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  429. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  430. int textureId = TextureHandle.UnpackTextureId(packedId);
  431. int samplerId;
  432. if (_samplerIndex == SamplerIndex.ViaHeaderIndex)
  433. {
  434. samplerId = textureId;
  435. }
  436. else
  437. {
  438. samplerId = TextureHandle.UnpackSamplerId(packedId);
  439. }
  440. ref TextureState state = ref _textureState[bindingInfo.Binding];
  441. if (!poolModified &&
  442. state.TextureHandle == textureId &&
  443. state.SamplerHandle == samplerId &&
  444. state.CachedTexture != null &&
  445. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence &&
  446. state.CachedSampler?.IsDisposed != true)
  447. {
  448. // The texture is already bound.
  449. state.CachedTexture.SynchronizeMemory();
  450. if ((state.ScaleIndex != index || state.UsageFlags != usageFlags) &&
  451. UpdateScale(state.CachedTexture, usageFlags, index, stage))
  452. {
  453. ITexture hostTextureRebind = state.CachedTexture.GetTargetTexture(bindingInfo.Target);
  454. state.Texture = hostTextureRebind;
  455. state.ScaleIndex = index;
  456. state.UsageFlags = usageFlags;
  457. _context.Renderer.Pipeline.SetTextureAndSampler(stage, bindingInfo.Binding, hostTextureRebind, state.Sampler);
  458. }
  459. continue;
  460. }
  461. state.TextureHandle = textureId;
  462. state.SamplerHandle = samplerId;
  463. ref readonly TextureDescriptor descriptor = ref texturePool.GetForBinding(textureId, out Texture texture);
  464. specStateMatches &= specState.MatchesTexture(stage, index, descriptor);
  465. Sampler sampler = _samplerPool?.Get(samplerId);
  466. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  467. ISampler hostSampler = sampler?.GetHostSampler(texture);
  468. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  469. {
  470. // Ensure that the buffer texture is using the correct buffer as storage.
  471. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  472. // to ensure we're not using a old buffer that was already deleted.
  473. _channel.BufferManager.SetBufferTextureStorage(stage, hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, bindingInfo.Format, false);
  474. }
  475. else
  476. {
  477. bool textureOrSamplerChanged = state.Texture != hostTexture || state.Sampler != hostSampler;
  478. if ((state.ScaleIndex != index || state.UsageFlags != usageFlags || textureOrSamplerChanged) &&
  479. UpdateScale(texture, usageFlags, index, stage))
  480. {
  481. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  482. textureOrSamplerChanged = true;
  483. }
  484. if (textureOrSamplerChanged)
  485. {
  486. state.Texture = hostTexture;
  487. state.ScaleIndex = index;
  488. state.UsageFlags = usageFlags;
  489. state.Sampler = hostSampler;
  490. _context.Renderer.Pipeline.SetTextureAndSampler(stage, bindingInfo.Binding, hostTexture, hostSampler);
  491. }
  492. state.CachedTexture = texture;
  493. state.CachedSampler = sampler;
  494. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  495. }
  496. }
  497. return specStateMatches;
  498. }
  499. /// <summary>
  500. /// Ensures that the image bindings are visible to the host GPU.
  501. /// Note: this actually performs the binding using the host graphics API.
  502. /// </summary>
  503. /// <param name="pool">The current texture pool</param>
  504. /// <param name="stage">The shader stage using the textures to be bound</param>
  505. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  506. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  507. /// <param name="specState">Specialization state for the bound shader</param>
  508. /// <returns>True if all bound images match the current shader specialiation state, false otherwise</returns>
  509. private bool CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex, bool poolModified, ShaderSpecializationState specState)
  510. {
  511. int imageCount = _imageBindingsCount[stageIndex];
  512. if (imageCount == 0)
  513. {
  514. return true;
  515. }
  516. if (pool == null)
  517. {
  518. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses images, but texture pool was not set.");
  519. return true;
  520. }
  521. // Scales for images appear after the texture ones.
  522. int baseScaleIndex = _textureBindingsCount[stageIndex];
  523. int cachedTextureBufferIndex = -1;
  524. int cachedSamplerBufferIndex = -1;
  525. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  526. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  527. bool specStateMatches = true;
  528. for (int index = 0; index < imageCount; index++)
  529. {
  530. TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];
  531. TextureUsageFlags usageFlags = bindingInfo.Flags;
  532. int scaleIndex = baseScaleIndex + index;
  533. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  534. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  535. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  536. int textureId = TextureHandle.UnpackTextureId(packedId);
  537. ref TextureState state = ref _imageState[bindingInfo.Binding];
  538. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  539. if (!poolModified &&
  540. state.TextureHandle == textureId &&
  541. state.CachedTexture != null &&
  542. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence)
  543. {
  544. Texture cachedTexture = state.CachedTexture;
  545. // The texture is already bound.
  546. cachedTexture.SynchronizeMemory();
  547. if (isStore)
  548. {
  549. cachedTexture?.SignalModified();
  550. }
  551. if ((state.ScaleIndex != scaleIndex || state.UsageFlags != usageFlags) &&
  552. UpdateScale(state.CachedTexture, usageFlags, scaleIndex, stage))
  553. {
  554. ITexture hostTextureRebind = state.CachedTexture.GetTargetTexture(bindingInfo.Target);
  555. Format format = bindingInfo.Format == 0 ? cachedTexture.Format : bindingInfo.Format;
  556. state.Texture = hostTextureRebind;
  557. state.ScaleIndex = scaleIndex;
  558. state.UsageFlags = usageFlags;
  559. _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTextureRebind, format);
  560. }
  561. continue;
  562. }
  563. state.TextureHandle = textureId;
  564. ref readonly TextureDescriptor descriptor = ref pool.GetForBinding(textureId, out Texture texture);
  565. specStateMatches &= specState.MatchesImage(stage, index, descriptor);
  566. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  567. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  568. {
  569. // Ensure that the buffer texture is using the correct buffer as storage.
  570. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  571. // to ensure we're not using a old buffer that was already deleted.
  572. Format format = bindingInfo.Format;
  573. if (format == 0 && texture != null)
  574. {
  575. format = texture.Format;
  576. }
  577. _channel.BufferManager.SetBufferTextureStorage(stage, hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, format, true);
  578. }
  579. else
  580. {
  581. if (isStore)
  582. {
  583. texture?.SignalModified();
  584. }
  585. if ((state.ScaleIndex != scaleIndex || state.UsageFlags != usageFlags || state.Texture != hostTexture) &&
  586. UpdateScale(texture, usageFlags, scaleIndex, stage))
  587. {
  588. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  589. }
  590. if (state.Texture != hostTexture)
  591. {
  592. state.Texture = hostTexture;
  593. state.ScaleIndex = scaleIndex;
  594. state.UsageFlags = usageFlags;
  595. Format format = bindingInfo.Format;
  596. if (format == 0 && texture != null)
  597. {
  598. format = texture.Format;
  599. }
  600. _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTexture, format);
  601. }
  602. state.CachedTexture = texture;
  603. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  604. }
  605. }
  606. return specStateMatches;
  607. }
  608. /// <summary>
  609. /// Gets the texture descriptor for a given texture handle.
  610. /// </summary>
  611. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  612. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  613. /// <param name="maximumId">Maximum ID of the texture pool</param>
  614. /// <param name="stageIndex">The stage number where the texture is bound</param>
  615. /// <param name="handle">The texture handle</param>
  616. /// <param name="cbufSlot">The texture handle's constant buffer slot</param>
  617. /// <returns>The texture descriptor for the specified texture</returns>
  618. public TextureDescriptor GetTextureDescriptor(
  619. ulong poolGpuVa,
  620. int bufferIndex,
  621. int maximumId,
  622. int stageIndex,
  623. int handle,
  624. int cbufSlot)
  625. {
  626. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(cbufSlot, bufferIndex);
  627. int packedId = ReadPackedId(stageIndex, handle, textureBufferIndex, samplerBufferIndex);
  628. int textureId = TextureHandle.UnpackTextureId(packedId);
  629. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  630. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  631. TextureDescriptor descriptor;
  632. if (texturePool.IsValidId(textureId))
  633. {
  634. descriptor = texturePool.GetDescriptor(textureId);
  635. }
  636. else
  637. {
  638. // If the ID is not valid, we just return a default descriptor with the most common state.
  639. // Since this is used for shader specialization, doing so might avoid the need for recompilations.
  640. descriptor = new TextureDescriptor();
  641. descriptor.Word4 |= (uint)TextureTarget.Texture2D << 23;
  642. descriptor.Word5 |= 1u << 31; // Coords normalized.
  643. }
  644. return descriptor;
  645. }
  646. /// <summary>
  647. /// Reads a packed texture and sampler ID (basically, the real texture handle)
  648. /// from the texture constant buffer.
  649. /// </summary>
  650. /// <param name="stageIndex">The number of the shader stage where the texture is bound</param>
  651. /// <param name="wordOffset">A word offset of the handle on the buffer (the "fake" shader handle)</param>
  652. /// <param name="textureBufferIndex">Index of the constant buffer holding the texture handles</param>
  653. /// <param name="samplerBufferIndex">Index of the constant buffer holding the sampler handles</param>
  654. /// <returns>The packed texture and sampler ID (the real texture handle)</returns>
  655. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  656. private int ReadPackedId(int stageIndex, int wordOffset, int textureBufferIndex, int samplerBufferIndex)
  657. {
  658. (int textureWordOffset, int samplerWordOffset, TextureHandleType handleType) = TextureHandle.UnpackOffsets(wordOffset);
  659. ulong textureBufferAddress = _isCompute
  660. ? _channel.BufferManager.GetComputeUniformBufferAddress(textureBufferIndex)
  661. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, textureBufferIndex);
  662. int handle = _channel.MemoryManager.Physical.Read<int>(textureBufferAddress + (uint)textureWordOffset * 4);
  663. // The "wordOffset" (which is really the immediate value used on texture instructions on the shader)
  664. // is a 13-bit value. However, in order to also support separate samplers and textures (which uses
  665. // bindless textures on the shader), we extend it with another value on the higher 16 bits with
  666. // another offset for the sampler.
  667. // The shader translator has code to detect separate texture and sampler uses with a bindless texture,
  668. // turn that into a regular texture access and produce those special handles with values on the higher 16 bits.
  669. if (handleType != TextureHandleType.CombinedSampler)
  670. {
  671. int samplerHandle;
  672. if (handleType != TextureHandleType.SeparateConstantSamplerHandle)
  673. {
  674. ulong samplerBufferAddress = _isCompute
  675. ? _channel.BufferManager.GetComputeUniformBufferAddress(samplerBufferIndex)
  676. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, samplerBufferIndex);
  677. samplerHandle = _channel.MemoryManager.Physical.Read<int>(samplerBufferAddress + (uint)samplerWordOffset * 4);
  678. }
  679. else
  680. {
  681. samplerHandle = samplerWordOffset;
  682. }
  683. if (handleType == TextureHandleType.SeparateSamplerId ||
  684. handleType == TextureHandleType.SeparateConstantSamplerHandle)
  685. {
  686. samplerHandle <<= 20;
  687. }
  688. handle |= samplerHandle;
  689. }
  690. return handle;
  691. }
  692. /// <summary>
  693. /// Gets the texture and sampler pool for the GPU virtual address that are currently set.
  694. /// </summary>
  695. /// <returns>The texture and sampler pools</returns>
  696. private (TexturePool, SamplerPool) GetPools()
  697. {
  698. MemoryManager memoryManager = _channel.MemoryManager;
  699. TexturePool texturePool = _texturePool;
  700. SamplerPool samplerPool = _samplerPool;
  701. if (texturePool == null)
  702. {
  703. ulong poolAddress = memoryManager.Translate(_texturePoolGpuVa);
  704. if (poolAddress != MemoryManager.PteUnmapped)
  705. {
  706. texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, _texturePoolMaximumId);
  707. _texturePool = texturePool;
  708. }
  709. }
  710. if (samplerPool == null)
  711. {
  712. ulong poolAddress = memoryManager.Translate(_samplerPoolGpuVa);
  713. if (poolAddress != MemoryManager.PteUnmapped)
  714. {
  715. samplerPool = _samplerPoolCache.FindOrCreate(_channel, poolAddress, _samplerPoolMaximumId);
  716. _samplerPool = samplerPool;
  717. }
  718. }
  719. return (texturePool, samplerPool);
  720. }
  721. /// <summary>
  722. /// Forces the texture and sampler pools to be re-loaded from the cache on next use.
  723. /// </summary>
  724. /// <remarks>
  725. /// This should be called if the memory mappings change, to ensure the correct pools are being used.
  726. /// </remarks>
  727. public void ReloadPools()
  728. {
  729. _samplerPool = null;
  730. _texturePool = null;
  731. }
  732. /// <summary>
  733. /// Force all bound textures and images to be rebound the next time CommitBindings is called.
  734. /// </summary>
  735. public void Rebind()
  736. {
  737. Array.Clear(_textureState);
  738. Array.Clear(_imageState);
  739. }
  740. }
  741. }