ShaderConfig.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. private bool FormatSupportsAtomic(TextureFormat format)
  129. {
  130. return format == TextureFormat.R32Sint || format == TextureFormat.R32Uint;
  131. }
  132. public TextureFormat GetTextureFormatAtomic(int handle, int cbufSlot = -1)
  133. {
  134. // Atomic image instructions do not support GL_EXT_shader_image_load_formatted,
  135. // and must have a type specified. Default to R32Sint if not available.
  136. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  137. if (!FormatSupportsAtomic(format))
  138. {
  139. GpuAccessor.Log($"Unsupported format for texture {handle}: {format}.");
  140. format = TextureFormat.R32Sint;
  141. }
  142. return format;
  143. }
  144. public void SizeAdd(int size)
  145. {
  146. Size += size;
  147. }
  148. public void InheritFrom(ShaderConfig other)
  149. {
  150. ClipDistancesWritten |= other.ClipDistancesWritten;
  151. UsedFeatures |= other.UsedFeatures;
  152. TextureHandlesForCache.UnionWith(other.TextureHandlesForCache);
  153. UsedInputAttributes |= other.UsedInputAttributes;
  154. UsedOutputAttributes |= other.UsedOutputAttributes;
  155. _usedConstantBuffers |= other._usedConstantBuffers;
  156. _usedStorageBuffers |= other._usedStorageBuffers;
  157. _usedStorageBuffersWrite |= other._usedStorageBuffersWrite;
  158. foreach (var kv in other._usedTextures)
  159. {
  160. if (!_usedTextures.TryAdd(kv.Key, kv.Value))
  161. {
  162. _usedTextures[kv.Key] = MergeTextureMeta(kv.Value, _usedTextures[kv.Key]);
  163. }
  164. }
  165. foreach (var kv in other._usedImages)
  166. {
  167. if (!_usedImages.TryAdd(kv.Key, kv.Value))
  168. {
  169. _usedImages[kv.Key] = MergeTextureMeta(kv.Value, _usedImages[kv.Key]);
  170. }
  171. }
  172. }
  173. public void SetInputUserAttribute(int index)
  174. {
  175. UsedInputAttributes |= 1 << index;
  176. }
  177. public void SetOutputUserAttribute(int index)
  178. {
  179. UsedOutputAttributes |= 1 << index;
  180. }
  181. public void MergeOutputUserAttributes(int mask)
  182. {
  183. if (GpPassthrough)
  184. {
  185. PassthroughAttributes = mask & ~UsedOutputAttributes;
  186. }
  187. else
  188. {
  189. UsedOutputAttributes |= mask;
  190. }
  191. }
  192. public void SetAllInputUserAttributes()
  193. {
  194. UsedInputAttributes |= Constants.AllAttributesMask;
  195. }
  196. public void SetAllOutputUserAttributes()
  197. {
  198. UsedOutputAttributes |= Constants.AllAttributesMask;
  199. }
  200. public void SetClipDistanceWritten(int index)
  201. {
  202. ClipDistancesWritten |= (byte)(1 << index);
  203. }
  204. public void SetUsedFeature(FeatureFlags flags)
  205. {
  206. UsedFeatures |= flags;
  207. }
  208. public Operand CreateCbuf(int slot, int offset)
  209. {
  210. SetUsedConstantBuffer(slot);
  211. return OperandHelper.Cbuf(slot, offset);
  212. }
  213. public void SetUsedConstantBuffer(int slot)
  214. {
  215. _usedConstantBuffers |= 1 << slot;
  216. }
  217. public void SetUsedStorageBuffer(int slot, bool write)
  218. {
  219. int mask = 1 << slot;
  220. _usedStorageBuffers |= mask;
  221. if (write)
  222. {
  223. _usedStorageBuffersWrite |= mask;
  224. }
  225. }
  226. public void SetUsedTexture(
  227. Instruction inst,
  228. SamplerType type,
  229. TextureFormat format,
  230. TextureFlags flags,
  231. int cbufSlot,
  232. int handle)
  233. {
  234. inst &= Instruction.Mask;
  235. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  236. bool isWrite = inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  237. bool accurateType = inst != Instruction.Lod;
  238. if (isImage)
  239. {
  240. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false);
  241. }
  242. else
  243. {
  244. bool intCoords = flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  245. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, intCoords, false, accurateType);
  246. }
  247. }
  248. private void SetUsedTextureOrImage(
  249. Dictionary<TextureInfo, TextureMeta> dict,
  250. int cbufSlot,
  251. int handle,
  252. SamplerType type,
  253. TextureFormat format,
  254. bool intCoords,
  255. bool write,
  256. bool accurateType)
  257. {
  258. var dimensions = type.GetDimensions();
  259. var isIndexed = type.HasFlag(SamplerType.Indexed);
  260. var usageFlags = TextureUsageFlags.None;
  261. if (intCoords)
  262. {
  263. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  264. var canScale = (Stage == ShaderStage.Fragment || Stage == ShaderStage.Compute) && !isIndexed && !write && dimensions == 2;
  265. if (!canScale)
  266. {
  267. // Resolution scaling cannot be applied to this texture right now.
  268. // Flag so that we know to blacklist scaling on related textures when binding them.
  269. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  270. }
  271. }
  272. if (write)
  273. {
  274. usageFlags |= TextureUsageFlags.ImageStore;
  275. }
  276. int arraySize = isIndexed ? SamplerArraySize : 1;
  277. for (int layer = 0; layer < arraySize; layer++)
  278. {
  279. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  280. var meta = new TextureMeta()
  281. {
  282. AccurateType = accurateType,
  283. Type = type,
  284. UsageFlags = usageFlags
  285. };
  286. if (dict.TryGetValue(info, out var existingMeta))
  287. {
  288. dict[info] = MergeTextureMeta(meta, existingMeta);
  289. }
  290. else
  291. {
  292. dict.Add(info, meta);
  293. }
  294. }
  295. }
  296. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  297. {
  298. meta.UsageFlags |= existingMeta.UsageFlags;
  299. // If the texture we have has inaccurate type information, then
  300. // we prefer the most accurate one.
  301. if (existingMeta.AccurateType)
  302. {
  303. meta.AccurateType = true;
  304. meta.Type = existingMeta.Type;
  305. }
  306. return meta;
  307. }
  308. public BufferDescriptor[] GetConstantBufferDescriptors()
  309. {
  310. if (_cachedConstantBufferDescriptors != null)
  311. {
  312. return _cachedConstantBufferDescriptors;
  313. }
  314. int usedMask = _usedConstantBuffers;
  315. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  316. {
  317. usedMask |= (int)GpuAccessor.QueryConstantBufferUse();
  318. }
  319. FirstConstantBufferBinding = _counts.UniformBuffersCount;
  320. return _cachedConstantBufferDescriptors = GetBufferDescriptors(
  321. usedMask,
  322. 0,
  323. UsedFeatures.HasFlag(FeatureFlags.CbIndexing),
  324. _counts.IncrementUniformBuffersCount);
  325. }
  326. public BufferDescriptor[] GetStorageBufferDescriptors()
  327. {
  328. if (_cachedStorageBufferDescriptors != null)
  329. {
  330. return _cachedStorageBufferDescriptors;
  331. }
  332. FirstStorageBufferBinding = _counts.StorageBuffersCount;
  333. return _cachedStorageBufferDescriptors = GetBufferDescriptors(
  334. _usedStorageBuffers,
  335. _usedStorageBuffersWrite,
  336. true,
  337. _counts.IncrementStorageBuffersCount);
  338. }
  339. private static BufferDescriptor[] GetBufferDescriptors(
  340. int usedMask,
  341. int writtenMask,
  342. bool isArray,
  343. Func<int> getBindingCallback)
  344. {
  345. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  346. int lastSlot = -1;
  347. for (int i = 0; i < descriptors.Length; i++)
  348. {
  349. int slot = BitOperations.TrailingZeroCount(usedMask);
  350. if (isArray)
  351. {
  352. // The next array entries also consumes bindings, even if they are unused.
  353. for (int j = lastSlot + 1; j < slot; j++)
  354. {
  355. getBindingCallback();
  356. }
  357. }
  358. lastSlot = slot;
  359. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  360. if ((writtenMask & (1 << slot)) != 0)
  361. {
  362. descriptors[i].SetFlag(BufferUsageFlags.Write);
  363. }
  364. usedMask &= ~(1 << slot);
  365. }
  366. return descriptors;
  367. }
  368. public TextureDescriptor[] GetTextureDescriptors()
  369. {
  370. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  371. }
  372. public TextureDescriptor[] GetImageDescriptors()
  373. {
  374. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  375. }
  376. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  377. {
  378. var descriptors = new TextureDescriptor[dict.Count];
  379. int i = 0;
  380. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  381. {
  382. var info = kv.Key;
  383. var meta = kv.Value;
  384. int binding = getBindingCallback();
  385. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  386. descriptors[i].SetFlag(meta.UsageFlags);
  387. i++;
  388. }
  389. return descriptors;
  390. }
  391. }
  392. }