ShaderConfig.cs 19 KB

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