ShaderCache.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. List<IShader> hostShaders = new List<IShader>();
  122. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  123. {
  124. ShaderProgram program = gpShaders.Shaders[stage]?.Program;
  125. if (program == null)
  126. {
  127. continue;
  128. }
  129. IShader hostShader = _context.Renderer.CompileShader(program);
  130. gpShaders.Shaders[stage].HostShader = hostShader;
  131. hostShaders.Add(hostShader);
  132. }
  133. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  134. if (!isCached)
  135. {
  136. list = new List<GraphicsShader>();
  137. _gpPrograms.Add(addresses, list);
  138. }
  139. list.Add(gpShaders);
  140. return gpShaders;
  141. }
  142. /// <summary>
  143. /// Checks if compute shader code in memory is different from the cached shader.
  144. /// </summary>
  145. /// <param name="cpShader">Cached compute shader</param>
  146. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  147. /// <returns>True if the code is different, false otherwise</returns>
  148. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  149. {
  150. return IsShaderDifferent(cpShader.Shader, gpuVa);
  151. }
  152. /// <summary>
  153. /// Checks if graphics shader code from all stages in memory is different from the cached shaders.
  154. /// </summary>
  155. /// <param name="gpShaders">Cached graphics shaders</param>
  156. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  157. /// <returns>True if the code is different, false otherwise</returns>
  158. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  159. {
  160. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  161. {
  162. CachedShader shader = gpShaders.Shaders[stage];
  163. ulong gpuVa = 0;
  164. switch (stage)
  165. {
  166. case 0: gpuVa = addresses.Vertex; break;
  167. case 1: gpuVa = addresses.TessControl; break;
  168. case 2: gpuVa = addresses.TessEvaluation; break;
  169. case 3: gpuVa = addresses.Geometry; break;
  170. case 4: gpuVa = addresses.Fragment; break;
  171. }
  172. if (IsShaderDifferent(shader, gpuVa))
  173. {
  174. return true;
  175. }
  176. }
  177. return false;
  178. }
  179. /// <summary>
  180. /// Checks if the code of the specified cached shader is different from the code in memory.
  181. /// </summary>
  182. /// <param name="shader">Cached shader to compare with</param>
  183. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  184. /// <returns>True if the code is different, false otherwise</returns>
  185. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  186. {
  187. if (shader == null)
  188. {
  189. return false;
  190. }
  191. ReadOnlySpan<byte> memoryCode = _context.MemoryAccessor.GetSpan(gpuVa, (ulong)shader.Code.Length * 4);
  192. return !MemoryMarshal.Cast<byte, int>(memoryCode).SequenceEqual(shader.Code);
  193. }
  194. /// <summary>
  195. /// Translates the binary Maxwell shader code to something that the host API accepts.
  196. /// </summary>
  197. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  198. /// <param name="localSizeX">Local group size X of the computer shader</param>
  199. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  200. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  201. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  202. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  203. /// <returns>Compiled compute shader code</returns>
  204. private CachedShader TranslateComputeShader(
  205. ulong gpuVa,
  206. int localSizeX,
  207. int localSizeY,
  208. int localSizeZ,
  209. int localMemorySize,
  210. int sharedMemorySize)
  211. {
  212. if (gpuVa == 0)
  213. {
  214. return null;
  215. }
  216. int QueryInfo(QueryInfoName info, int index)
  217. {
  218. return info switch
  219. {
  220. QueryInfoName.ComputeLocalSizeX => localSizeX,
  221. QueryInfoName.ComputeLocalSizeY => localSizeY,
  222. QueryInfoName.ComputeLocalSizeZ => localSizeZ,
  223. QueryInfoName.ComputeLocalMemorySize => localMemorySize,
  224. QueryInfoName.ComputeSharedMemorySize => sharedMemorySize,
  225. _ => QueryInfoCommon(info)
  226. };
  227. }
  228. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  229. ShaderProgram program;
  230. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  231. program = Translator.Translate(code, callbacks, DefaultFlags | TranslationFlags.Compute);
  232. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  233. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  234. if (fullPath != null && codePath != null)
  235. {
  236. program.Prepend("// " + codePath);
  237. program.Prepend("// " + fullPath);
  238. }
  239. return new CachedShader(program, codeCached);
  240. }
  241. /// <summary>
  242. /// Translates the binary Maxwell shader code to something that the host API accepts.
  243. /// </summary>
  244. /// <remarks>
  245. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  246. /// </remarks>
  247. /// <param name="state">Current GPU state</param>
  248. /// <param name="stage">Shader stage</param>
  249. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  250. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  251. /// <returns>Compiled graphics shader code</returns>
  252. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  253. {
  254. if (gpuVa == 0)
  255. {
  256. return null;
  257. }
  258. int QueryInfo(QueryInfoName info, int index)
  259. {
  260. return info switch
  261. {
  262. QueryInfoName.IsTextureBuffer => Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index)),
  263. QueryInfoName.IsTextureRectangle => Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index)),
  264. QueryInfoName.PrimitiveTopology => (int)GetPrimitiveTopology(),
  265. _ => QueryInfoCommon(info)
  266. };
  267. }
  268. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  269. ShaderProgram program;
  270. int[] codeCached = null;
  271. if (gpuVaA != 0)
  272. {
  273. ReadOnlySpan<byte> codeA = _context.MemoryAccessor.GetSpan(gpuVaA, MaxProgramSize);
  274. ReadOnlySpan<byte> codeB = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  275. program = Translator.Translate(codeA, codeB, callbacks, DefaultFlags);
  276. // TODO: We should also take "codeA" into account.
  277. codeCached = MemoryMarshal.Cast<byte, int>(codeB.Slice(0, program.Size)).ToArray();
  278. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  279. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  280. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  281. {
  282. program.Prepend("// " + codePathB);
  283. program.Prepend("// " + fullPathB);
  284. program.Prepend("// " + codePathA);
  285. program.Prepend("// " + fullPathA);
  286. }
  287. }
  288. else
  289. {
  290. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  291. program = Translator.Translate(code, callbacks, DefaultFlags);
  292. codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  293. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  294. if (fullPath != null && codePath != null)
  295. {
  296. program.Prepend("// " + codePath);
  297. program.Prepend("// " + fullPath);
  298. }
  299. }
  300. ulong address = _context.MemoryManager.Translate(gpuVa);
  301. return new CachedShader(program, codeCached);
  302. }
  303. /// <summary>
  304. /// Gets the primitive topology for the current draw.
  305. /// This is required by geometry shaders.
  306. /// </summary>
  307. /// <returns>Primitive topology</returns>
  308. private InputTopology GetPrimitiveTopology()
  309. {
  310. switch (_context.Methods.PrimitiveType)
  311. {
  312. case PrimitiveType.Points:
  313. return InputTopology.Points;
  314. case PrimitiveType.Lines:
  315. case PrimitiveType.LineLoop:
  316. case PrimitiveType.LineStrip:
  317. return InputTopology.Lines;
  318. case PrimitiveType.LinesAdjacency:
  319. case PrimitiveType.LineStripAdjacency:
  320. return InputTopology.LinesAdjacency;
  321. case PrimitiveType.Triangles:
  322. case PrimitiveType.TriangleStrip:
  323. case PrimitiveType.TriangleFan:
  324. return InputTopology.Triangles;
  325. case PrimitiveType.TrianglesAdjacency:
  326. case PrimitiveType.TriangleStripAdjacency:
  327. return InputTopology.TrianglesAdjacency;
  328. }
  329. return InputTopology.Points;
  330. }
  331. /// <summary>
  332. /// Check if the target of a given texture is texture buffer.
  333. /// This is required as 1D textures and buffer textures shares the same sampler type on binary shader code,
  334. /// but not on GLSL.
  335. /// </summary>
  336. /// <param name="state">Current GPU state</param>
  337. /// <param name="stageIndex">Index of the shader stage</param>
  338. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  339. /// <returns>True if the texture is a buffer texture, false otherwise</returns>
  340. private bool QueryIsTextureBuffer(GpuState state, int stageIndex, int index)
  341. {
  342. return GetTextureDescriptor(state, stageIndex, index).UnpackTextureTarget() == TextureTarget.TextureBuffer;
  343. }
  344. /// <summary>
  345. /// Check if the target of a given texture is texture rectangle.
  346. /// This is required as 2D textures and rectangle textures shares the same sampler type on binary shader code,
  347. /// but not on GLSL.
  348. /// </summary>
  349. /// <param name="state">Current GPU state</param>
  350. /// <param name="stageIndex">Index of the shader stage</param>
  351. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  352. /// <returns>True if the texture is a rectangle texture, false otherwise</returns>
  353. private bool QueryIsTextureRectangle(GpuState state, int stageIndex, int index)
  354. {
  355. var descriptor = GetTextureDescriptor(state, stageIndex, index);
  356. TextureTarget target = descriptor.UnpackTextureTarget();
  357. bool is2DTexture = target == TextureTarget.Texture2D ||
  358. target == TextureTarget.Texture2DRect;
  359. return !descriptor.UnpackTextureCoordNormalized() && is2DTexture;
  360. }
  361. /// <summary>
  362. /// Gets the texture descriptor for a given texture on the pool.
  363. /// </summary>
  364. /// <param name="state">Current GPU state</param>
  365. /// <param name="stageIndex">Index of the shader stage</param>
  366. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  367. /// <returns>Texture descriptor</returns>
  368. private TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int index)
  369. {
  370. return _context.Methods.TextureManager.GetGraphicsTextureDescriptor(state, stageIndex, index);
  371. }
  372. /// <summary>
  373. /// Returns information required by both compute and graphics shader compilation.
  374. /// </summary>
  375. /// <param name="info">Information queried</param>
  376. /// <returns>Requested information</returns>
  377. private int QueryInfoCommon(QueryInfoName info)
  378. {
  379. return info switch
  380. {
  381. QueryInfoName.StorageBufferOffsetAlignment => _context.Capabilities.StorageBufferOffsetAlignment,
  382. QueryInfoName.SupportsNonConstantTextureOffset => Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset),
  383. _ => 0
  384. };
  385. }
  386. /// <summary>
  387. /// Prints a warning from the shader code translator.
  388. /// </summary>
  389. /// <param name="message">Warning message</param>
  390. private static void PrintLog(string message)
  391. {
  392. Logger.PrintWarning(LogClass.Gpu, $"Shader translator: {message}");
  393. }
  394. /// <summary>
  395. /// Disposes the shader cache, deleting all the cached shaders.
  396. /// It's an error to use the shader cache after disposal.
  397. /// </summary>
  398. public void Dispose()
  399. {
  400. foreach (List<ComputeShader> list in _cpPrograms.Values)
  401. {
  402. foreach (ComputeShader shader in list)
  403. {
  404. shader.HostProgram.Dispose();
  405. shader.Shader?.HostShader.Dispose();
  406. }
  407. }
  408. foreach (List<GraphicsShader> list in _gpPrograms.Values)
  409. {
  410. foreach (GraphicsShader shader in list)
  411. {
  412. shader.HostProgram.Dispose();
  413. foreach (CachedShader cachedShader in shader.Shaders)
  414. {
  415. cachedShader?.HostShader.Dispose();
  416. }
  417. }
  418. }
  419. }
  420. }
  421. }