ShaderConfig.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 TranslationFlags Flags { 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 ShaderConfig(IGpuAccessor gpuAccessor, TranslationFlags flags, TranslationCounts counts)
  70. {
  71. Stage = ShaderStage.Compute;
  72. GpuAccessor = gpuAccessor;
  73. Flags = flags;
  74. _counts = counts;
  75. TextureHandlesForCache = new HashSet<int>();
  76. _usedTextures = new Dictionary<TextureInfo, TextureMeta>();
  77. _usedImages = new Dictionary<TextureInfo, TextureMeta>();
  78. }
  79. public ShaderConfig(ShaderHeader header, IGpuAccessor gpuAccessor, TranslationFlags flags, TranslationCounts counts) : this(gpuAccessor, flags, counts)
  80. {
  81. Stage = header.Stage;
  82. GpPassthrough = header.Stage == ShaderStage.Geometry && header.GpPassthrough;
  83. OutputTopology = header.OutputTopology;
  84. MaxOutputVertices = header.MaxOutputVertexCount;
  85. LocalMemorySize = header.ShaderLocalMemoryLowSize + header.ShaderLocalMemoryHighSize;
  86. ImapTypes = header.ImapTypes;
  87. OmapTargets = header.OmapTargets;
  88. OmapSampleMask = header.OmapSampleMask;
  89. OmapDepth = header.OmapDepth;
  90. }
  91. public int GetDepthRegister()
  92. {
  93. int count = 0;
  94. for (int index = 0; index < OmapTargets.Length; index++)
  95. {
  96. for (int component = 0; component < 4; component++)
  97. {
  98. if (OmapTargets[index].ComponentEnabled(component))
  99. {
  100. count++;
  101. }
  102. }
  103. }
  104. // The depth register is always two registers after the last color output.
  105. return count + 1;
  106. }
  107. public TextureFormat GetTextureFormat(int handle, int cbufSlot = -1)
  108. {
  109. // When the formatted load extension is supported, we don't need to
  110. // specify a format, we can just declare it without a format and the GPU will handle it.
  111. if (GpuAccessor.QuerySupportsImageLoadFormatted())
  112. {
  113. return TextureFormat.Unknown;
  114. }
  115. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  116. if (format == TextureFormat.Unknown)
  117. {
  118. GpuAccessor.Log($"Unknown format for texture {handle}.");
  119. format = TextureFormat.R8G8B8A8Unorm;
  120. }
  121. return format;
  122. }
  123. public void SizeAdd(int size)
  124. {
  125. Size += size;
  126. }
  127. public void SetClipDistanceWritten(int index)
  128. {
  129. ClipDistancesWritten |= (byte)(1 << index);
  130. }
  131. public void SetUsedFeature(FeatureFlags flags)
  132. {
  133. UsedFeatures |= flags;
  134. }
  135. public Operand CreateCbuf(int slot, int offset)
  136. {
  137. SetUsedConstantBuffer(slot);
  138. return OperandHelper.Cbuf(slot, offset);
  139. }
  140. public void SetUsedConstantBuffer(int slot)
  141. {
  142. _usedConstantBuffers |= 1 << slot;
  143. }
  144. public void SetUsedStorageBuffer(int slot, bool write)
  145. {
  146. int mask = 1 << slot;
  147. _usedStorageBuffers |= mask;
  148. if (write)
  149. {
  150. _usedStorageBuffersWrite |= mask;
  151. }
  152. }
  153. public void SetUsedTexture(
  154. Instruction inst,
  155. SamplerType type,
  156. TextureFormat format,
  157. TextureFlags flags,
  158. int cbufSlot,
  159. int handle)
  160. {
  161. inst &= Instruction.Mask;
  162. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore;
  163. bool isWrite = inst == Instruction.ImageStore;
  164. bool accurateType = inst != Instruction.TextureSize && inst != Instruction.Lod;
  165. if (isImage)
  166. {
  167. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false);
  168. }
  169. else
  170. {
  171. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, flags.HasFlag(TextureFlags.IntCoords), false, accurateType);
  172. }
  173. }
  174. private static void SetUsedTextureOrImage(
  175. Dictionary<TextureInfo, TextureMeta> dict,
  176. int cbufSlot,
  177. int handle,
  178. SamplerType type,
  179. TextureFormat format,
  180. bool intCoords,
  181. bool write,
  182. bool accurateType)
  183. {
  184. var dimensions = type.GetDimensions();
  185. var isArray = type.HasFlag(SamplerType.Array);
  186. var isIndexed = type.HasFlag(SamplerType.Indexed);
  187. var usageFlags = TextureUsageFlags.None;
  188. if (intCoords)
  189. {
  190. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  191. var canScale = (dimensions == 2 && !isArray) || (dimensions == 3 && isArray);
  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. int arraySize = isIndexed ? SamplerArraySize : 1;
  204. for (int layer = 0; layer < arraySize; layer++)
  205. {
  206. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  207. var meta = new TextureMeta()
  208. {
  209. AccurateType = accurateType,
  210. Type = type,
  211. UsageFlags = usageFlags
  212. };
  213. if (dict.TryGetValue(info, out var existingMeta))
  214. {
  215. meta.UsageFlags |= existingMeta.UsageFlags;
  216. // If the texture we have has inaccurate type information, then
  217. // we prefer the most accurate one.
  218. if (existingMeta.AccurateType)
  219. {
  220. meta.AccurateType = true;
  221. meta.Type = existingMeta.Type;
  222. }
  223. dict[info] = meta;
  224. }
  225. else
  226. {
  227. dict.Add(info, meta);
  228. }
  229. }
  230. }
  231. public BufferDescriptor[] GetConstantBufferDescriptors()
  232. {
  233. if (_cachedConstantBufferDescriptors != null)
  234. {
  235. return _cachedConstantBufferDescriptors;
  236. }
  237. int usedMask = _usedConstantBuffers;
  238. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  239. {
  240. usedMask = FillMask(usedMask);
  241. }
  242. return _cachedConstantBufferDescriptors = GetBufferDescriptors(usedMask, 0, _counts.IncrementUniformBuffersCount);
  243. }
  244. public BufferDescriptor[] GetStorageBufferDescriptors()
  245. {
  246. return _cachedStorageBufferDescriptors ??= GetBufferDescriptors(FillMask(_usedStorageBuffers), _usedStorageBuffersWrite, _counts.IncrementStorageBuffersCount);
  247. }
  248. private static int FillMask(int mask)
  249. {
  250. // When the storage or uniform buffers are used as array, we must allocate a binding
  251. // even for the "gaps" that are not used on the shader.
  252. // For this reason, fill up the gaps so that all slots up to the highest one are
  253. // marked as "used".
  254. return mask != 0 ? (int)(uint.MaxValue >> BitOperations.LeadingZeroCount((uint)mask)) : 0;
  255. }
  256. private static BufferDescriptor[] GetBufferDescriptors(int usedMask, int writtenMask, Func<int> getBindingCallback)
  257. {
  258. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  259. for (int i = 0; i < descriptors.Length; i++)
  260. {
  261. int slot = BitOperations.TrailingZeroCount(usedMask);
  262. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  263. if ((writtenMask & (1 << slot)) != 0)
  264. {
  265. descriptors[i].SetFlag(BufferUsageFlags.Write);
  266. }
  267. usedMask &= ~(1 << slot);
  268. }
  269. return descriptors;
  270. }
  271. public TextureDescriptor[] GetTextureDescriptors()
  272. {
  273. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  274. }
  275. public TextureDescriptor[] GetImageDescriptors()
  276. {
  277. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  278. }
  279. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  280. {
  281. var descriptors = new TextureDescriptor[dict.Count];
  282. int i = 0;
  283. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  284. {
  285. var info = kv.Key;
  286. var meta = kv.Value;
  287. int binding = getBindingCallback();
  288. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  289. descriptors[i].SetFlag(meta.UsageFlags);
  290. i++;
  291. }
  292. return descriptors;
  293. }
  294. }
  295. }