ShaderConfig.cs 19 KB

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