ShaderConfig.cs 15 KB

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