ResourceManager.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. namespace Ryujinx.Graphics.Shader.Translation
  8. {
  9. class ResourceManager
  10. {
  11. // Those values are used if the shader as local or shared memory access,
  12. // but for some reason the supplied size was 0.
  13. private const int DefaultLocalMemorySize = 128;
  14. private const int DefaultSharedMemorySize = 4096;
  15. // TODO: Non-hardcoded array size.
  16. public const int SamplerArraySize = 4;
  17. private static readonly string[] _stagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
  18. private readonly IGpuAccessor _gpuAccessor;
  19. private readonly ShaderStage _stage;
  20. private readonly string _stagePrefix;
  21. private readonly int[] _cbSlotToBindingMap;
  22. private readonly int[] _sbSlotToBindingMap;
  23. private uint _sbSlotWritten;
  24. private readonly Dictionary<int, int> _sbSlots;
  25. private readonly Dictionary<int, int> _sbSlotsReverse;
  26. private readonly HashSet<int> _usedConstantBufferBindings;
  27. private readonly record struct TextureInfo(int CbufSlot, int Handle, bool Indexed, TextureFormat Format);
  28. private struct TextureMeta
  29. {
  30. public int Binding;
  31. public bool AccurateType;
  32. public SamplerType Type;
  33. public TextureUsageFlags UsageFlags;
  34. }
  35. private readonly Dictionary<TextureInfo, TextureMeta> _usedTextures;
  36. private readonly Dictionary<TextureInfo, TextureMeta> _usedImages;
  37. public int LocalMemoryId { get; private set; }
  38. public int SharedMemoryId { get; private set; }
  39. public ShaderProperties Properties { get; }
  40. public ResourceManager(ShaderStage stage, IGpuAccessor gpuAccessor, ShaderProperties properties)
  41. {
  42. _gpuAccessor = gpuAccessor;
  43. Properties = properties;
  44. _stage = stage;
  45. _stagePrefix = GetShaderStagePrefix(stage);
  46. _cbSlotToBindingMap = new int[18];
  47. _sbSlotToBindingMap = new int[16];
  48. _cbSlotToBindingMap.AsSpan().Fill(-1);
  49. _sbSlotToBindingMap.AsSpan().Fill(-1);
  50. _sbSlots = new Dictionary<int, int>();
  51. _sbSlotsReverse = new Dictionary<int, int>();
  52. _usedConstantBufferBindings = new HashSet<int>();
  53. _usedTextures = new Dictionary<TextureInfo, TextureMeta>();
  54. _usedImages = new Dictionary<TextureInfo, TextureMeta>();
  55. properties.AddOrUpdateConstantBuffer(0, new BufferDefinition(BufferLayout.Std140, 0, 0, "support_buffer", SupportBuffer.GetStructureType()));
  56. LocalMemoryId = -1;
  57. SharedMemoryId = -1;
  58. }
  59. public void SetCurrentLocalMemory(int size, bool isUsed)
  60. {
  61. if (isUsed)
  62. {
  63. if (size <= 0)
  64. {
  65. size = DefaultLocalMemorySize;
  66. }
  67. var lmem = new MemoryDefinition("local_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
  68. LocalMemoryId = Properties.AddLocalMemory(lmem);
  69. }
  70. else
  71. {
  72. LocalMemoryId = -1;
  73. }
  74. }
  75. public void SetCurrentSharedMemory(int size, bool isUsed)
  76. {
  77. if (isUsed)
  78. {
  79. if (size <= 0)
  80. {
  81. size = DefaultSharedMemorySize;
  82. }
  83. var smem = new MemoryDefinition("shared_memory", AggregateType.Array | AggregateType.U32, BitUtils.DivRoundUp(size, sizeof(uint)));
  84. SharedMemoryId = Properties.AddSharedMemory(smem);
  85. }
  86. else
  87. {
  88. SharedMemoryId = -1;
  89. }
  90. }
  91. public int GetConstantBufferBinding(int slot)
  92. {
  93. int binding = _cbSlotToBindingMap[slot];
  94. if (binding < 0)
  95. {
  96. binding = _gpuAccessor.QueryBindingConstantBuffer(slot);
  97. _cbSlotToBindingMap[slot] = binding;
  98. string slotNumber = slot.ToString(CultureInfo.InvariantCulture);
  99. AddNewConstantBuffer(binding, $"{_stagePrefix}_c{slotNumber}");
  100. }
  101. return binding;
  102. }
  103. public bool TryGetStorageBufferBinding(int sbCbSlot, int sbCbOffset, bool write, out int binding)
  104. {
  105. if (!TryGetSbSlot((byte)sbCbSlot, (ushort)sbCbOffset, out int slot))
  106. {
  107. binding = 0;
  108. return false;
  109. }
  110. binding = _sbSlotToBindingMap[slot];
  111. if (binding < 0)
  112. {
  113. binding = _gpuAccessor.QueryBindingStorageBuffer(slot);
  114. _sbSlotToBindingMap[slot] = binding;
  115. string slotNumber = slot.ToString(CultureInfo.InvariantCulture);
  116. AddNewStorageBuffer(binding, $"{_stagePrefix}_s{slotNumber}");
  117. }
  118. if (write)
  119. {
  120. _sbSlotWritten |= 1u << slot;
  121. }
  122. return true;
  123. }
  124. private bool TryGetSbSlot(byte sbCbSlot, ushort sbCbOffset, out int slot)
  125. {
  126. int key = PackSbCbInfo(sbCbSlot, sbCbOffset);
  127. if (!_sbSlots.TryGetValue(key, out slot))
  128. {
  129. slot = _sbSlots.Count;
  130. if (slot >= _sbSlotToBindingMap.Length)
  131. {
  132. return false;
  133. }
  134. _sbSlots.Add(key, slot);
  135. _sbSlotsReverse.Add(slot, key);
  136. }
  137. return true;
  138. }
  139. public bool TryGetConstantBufferSlot(int binding, out int slot)
  140. {
  141. for (slot = 0; slot < _cbSlotToBindingMap.Length; slot++)
  142. {
  143. if (_cbSlotToBindingMap[slot] == binding)
  144. {
  145. return true;
  146. }
  147. }
  148. slot = 0;
  149. return false;
  150. }
  151. public int GetTextureOrImageBinding(
  152. Instruction inst,
  153. SamplerType type,
  154. TextureFormat format,
  155. TextureFlags flags,
  156. int cbufSlot,
  157. int handle)
  158. {
  159. inst &= Instruction.Mask;
  160. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  161. bool isWrite = inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  162. bool accurateType = inst != Instruction.Lod && inst != Instruction.TextureSize;
  163. bool intCoords = isImage || flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  164. bool coherent = flags.HasFlag(TextureFlags.Coherent);
  165. if (!isImage)
  166. {
  167. format = TextureFormat.Unknown;
  168. }
  169. int binding = GetTextureOrImageBinding(cbufSlot, handle, type, format, isImage, intCoords, isWrite, accurateType, coherent);
  170. _gpuAccessor.RegisterTexture(handle, cbufSlot);
  171. return binding;
  172. }
  173. private int GetTextureOrImageBinding(
  174. int cbufSlot,
  175. int handle,
  176. SamplerType type,
  177. TextureFormat format,
  178. bool isImage,
  179. bool intCoords,
  180. bool write,
  181. bool accurateType,
  182. bool coherent)
  183. {
  184. var dimensions = type.GetDimensions();
  185. var isIndexed = type.HasFlag(SamplerType.Indexed);
  186. var dict = isImage ? _usedImages : _usedTextures;
  187. var usageFlags = TextureUsageFlags.None;
  188. if (intCoords)
  189. {
  190. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  191. var canScale = _stage.SupportsRenderScale() && !isIndexed && !write && dimensions == 2;
  192. if (!canScale)
  193. {
  194. // Resolution scaling cannot be applied to this texture right now.
  195. // Flag so that we know to blacklist scaling on related textures when binding them.
  196. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  197. }
  198. }
  199. if (write)
  200. {
  201. usageFlags |= TextureUsageFlags.ImageStore;
  202. }
  203. if (coherent)
  204. {
  205. usageFlags |= TextureUsageFlags.ImageCoherent;
  206. }
  207. int arraySize = isIndexed ? SamplerArraySize : 1;
  208. int firstBinding = -1;
  209. for (int layer = 0; layer < arraySize; layer++)
  210. {
  211. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  212. var meta = new TextureMeta()
  213. {
  214. AccurateType = accurateType,
  215. Type = type,
  216. UsageFlags = usageFlags
  217. };
  218. int binding;
  219. if (dict.TryGetValue(info, out var existingMeta))
  220. {
  221. dict[info] = MergeTextureMeta(meta, existingMeta);
  222. binding = existingMeta.Binding;
  223. }
  224. else
  225. {
  226. bool isBuffer = (type & SamplerType.Mask) == SamplerType.TextureBuffer;
  227. binding = isImage
  228. ? _gpuAccessor.QueryBindingImage(dict.Count, isBuffer)
  229. : _gpuAccessor.QueryBindingTexture(dict.Count, isBuffer);
  230. meta.Binding = binding;
  231. dict.Add(info, meta);
  232. }
  233. string nameSuffix;
  234. if (isImage)
  235. {
  236. nameSuffix = cbufSlot < 0
  237. ? $"i_tcb_{handle:X}_{format.ToGlslFormat()}"
  238. : $"i_cb{cbufSlot}_{handle:X}_{format.ToGlslFormat()}";
  239. }
  240. else
  241. {
  242. nameSuffix = cbufSlot < 0 ? $"t_tcb_{handle:X}" : $"t_cb{cbufSlot}_{handle:X}";
  243. }
  244. var definition = new TextureDefinition(
  245. isImage ? 3 : 2,
  246. binding,
  247. $"{_stagePrefix}_{nameSuffix}",
  248. meta.Type,
  249. info.Format,
  250. meta.UsageFlags);
  251. if (isImage)
  252. {
  253. Properties.AddOrUpdateImage(binding, definition);
  254. }
  255. else
  256. {
  257. Properties.AddOrUpdateTexture(binding, definition);
  258. }
  259. if (layer == 0)
  260. {
  261. firstBinding = binding;
  262. }
  263. }
  264. return firstBinding;
  265. }
  266. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  267. {
  268. meta.Binding = existingMeta.Binding;
  269. meta.UsageFlags |= existingMeta.UsageFlags;
  270. // If the texture we have has inaccurate type information, then
  271. // we prefer the most accurate one.
  272. if (existingMeta.AccurateType)
  273. {
  274. meta.AccurateType = true;
  275. meta.Type = existingMeta.Type;
  276. }
  277. return meta;
  278. }
  279. public void SetUsageFlagsForTextureQuery(int binding, SamplerType type)
  280. {
  281. TextureInfo selectedInfo = default;
  282. TextureMeta selectedMeta = default;
  283. bool found = false;
  284. foreach ((TextureInfo info, TextureMeta meta) in _usedTextures)
  285. {
  286. if (meta.Binding == binding)
  287. {
  288. selectedInfo = info;
  289. selectedMeta = meta;
  290. found = true;
  291. break;
  292. }
  293. }
  294. if (found)
  295. {
  296. selectedMeta.UsageFlags |= TextureUsageFlags.NeedsScaleValue;
  297. var dimensions = type.GetDimensions();
  298. var isIndexed = type.HasFlag(SamplerType.Indexed);
  299. var canScale = _stage.SupportsRenderScale() && !isIndexed && dimensions == 2;
  300. if (!canScale)
  301. {
  302. // Resolution scaling cannot be applied to this texture right now.
  303. // Flag so that we know to blacklist scaling on related textures when binding them.
  304. selectedMeta.UsageFlags |= TextureUsageFlags.ResScaleUnsupported;
  305. }
  306. _usedTextures[selectedInfo] = selectedMeta;
  307. }
  308. }
  309. public void SetUsedConstantBufferBinding(int binding)
  310. {
  311. _usedConstantBufferBindings.Add(binding);
  312. }
  313. public BufferDescriptor[] GetConstantBufferDescriptors()
  314. {
  315. var descriptors = new BufferDescriptor[_usedConstantBufferBindings.Count];
  316. int descriptorIndex = 0;
  317. for (int slot = 0; slot < _cbSlotToBindingMap.Length; slot++)
  318. {
  319. int binding = _cbSlotToBindingMap[slot];
  320. if (binding >= 0 && _usedConstantBufferBindings.Contains(binding))
  321. {
  322. descriptors[descriptorIndex++] = new BufferDescriptor(binding, slot);
  323. }
  324. }
  325. if (descriptors.Length != descriptorIndex)
  326. {
  327. Array.Resize(ref descriptors, descriptorIndex);
  328. }
  329. return descriptors;
  330. }
  331. public BufferDescriptor[] GetStorageBufferDescriptors()
  332. {
  333. var descriptors = new BufferDescriptor[_sbSlots.Count];
  334. int descriptorIndex = 0;
  335. foreach ((int key, int slot) in _sbSlots)
  336. {
  337. int binding = _sbSlotToBindingMap[slot];
  338. if (binding >= 0)
  339. {
  340. (int sbCbSlot, int sbCbOffset) = UnpackSbCbInfo(key);
  341. BufferUsageFlags flags = (_sbSlotWritten & (1u << slot)) != 0 ? BufferUsageFlags.Write : BufferUsageFlags.None;
  342. descriptors[descriptorIndex++] = new BufferDescriptor(binding, slot, sbCbSlot, sbCbOffset, flags);
  343. }
  344. }
  345. if (descriptors.Length != descriptorIndex)
  346. {
  347. Array.Resize(ref descriptors, descriptorIndex);
  348. }
  349. return descriptors;
  350. }
  351. public TextureDescriptor[] GetTextureDescriptors()
  352. {
  353. return GetDescriptors(_usedTextures, _usedTextures.Count);
  354. }
  355. public TextureDescriptor[] GetImageDescriptors()
  356. {
  357. return GetDescriptors(_usedImages, _usedImages.Count);
  358. }
  359. private static TextureDescriptor[] GetDescriptors(IReadOnlyDictionary<TextureInfo, TextureMeta> usedResources, int count)
  360. {
  361. TextureDescriptor[] descriptors = new TextureDescriptor[count];
  362. int descriptorIndex = 0;
  363. foreach ((TextureInfo info, TextureMeta meta) in usedResources)
  364. {
  365. descriptors[descriptorIndex++] = new TextureDescriptor(
  366. meta.Binding,
  367. meta.Type,
  368. info.Format,
  369. info.CbufSlot,
  370. info.Handle,
  371. meta.UsageFlags);
  372. }
  373. return descriptors;
  374. }
  375. public (int, int) GetCbufSlotAndHandleForTexture(int binding)
  376. {
  377. foreach ((TextureInfo info, TextureMeta meta) in _usedTextures)
  378. {
  379. if (meta.Binding == binding)
  380. {
  381. return (info.CbufSlot, info.Handle);
  382. }
  383. }
  384. throw new ArgumentException($"Binding {binding} is invalid.");
  385. }
  386. private static int FindDescriptorIndex(TextureDescriptor[] array, int binding)
  387. {
  388. return Array.FindIndex(array, x => x.Binding == binding);
  389. }
  390. public int FindTextureDescriptorIndex(int binding)
  391. {
  392. return FindDescriptorIndex(GetTextureDescriptors(), binding);
  393. }
  394. public int FindImageDescriptorIndex(int binding)
  395. {
  396. return FindDescriptorIndex(GetImageDescriptors(), binding);
  397. }
  398. private void AddNewConstantBuffer(int binding, string name)
  399. {
  400. StructureType type = new(new[]
  401. {
  402. new StructureField(AggregateType.Array | AggregateType.Vector4 | AggregateType.FP32, "data", Constants.ConstantBufferSize / 16),
  403. });
  404. Properties.AddOrUpdateConstantBuffer(binding, new BufferDefinition(BufferLayout.Std140, 0, binding, name, type));
  405. }
  406. private void AddNewStorageBuffer(int binding, string name)
  407. {
  408. StructureType type = new(new[]
  409. {
  410. new StructureField(AggregateType.Array | AggregateType.U32, "data", 0),
  411. });
  412. Properties.AddOrUpdateStorageBuffer(binding, new BufferDefinition(BufferLayout.Std430, 1, binding, name, type));
  413. }
  414. public static string GetShaderStagePrefix(ShaderStage stage)
  415. {
  416. uint index = (uint)stage;
  417. return index >= _stagePrefixes.Length ? "invalid" : _stagePrefixes[index];
  418. }
  419. private static int PackSbCbInfo(int sbCbSlot, int sbCbOffset)
  420. {
  421. return sbCbOffset | (sbCbSlot << 16);
  422. }
  423. private static (int, int) UnpackSbCbInfo(int key)
  424. {
  425. return ((byte)(key >> 16), (ushort)key);
  426. }
  427. }
  428. }