ShaderConfig.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Numerics;
  6. namespace Ryujinx.Graphics.Shader.Translation
  7. {
  8. class ShaderConfig
  9. {
  10. // TODO: Non-hardcoded array size.
  11. public const int SamplerArraySize = 4;
  12. public ShaderStage Stage { get; }
  13. public bool GpPassthrough { get; }
  14. public OutputTopology OutputTopology { get; }
  15. public int MaxOutputVertices { get; }
  16. public int LocalMemorySize { get; }
  17. public ImapPixelType[] ImapTypes { get; }
  18. public OmapTarget[] OmapTargets { get; }
  19. public bool OmapSampleMask { get; }
  20. public bool OmapDepth { get; }
  21. public IGpuAccessor GpuAccessor { get; }
  22. public TranslationOptions Options { get; }
  23. public int Size { get; private set; }
  24. public byte ClipDistancesWritten { get; private set; }
  25. public FeatureFlags UsedFeatures { get; private set; }
  26. public HashSet<int> TextureHandlesForCache { get; }
  27. private readonly TranslationCounts _counts;
  28. private int _usedConstantBuffers;
  29. private int _usedStorageBuffers;
  30. private int _usedStorageBuffersWrite;
  31. private struct TextureInfo : IEquatable<TextureInfo>
  32. {
  33. public int CbufSlot { get; }
  34. public int Handle { get; }
  35. public bool Indexed { get; }
  36. public TextureFormat Format { get; }
  37. public TextureInfo(int cbufSlot, int handle, bool indexed, TextureFormat format)
  38. {
  39. CbufSlot = cbufSlot;
  40. Handle = handle;
  41. Indexed = indexed;
  42. Format = format;
  43. }
  44. public override bool Equals(object obj)
  45. {
  46. return obj is TextureInfo other && Equals(other);
  47. }
  48. public bool Equals(TextureInfo other)
  49. {
  50. return CbufSlot == other.CbufSlot && Handle == other.Handle && Indexed == other.Indexed && Format == other.Format;
  51. }
  52. public override int GetHashCode()
  53. {
  54. return HashCode.Combine(CbufSlot, Handle, Indexed, Format);
  55. }
  56. }
  57. private struct TextureMeta
  58. {
  59. public bool AccurateType;
  60. public SamplerType Type;
  61. public TextureUsageFlags UsageFlags;
  62. }
  63. private readonly Dictionary<TextureInfo, TextureMeta> _usedTextures;
  64. private readonly Dictionary<TextureInfo, TextureMeta> _usedImages;
  65. private BufferDescriptor[] _cachedConstantBufferDescriptors;
  66. private BufferDescriptor[] _cachedStorageBufferDescriptors;
  67. private TextureDescriptor[] _cachedTextureDescriptors;
  68. private TextureDescriptor[] _cachedImageDescriptors;
  69. public int FirstConstantBufferBinding { get; private set; }
  70. public int FirstStorageBufferBinding { get; private set; }
  71. public ShaderConfig(IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts)
  72. {
  73. Stage = ShaderStage.Compute;
  74. GpuAccessor = gpuAccessor;
  75. Options = options;
  76. _counts = counts;
  77. TextureHandlesForCache = new HashSet<int>();
  78. _usedTextures = new Dictionary<TextureInfo, TextureMeta>();
  79. _usedImages = new Dictionary<TextureInfo, TextureMeta>();
  80. }
  81. public ShaderConfig(ShaderHeader header, IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts) : this(gpuAccessor, options, counts)
  82. {
  83. Stage = header.Stage;
  84. GpPassthrough = header.Stage == ShaderStage.Geometry && header.GpPassthrough;
  85. OutputTopology = header.OutputTopology;
  86. MaxOutputVertices = header.MaxOutputVertexCount;
  87. LocalMemorySize = header.ShaderLocalMemoryLowSize + header.ShaderLocalMemoryHighSize;
  88. ImapTypes = header.ImapTypes;
  89. OmapTargets = header.OmapTargets;
  90. OmapSampleMask = header.OmapSampleMask;
  91. OmapDepth = header.OmapDepth;
  92. }
  93. public int GetDepthRegister()
  94. {
  95. int count = 0;
  96. for (int index = 0; index < OmapTargets.Length; index++)
  97. {
  98. for (int component = 0; component < 4; component++)
  99. {
  100. if (OmapTargets[index].ComponentEnabled(component))
  101. {
  102. count++;
  103. }
  104. }
  105. }
  106. // The depth register is always two registers after the last color output.
  107. return count + 1;
  108. }
  109. public TextureFormat GetTextureFormat(int handle, int cbufSlot = -1)
  110. {
  111. // When the formatted load extension is supported, we don't need to
  112. // specify a format, we can just declare it without a format and the GPU will handle it.
  113. if (GpuAccessor.QuerySupportsImageLoadFormatted())
  114. {
  115. return TextureFormat.Unknown;
  116. }
  117. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  118. if (format == TextureFormat.Unknown)
  119. {
  120. GpuAccessor.Log($"Unknown format for texture {handle}.");
  121. format = TextureFormat.R8G8B8A8Unorm;
  122. }
  123. return format;
  124. }
  125. public void SizeAdd(int size)
  126. {
  127. Size += size;
  128. }
  129. public void InheritFrom(ShaderConfig other)
  130. {
  131. ClipDistancesWritten |= other.ClipDistancesWritten;
  132. UsedFeatures |= other.UsedFeatures;
  133. TextureHandlesForCache.UnionWith(other.TextureHandlesForCache);
  134. _usedConstantBuffers |= other._usedConstantBuffers;
  135. _usedStorageBuffers |= other._usedStorageBuffers;
  136. _usedStorageBuffersWrite |= other._usedStorageBuffersWrite;
  137. foreach (var kv in other._usedTextures)
  138. {
  139. if (!_usedTextures.TryAdd(kv.Key, kv.Value))
  140. {
  141. _usedTextures[kv.Key] = MergeTextureMeta(kv.Value, _usedTextures[kv.Key]);
  142. }
  143. }
  144. foreach (var kv in other._usedImages)
  145. {
  146. if (!_usedImages.TryAdd(kv.Key, kv.Value))
  147. {
  148. _usedImages[kv.Key] = MergeTextureMeta(kv.Value, _usedImages[kv.Key]);
  149. }
  150. }
  151. }
  152. public void SetClipDistanceWritten(int index)
  153. {
  154. ClipDistancesWritten |= (byte)(1 << index);
  155. }
  156. public void SetUsedFeature(FeatureFlags flags)
  157. {
  158. UsedFeatures |= flags;
  159. }
  160. public Operand CreateCbuf(int slot, int offset)
  161. {
  162. SetUsedConstantBuffer(slot);
  163. return OperandHelper.Cbuf(slot, offset);
  164. }
  165. public void SetUsedConstantBuffer(int slot)
  166. {
  167. _usedConstantBuffers |= 1 << slot;
  168. }
  169. public void SetUsedStorageBuffer(int slot, bool write)
  170. {
  171. int mask = 1 << slot;
  172. _usedStorageBuffers |= mask;
  173. if (write)
  174. {
  175. _usedStorageBuffersWrite |= mask;
  176. }
  177. }
  178. public void SetUsedTexture(
  179. Instruction inst,
  180. SamplerType type,
  181. TextureFormat format,
  182. TextureFlags flags,
  183. int cbufSlot,
  184. int handle)
  185. {
  186. inst &= Instruction.Mask;
  187. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore;
  188. bool isWrite = inst == Instruction.ImageStore;
  189. bool accurateType = inst != Instruction.TextureSize && inst != Instruction.Lod;
  190. if (isImage)
  191. {
  192. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false);
  193. }
  194. else
  195. {
  196. bool intCoords = flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  197. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, intCoords, false, accurateType);
  198. }
  199. }
  200. private void SetUsedTextureOrImage(
  201. Dictionary<TextureInfo, TextureMeta> dict,
  202. int cbufSlot,
  203. int handle,
  204. SamplerType type,
  205. TextureFormat format,
  206. bool intCoords,
  207. bool write,
  208. bool accurateType)
  209. {
  210. var dimensions = type.GetDimensions();
  211. var isIndexed = type.HasFlag(SamplerType.Indexed);
  212. var usageFlags = TextureUsageFlags.None;
  213. if (intCoords)
  214. {
  215. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  216. var canScale = (Stage == ShaderStage.Fragment || Stage == ShaderStage.Compute) && !isIndexed && !write && dimensions == 2;
  217. if (!canScale)
  218. {
  219. // Resolution scaling cannot be applied to this texture right now.
  220. // Flag so that we know to blacklist scaling on related textures when binding them.
  221. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  222. }
  223. }
  224. if (write)
  225. {
  226. usageFlags |= TextureUsageFlags.ImageStore;
  227. }
  228. int arraySize = isIndexed ? SamplerArraySize : 1;
  229. for (int layer = 0; layer < arraySize; layer++)
  230. {
  231. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  232. var meta = new TextureMeta()
  233. {
  234. AccurateType = accurateType,
  235. Type = type,
  236. UsageFlags = usageFlags
  237. };
  238. if (dict.TryGetValue(info, out var existingMeta))
  239. {
  240. dict[info] = MergeTextureMeta(meta, existingMeta);
  241. }
  242. else
  243. {
  244. dict.Add(info, meta);
  245. }
  246. }
  247. }
  248. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  249. {
  250. meta.UsageFlags |= existingMeta.UsageFlags;
  251. // If the texture we have has inaccurate type information, then
  252. // we prefer the most accurate one.
  253. if (existingMeta.AccurateType)
  254. {
  255. meta.AccurateType = true;
  256. meta.Type = existingMeta.Type;
  257. }
  258. return meta;
  259. }
  260. public BufferDescriptor[] GetConstantBufferDescriptors()
  261. {
  262. if (_cachedConstantBufferDescriptors != null)
  263. {
  264. return _cachedConstantBufferDescriptors;
  265. }
  266. int usedMask = _usedConstantBuffers;
  267. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  268. {
  269. usedMask |= (int)GpuAccessor.QueryConstantBufferUse();
  270. }
  271. FirstConstantBufferBinding = _counts.UniformBuffersCount;
  272. return _cachedConstantBufferDescriptors = GetBufferDescriptors(
  273. usedMask,
  274. 0,
  275. UsedFeatures.HasFlag(FeatureFlags.CbIndexing),
  276. _counts.IncrementUniformBuffersCount);
  277. }
  278. public BufferDescriptor[] GetStorageBufferDescriptors()
  279. {
  280. if (_cachedStorageBufferDescriptors != null)
  281. {
  282. return _cachedStorageBufferDescriptors;
  283. }
  284. FirstStorageBufferBinding = _counts.StorageBuffersCount;
  285. return _cachedStorageBufferDescriptors = GetBufferDescriptors(
  286. _usedStorageBuffers,
  287. _usedStorageBuffersWrite,
  288. true,
  289. _counts.IncrementStorageBuffersCount);
  290. }
  291. private static BufferDescriptor[] GetBufferDescriptors(
  292. int usedMask,
  293. int writtenMask,
  294. bool isArray,
  295. Func<int> getBindingCallback)
  296. {
  297. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  298. int lastSlot = -1;
  299. for (int i = 0; i < descriptors.Length; i++)
  300. {
  301. int slot = BitOperations.TrailingZeroCount(usedMask);
  302. if (isArray)
  303. {
  304. // The next array entries also consumes bindings, even if they are unused.
  305. for (int j = lastSlot + 1; j < slot; j++)
  306. {
  307. getBindingCallback();
  308. }
  309. }
  310. lastSlot = slot;
  311. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  312. if ((writtenMask & (1 << slot)) != 0)
  313. {
  314. descriptors[i].SetFlag(BufferUsageFlags.Write);
  315. }
  316. usedMask &= ~(1 << slot);
  317. }
  318. return descriptors;
  319. }
  320. public TextureDescriptor[] GetTextureDescriptors()
  321. {
  322. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  323. }
  324. public TextureDescriptor[] GetImageDescriptors()
  325. {
  326. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  327. }
  328. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  329. {
  330. var descriptors = new TextureDescriptor[dict.Count];
  331. int i = 0;
  332. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  333. {
  334. var info = kv.Key;
  335. var meta = kv.Value;
  336. int binding = getBindingCallback();
  337. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  338. descriptors[i].SetFlag(meta.UsageFlags);
  339. i++;
  340. }
  341. return descriptors;
  342. }
  343. }
  344. }