ShaderConfig.cs 19 KB

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