ShaderCache.cs 21 KB

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