ShaderCache.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Image;
  4. using Ryujinx.Graphics.Gpu.State;
  5. using Ryujinx.Graphics.Shader;
  6. using Ryujinx.Graphics.Shader.Translation;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Gpu.Shader
  11. {
  12. using TextureDescriptor = Image.TextureDescriptor;
  13. /// <summary>
  14. /// Memory cache of shader code.
  15. /// </summary>
  16. class ShaderCache : IDisposable
  17. {
  18. private const int MaxProgramSize = 0x100000;
  19. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  20. private GpuContext _context;
  21. private ShaderDumper _dumper;
  22. private Dictionary<ulong, List<ComputeShader>> _cpPrograms;
  23. private Dictionary<ShaderAddresses, List<GraphicsShader>> _gpPrograms;
  24. /// <summary>
  25. /// Creates a new instance of the shader cache.
  26. /// </summary>
  27. /// <param name="context">GPU context that the shader cache belongs to</param>
  28. public ShaderCache(GpuContext context)
  29. {
  30. _context = context;
  31. _dumper = new ShaderDumper();
  32. _cpPrograms = new Dictionary<ulong, List<ComputeShader>>();
  33. _gpPrograms = new Dictionary<ShaderAddresses, List<GraphicsShader>>();
  34. }
  35. /// <summary>
  36. /// Gets a compute shader from the cache.
  37. /// </summary>
  38. /// <remarks>
  39. /// This automatically translates, compiles and adds the code to the cache if not present.
  40. /// </remarks>
  41. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  42. /// <param name="localSizeX">Local group size X of the computer shader</param>
  43. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  44. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  45. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  46. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  47. /// <returns>Compiled compute shader code</returns>
  48. public ComputeShader GetComputeShader(
  49. ulong gpuVa,
  50. int localSizeX,
  51. int localSizeY,
  52. int localSizeZ,
  53. int localMemorySize,
  54. int sharedMemorySize)
  55. {
  56. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ComputeShader> list);
  57. if (isCached)
  58. {
  59. foreach (ComputeShader cachedCpShader in list)
  60. {
  61. if (!IsShaderDifferent(cachedCpShader, gpuVa))
  62. {
  63. return cachedCpShader;
  64. }
  65. }
  66. }
  67. CachedShader shader = TranslateComputeShader(
  68. gpuVa,
  69. localSizeX,
  70. localSizeY,
  71. localSizeZ,
  72. localMemorySize,
  73. sharedMemorySize);
  74. shader.HostShader = _context.Renderer.CompileShader(shader.Program);
  75. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader });
  76. ComputeShader cpShader = new ComputeShader(hostProgram, shader);
  77. if (!isCached)
  78. {
  79. list = new List<ComputeShader>();
  80. _cpPrograms.Add(gpuVa, list);
  81. }
  82. list.Add(cpShader);
  83. return cpShader;
  84. }
  85. /// <summary>
  86. /// Gets a graphics shader program from the shader cache.
  87. /// This includes all the specified shader stages.
  88. /// </summary>
  89. /// <remarks>
  90. /// This automatically translates, compiles and adds the code to the cache if not present.
  91. /// </remarks>
  92. /// <param name="state">Current GPU state</param>
  93. /// <param name="addresses">Addresses of the shaders for each stage</param>
  94. /// <returns>Compiled graphics shader code</returns>
  95. public GraphicsShader GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  96. {
  97. bool isCached = _gpPrograms.TryGetValue(addresses, out List<GraphicsShader> list);
  98. if (isCached)
  99. {
  100. foreach (GraphicsShader cachedGpShaders in list)
  101. {
  102. if (!IsShaderDifferent(cachedGpShaders, addresses))
  103. {
  104. return cachedGpShaders;
  105. }
  106. }
  107. }
  108. GraphicsShader gpShaders = new GraphicsShader();
  109. if (addresses.VertexA != 0)
  110. {
  111. gpShaders.Shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  112. }
  113. else
  114. {
  115. gpShaders.Shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  116. }
  117. gpShaders.Shaders[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  118. gpShaders.Shaders[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  119. gpShaders.Shaders[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  120. gpShaders.Shaders[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  121. BackpropQualifiers(gpShaders);
  122. List<IShader> hostShaders = new List<IShader>();
  123. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  124. {
  125. ShaderProgram program = gpShaders.Shaders[stage]?.Program;
  126. if (program == null)
  127. {
  128. continue;
  129. }
  130. IShader hostShader = _context.Renderer.CompileShader(program);
  131. gpShaders.Shaders[stage].HostShader = hostShader;
  132. hostShaders.Add(hostShader);
  133. }
  134. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  135. if (!isCached)
  136. {
  137. list = new List<GraphicsShader>();
  138. _gpPrograms.Add(addresses, list);
  139. }
  140. list.Add(gpShaders);
  141. return gpShaders;
  142. }
  143. /// <summary>
  144. /// Checks if compute shader code in memory is different from the cached shader.
  145. /// </summary>
  146. /// <param name="cpShader">Cached compute shader</param>
  147. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  148. /// <returns>True if the code is different, false otherwise</returns>
  149. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  150. {
  151. return IsShaderDifferent(cpShader.Shader, gpuVa);
  152. }
  153. /// <summary>
  154. /// Checks if graphics shader code from all stages in memory is different from the cached shaders.
  155. /// </summary>
  156. /// <param name="gpShaders">Cached graphics shaders</param>
  157. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  158. /// <returns>True if the code is different, false otherwise</returns>
  159. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  160. {
  161. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  162. {
  163. CachedShader shader = gpShaders.Shaders[stage];
  164. ulong gpuVa = 0;
  165. switch (stage)
  166. {
  167. case 0: gpuVa = addresses.Vertex; break;
  168. case 1: gpuVa = addresses.TessControl; break;
  169. case 2: gpuVa = addresses.TessEvaluation; break;
  170. case 3: gpuVa = addresses.Geometry; break;
  171. case 4: gpuVa = addresses.Fragment; break;
  172. }
  173. if (IsShaderDifferent(shader, gpuVa))
  174. {
  175. return true;
  176. }
  177. }
  178. return false;
  179. }
  180. /// <summary>
  181. /// Checks if the code of the specified cached shader is different from the code in memory.
  182. /// </summary>
  183. /// <param name="shader">Cached shader to compare with</param>
  184. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  185. /// <returns>True if the code is different, false otherwise</returns>
  186. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  187. {
  188. if (shader == null)
  189. {
  190. return false;
  191. }
  192. ReadOnlySpan<byte> memoryCode = _context.MemoryAccessor.GetSpan(gpuVa, (ulong)shader.Code.Length * 4);
  193. return !MemoryMarshal.Cast<byte, int>(memoryCode).SequenceEqual(shader.Code);
  194. }
  195. /// <summary>
  196. /// Translates the binary Maxwell shader code to something that the host API accepts.
  197. /// </summary>
  198. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  199. /// <param name="localSizeX">Local group size X of the computer shader</param>
  200. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  201. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  202. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  203. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  204. /// <returns>Compiled compute shader code</returns>
  205. private CachedShader TranslateComputeShader(
  206. ulong gpuVa,
  207. int localSizeX,
  208. int localSizeY,
  209. int localSizeZ,
  210. int localMemorySize,
  211. int sharedMemorySize)
  212. {
  213. if (gpuVa == 0)
  214. {
  215. return null;
  216. }
  217. int QueryInfo(QueryInfoName info, int index)
  218. {
  219. return info switch
  220. {
  221. QueryInfoName.ComputeLocalSizeX => localSizeX,
  222. QueryInfoName.ComputeLocalSizeY => localSizeY,
  223. QueryInfoName.ComputeLocalSizeZ => localSizeZ,
  224. QueryInfoName.ComputeLocalMemorySize => localMemorySize,
  225. QueryInfoName.ComputeSharedMemorySize => sharedMemorySize,
  226. _ => QueryInfoCommon(info)
  227. };
  228. }
  229. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  230. ShaderProgram program;
  231. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  232. program = Translator.Translate(code, callbacks, DefaultFlags | TranslationFlags.Compute);
  233. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  234. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  235. if (fullPath != null && codePath != null)
  236. {
  237. program.Prepend("// " + codePath);
  238. program.Prepend("// " + fullPath);
  239. }
  240. return new CachedShader(program, codeCached);
  241. }
  242. /// <summary>
  243. /// Translates the binary Maxwell shader code to something that the host API accepts.
  244. /// </summary>
  245. /// <remarks>
  246. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  247. /// </remarks>
  248. /// <param name="state">Current GPU state</param>
  249. /// <param name="stage">Shader stage</param>
  250. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  251. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  252. /// <returns>Compiled graphics shader code</returns>
  253. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  254. {
  255. if (gpuVa == 0)
  256. {
  257. return null;
  258. }
  259. int QueryInfo(QueryInfoName info, int index)
  260. {
  261. return info switch
  262. {
  263. QueryInfoName.IsTextureBuffer => Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index)),
  264. QueryInfoName.IsTextureRectangle => Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index)),
  265. QueryInfoName.PrimitiveTopology => (int)GetPrimitiveTopology(),
  266. _ => QueryInfoCommon(info)
  267. };
  268. }
  269. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  270. ShaderProgram program;
  271. int[] codeCached = null;
  272. if (gpuVaA != 0)
  273. {
  274. ReadOnlySpan<byte> codeA = _context.MemoryAccessor.GetSpan(gpuVaA, MaxProgramSize);
  275. ReadOnlySpan<byte> codeB = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  276. program = Translator.Translate(codeA, codeB, callbacks, DefaultFlags);
  277. // TODO: We should also take "codeA" into account.
  278. codeCached = MemoryMarshal.Cast<byte, int>(codeB.Slice(0, program.Size)).ToArray();
  279. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  280. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  281. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  282. {
  283. program.Prepend("// " + codePathB);
  284. program.Prepend("// " + fullPathB);
  285. program.Prepend("// " + codePathA);
  286. program.Prepend("// " + fullPathA);
  287. }
  288. }
  289. else
  290. {
  291. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  292. program = Translator.Translate(code, callbacks, DefaultFlags);
  293. codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  294. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  295. if (fullPath != null && codePath != null)
  296. {
  297. program.Prepend("// " + codePath);
  298. program.Prepend("// " + fullPath);
  299. }
  300. }
  301. ulong address = _context.MemoryManager.Translate(gpuVa);
  302. return new CachedShader(program, codeCached);
  303. }
  304. /// <summary>
  305. /// Performs backwards propagation of interpolation qualifiers or later shader stages input,
  306. /// to ealier shader stages output.
  307. /// This is required by older versions of OpenGL (pre-4.3).
  308. /// </summary>
  309. /// <param name="program">Graphics shader cached code</param>
  310. private void BackpropQualifiers(GraphicsShader program)
  311. {
  312. ShaderProgram fragmentShader = program.Shaders[4]?.Program;
  313. bool isFirst = true;
  314. for (int stage = 3; stage >= 0; stage--)
  315. {
  316. if (program.Shaders[stage] == null)
  317. {
  318. continue;
  319. }
  320. // We need to iterate backwards, since we do name replacement,
  321. // and it would otherwise replace a subset of the longer names.
  322. for (int attr = 31; attr >= 0; attr--)
  323. {
  324. string iq = fragmentShader?.Info.InterpolationQualifiers[attr].ToGlslQualifier() ?? string.Empty;
  325. if (isFirst && !string.IsNullOrEmpty(iq))
  326. {
  327. program.Shaders[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
  328. }
  329. else
  330. {
  331. program.Shaders[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr} ", string.Empty);
  332. }
  333. }
  334. isFirst = false;
  335. }
  336. }
  337. /// <summary>
  338. /// Gets the primitive topology for the current draw.
  339. /// This is required by geometry shaders.
  340. /// </summary>
  341. /// <returns>Primitive topology</returns>
  342. private InputTopology GetPrimitiveTopology()
  343. {
  344. switch (_context.Methods.PrimitiveType)
  345. {
  346. case PrimitiveType.Points:
  347. return InputTopology.Points;
  348. case PrimitiveType.Lines:
  349. case PrimitiveType.LineLoop:
  350. case PrimitiveType.LineStrip:
  351. return InputTopology.Lines;
  352. case PrimitiveType.LinesAdjacency:
  353. case PrimitiveType.LineStripAdjacency:
  354. return InputTopology.LinesAdjacency;
  355. case PrimitiveType.Triangles:
  356. case PrimitiveType.TriangleStrip:
  357. case PrimitiveType.TriangleFan:
  358. return InputTopology.Triangles;
  359. case PrimitiveType.TrianglesAdjacency:
  360. case PrimitiveType.TriangleStripAdjacency:
  361. return InputTopology.TrianglesAdjacency;
  362. }
  363. return InputTopology.Points;
  364. }
  365. /// <summary>
  366. /// Check if the target of a given texture is texture buffer.
  367. /// This is required as 1D textures and buffer textures shares the same sampler type on binary shader code,
  368. /// but not on GLSL.
  369. /// </summary>
  370. /// <param name="state">Current GPU state</param>
  371. /// <param name="stageIndex">Index of the shader stage</param>
  372. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  373. /// <returns>True if the texture is a buffer texture, false otherwise</returns>
  374. private bool QueryIsTextureBuffer(GpuState state, int stageIndex, int index)
  375. {
  376. return GetTextureDescriptor(state, stageIndex, index).UnpackTextureTarget() == TextureTarget.TextureBuffer;
  377. }
  378. /// <summary>
  379. /// Check if the target of a given texture is texture rectangle.
  380. /// This is required as 2D textures and rectangle textures shares the same sampler type on binary shader code,
  381. /// but not on GLSL.
  382. /// </summary>
  383. /// <param name="state">Current GPU state</param>
  384. /// <param name="stageIndex">Index of the shader stage</param>
  385. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  386. /// <returns>True if the texture is a rectangle texture, false otherwise</returns>
  387. private bool QueryIsTextureRectangle(GpuState state, int stageIndex, int index)
  388. {
  389. var descriptor = GetTextureDescriptor(state, stageIndex, index);
  390. TextureTarget target = descriptor.UnpackTextureTarget();
  391. bool is2DTexture = target == TextureTarget.Texture2D ||
  392. target == TextureTarget.Texture2DRect;
  393. return !descriptor.UnpackTextureCoordNormalized() && is2DTexture;
  394. }
  395. /// <summary>
  396. /// Gets the texture descriptor for a given texture on the pool.
  397. /// </summary>
  398. /// <param name="state">Current GPU state</param>
  399. /// <param name="stageIndex">Index of the shader stage</param>
  400. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  401. /// <returns>Texture descriptor</returns>
  402. private TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int index)
  403. {
  404. return _context.Methods.TextureManager.GetGraphicsTextureDescriptor(state, stageIndex, index);
  405. }
  406. /// <summary>
  407. /// Returns information required by both compute and graphics shader compilation.
  408. /// </summary>
  409. /// <param name="info">Information queried</param>
  410. /// <returns>Requested information</returns>
  411. private int QueryInfoCommon(QueryInfoName info)
  412. {
  413. return info switch
  414. {
  415. QueryInfoName.StorageBufferOffsetAlignment => _context.Capabilities.StorageBufferOffsetAlignment,
  416. QueryInfoName.SupportsNonConstantTextureOffset => Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset),
  417. _ => 0
  418. };
  419. }
  420. /// <summary>
  421. /// Prints a warning from the shader code translator.
  422. /// </summary>
  423. /// <param name="message">Warning message</param>
  424. private static void PrintLog(string message)
  425. {
  426. Logger.PrintWarning(LogClass.Gpu, $"Shader translator: {message}");
  427. }
  428. /// <summary>
  429. /// Disposes the shader cache, deleting all the cached shaders.
  430. /// It's an error to use the shader cache after disposal.
  431. /// </summary>
  432. public void Dispose()
  433. {
  434. foreach (List<ComputeShader> list in _cpPrograms.Values)
  435. {
  436. foreach (ComputeShader shader in list)
  437. {
  438. shader.HostProgram.Dispose();
  439. shader.Shader?.HostShader.Dispose();
  440. }
  441. }
  442. foreach (List<GraphicsShader> list in _gpPrograms.Values)
  443. {
  444. foreach (GraphicsShader shader in list)
  445. {
  446. shader.HostProgram.Dispose();
  447. foreach (CachedShader cachedShader in shader.Shaders)
  448. {
  449. cachedShader?.HostShader.Dispose();
  450. }
  451. }
  452. }
  453. }
  454. }
  455. }