ShaderCache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.State;
  3. using Ryujinx.Graphics.Shader;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. namespace Ryujinx.Graphics.Gpu.Shader
  8. {
  9. /// <summary>
  10. /// Memory cache of shader code.
  11. /// </summary>
  12. class ShaderCache : IDisposable
  13. {
  14. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  15. private readonly GpuContext _context;
  16. private readonly ShaderDumper _dumper;
  17. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  18. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  19. /// <summary>
  20. /// Creates a new instance of the shader cache.
  21. /// </summary>
  22. /// <param name="context">GPU context that the shader cache belongs to</param>
  23. public ShaderCache(GpuContext context)
  24. {
  25. _context = context;
  26. _dumper = new ShaderDumper();
  27. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  28. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  29. }
  30. /// <summary>
  31. /// Gets a compute shader from the cache.
  32. /// </summary>
  33. /// <remarks>
  34. /// This automatically translates, compiles and adds the code to the cache if not present.
  35. /// </remarks>
  36. /// <param name="state">Current GPU state</param>
  37. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  38. /// <param name="localSizeX">Local group size X of the computer shader</param>
  39. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  40. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  41. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  42. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  43. /// <returns>Compiled compute shader code</returns>
  44. public ShaderBundle GetComputeShader(
  45. GpuState state,
  46. ulong gpuVa,
  47. int localSizeX,
  48. int localSizeY,
  49. int localSizeZ,
  50. int localMemorySize,
  51. int sharedMemorySize)
  52. {
  53. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  54. if (isCached)
  55. {
  56. foreach (ShaderBundle cachedCpShader in list)
  57. {
  58. if (IsShaderEqual(cachedCpShader, gpuVa))
  59. {
  60. return cachedCpShader;
  61. }
  62. }
  63. }
  64. ShaderCodeHolder shader = TranslateComputeShader(
  65. state,
  66. gpuVa,
  67. localSizeX,
  68. localSizeY,
  69. localSizeZ,
  70. localMemorySize,
  71. sharedMemorySize);
  72. shader.HostShader = _context.Renderer.CompileShader(shader.Program);
  73. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  74. ShaderBundle cpShader = new ShaderBundle(hostProgram, shader);
  75. if (!isCached)
  76. {
  77. list = new List<ShaderBundle>();
  78. _cpPrograms.Add(gpuVa, list);
  79. }
  80. list.Add(cpShader);
  81. return cpShader;
  82. }
  83. /// <summary>
  84. /// Gets a graphics shader program from the shader cache.
  85. /// This includes all the specified shader stages.
  86. /// </summary>
  87. /// <remarks>
  88. /// This automatically translates, compiles and adds the code to the cache if not present.
  89. /// </remarks>
  90. /// <param name="state">Current GPU state</param>
  91. /// <param name="addresses">Addresses of the shaders for each stage</param>
  92. /// <returns>Compiled graphics shader code</returns>
  93. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  94. {
  95. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  96. if (isCached)
  97. {
  98. foreach (ShaderBundle cachedGpShaders in list)
  99. {
  100. if (IsShaderEqual(cachedGpShaders, addresses))
  101. {
  102. return cachedGpShaders;
  103. }
  104. }
  105. }
  106. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  107. var tfd = GetTransformFeedbackDescriptors(state);
  108. TranslationFlags flags = DefaultFlags;
  109. if (tfd != null)
  110. {
  111. flags |= TranslationFlags.Feedback;
  112. }
  113. if (addresses.VertexA != 0)
  114. {
  115. shaders[0] = TranslateGraphicsShader(state, flags, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  116. }
  117. else
  118. {
  119. shaders[0] = TranslateGraphicsShader(state, flags, ShaderStage.Vertex, addresses.Vertex);
  120. }
  121. shaders[1] = TranslateGraphicsShader(state, flags, ShaderStage.TessellationControl, addresses.TessControl);
  122. shaders[2] = TranslateGraphicsShader(state, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  123. shaders[3] = TranslateGraphicsShader(state, flags, ShaderStage.Geometry, addresses.Geometry);
  124. shaders[4] = TranslateGraphicsShader(state, flags, ShaderStage.Fragment, addresses.Fragment);
  125. List<IShader> hostShaders = new List<IShader>();
  126. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  127. {
  128. ShaderProgram program = shaders[stage]?.Program;
  129. if (program == null)
  130. {
  131. continue;
  132. }
  133. IShader hostShader = _context.Renderer.CompileShader(program);
  134. shaders[stage].HostShader = hostShader;
  135. hostShaders.Add(hostShader);
  136. }
  137. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  138. ShaderBundle gpShaders = new ShaderBundle(hostProgram, shaders);
  139. if (!isCached)
  140. {
  141. list = new List<ShaderBundle>();
  142. _gpPrograms.Add(addresses, list);
  143. }
  144. list.Add(gpShaders);
  145. return gpShaders;
  146. }
  147. /// <summary>
  148. /// Gets transform feedback state from the current GPU state.
  149. /// </summary>
  150. /// <param name="state">Current GPU state</param>
  151. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  152. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  153. {
  154. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  155. if (!tfEnable)
  156. {
  157. return null;
  158. }
  159. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  160. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  161. {
  162. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  163. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  164. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  165. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  166. }
  167. return descs;
  168. }
  169. /// <summary>
  170. /// Checks if compute shader code in memory is equal to the cached shader.
  171. /// </summary>
  172. /// <param name="cpShader">Cached compute shader</param>
  173. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  174. /// <returns>True if the code is different, false otherwise</returns>
  175. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  176. {
  177. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  178. }
  179. /// <summary>
  180. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  181. /// </summary>
  182. /// <param name="gpShaders">Cached graphics shaders</param>
  183. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  184. /// <returns>True if the code is different, false otherwise</returns>
  185. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  186. {
  187. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  188. {
  189. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  190. ulong gpuVa = 0;
  191. switch (stage)
  192. {
  193. case 0: gpuVa = addresses.Vertex; break;
  194. case 1: gpuVa = addresses.TessControl; break;
  195. case 2: gpuVa = addresses.TessEvaluation; break;
  196. case 3: gpuVa = addresses.Geometry; break;
  197. case 4: gpuVa = addresses.Fragment; break;
  198. }
  199. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  200. {
  201. return false;
  202. }
  203. }
  204. return true;
  205. }
  206. /// <summary>
  207. /// Checks if the code of the specified cached shader is different from the code in memory.
  208. /// </summary>
  209. /// <param name="shader">Cached shader to compare with</param>
  210. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  211. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  212. /// <returns>True if the code is different, false otherwise</returns>
  213. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  214. {
  215. if (shader == null)
  216. {
  217. return true;
  218. }
  219. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  220. bool equals = memoryCode.SequenceEqual(shader.Code);
  221. if (equals && shader.Code2 != null)
  222. {
  223. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  224. equals = memoryCode.SequenceEqual(shader.Code2);
  225. }
  226. return equals;
  227. }
  228. /// <summary>
  229. /// Translates the binary Maxwell shader code to something that the host API accepts.
  230. /// </summary>
  231. /// <param name="state">Current GPU state</param>
  232. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  233. /// <param name="localSizeX">Local group size X of the computer shader</param>
  234. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  235. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  236. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  237. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  238. /// <returns>Compiled compute shader code</returns>
  239. private ShaderCodeHolder TranslateComputeShader(
  240. GpuState state,
  241. ulong gpuVa,
  242. int localSizeX,
  243. int localSizeY,
  244. int localSizeZ,
  245. int localMemorySize,
  246. int sharedMemorySize)
  247. {
  248. if (gpuVa == 0)
  249. {
  250. return null;
  251. }
  252. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  253. ShaderProgram program;
  254. program = Translator.Translate(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  255. byte[] code = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  256. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  257. if (fullPath != null && codePath != null)
  258. {
  259. program.Prepend("// " + codePath);
  260. program.Prepend("// " + fullPath);
  261. }
  262. return new ShaderCodeHolder(program, code);
  263. }
  264. /// <summary>
  265. /// Translates the binary Maxwell shader code to something that the host API accepts.
  266. /// </summary>
  267. /// <remarks>
  268. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  269. /// </remarks>
  270. /// <param name="state">Current GPU state</param>
  271. /// <param name="flags">Flags that controls shader translation</param>
  272. /// <param name="stage">Shader stage</param>
  273. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  274. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  275. /// <returns>Compiled graphics shader code</returns>
  276. private ShaderCodeHolder TranslateGraphicsShader(GpuState state, TranslationFlags flags, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  277. {
  278. if (gpuVa == 0)
  279. {
  280. return null;
  281. }
  282. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  283. if (gpuVaA != 0)
  284. {
  285. ShaderProgram program = Translator.Translate(gpuVaA, gpuVa, gpuAccessor, flags);
  286. byte[] codeA = _context.MemoryManager.GetSpan(gpuVaA, program.SizeA).ToArray();
  287. byte[] codeB = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  288. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  289. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  290. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  291. {
  292. program.Prepend("// " + codePathB);
  293. program.Prepend("// " + fullPathB);
  294. program.Prepend("// " + codePathA);
  295. program.Prepend("// " + fullPathA);
  296. }
  297. return new ShaderCodeHolder(program, codeB, codeA);
  298. }
  299. else
  300. {
  301. ShaderProgram program = Translator.Translate(gpuVa, gpuAccessor, flags);
  302. byte[] code = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  303. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  304. if (fullPath != null && codePath != null)
  305. {
  306. program.Prepend("// " + codePath);
  307. program.Prepend("// " + fullPath);
  308. }
  309. return new ShaderCodeHolder(program, code);
  310. }
  311. }
  312. /// <summary>
  313. /// Disposes the shader cache, deleting all the cached shaders.
  314. /// It's an error to use the shader cache after disposal.
  315. /// </summary>
  316. public void Dispose()
  317. {
  318. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  319. {
  320. foreach (ShaderBundle bundle in list)
  321. {
  322. bundle.Dispose();
  323. }
  324. }
  325. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  326. {
  327. foreach (ShaderBundle bundle in list)
  328. {
  329. bundle.Dispose();
  330. }
  331. }
  332. }
  333. }
  334. }