ShaderCache.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Image;
  3. using Ryujinx.Graphics.Gpu.State;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Graphics.Shader.Translation;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Runtime.InteropServices;
  9. namespace Ryujinx.Graphics.Gpu.Shader
  10. {
  11. using TextureDescriptor = Image.TextureDescriptor;
  12. /// <summary>
  13. /// Memory cache of shader code.
  14. /// </summary>
  15. class ShaderCache
  16. {
  17. private const int MaxProgramSize = 0x100000;
  18. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  19. private GpuContext _context;
  20. private ShaderDumper _dumper;
  21. private Dictionary<ulong, List<ComputeShader>> _cpPrograms;
  22. private Dictionary<ShaderAddresses, List<GraphicsShader>> _gpPrograms;
  23. /// <summary>
  24. /// Creates a new instance of the shader cache.
  25. /// </summary>
  26. /// <param name="context">GPU context that the shader cache belongs to</param>
  27. public ShaderCache(GpuContext context)
  28. {
  29. _context = context;
  30. _dumper = new ShaderDumper();
  31. _cpPrograms = new Dictionary<ulong, List<ComputeShader>>();
  32. _gpPrograms = new Dictionary<ShaderAddresses, List<GraphicsShader>>();
  33. }
  34. /// <summary>
  35. /// Gets a compute shader from the cache.
  36. /// This automatically translates, compiles and adds the code to the cache if not present.
  37. /// </summary>
  38. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  39. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  40. /// <param name="localSizeX">Local group size X of the computer shader</param>
  41. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  42. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  43. /// <returns>Compiled compute shader code</returns>
  44. public ComputeShader GetComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  45. {
  46. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ComputeShader> list);
  47. if (isCached)
  48. {
  49. foreach (ComputeShader cachedCpShader in list)
  50. {
  51. if (!IsShaderDifferent(cachedCpShader, gpuVa))
  52. {
  53. return cachedCpShader;
  54. }
  55. }
  56. }
  57. CachedShader shader = TranslateComputeShader(gpuVa, sharedMemorySize, localSizeX, localSizeY, localSizeZ);
  58. IShader hostShader = _context.Renderer.CompileShader(shader.Program);
  59. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { hostShader });
  60. ulong address = _context.MemoryManager.Translate(gpuVa);
  61. ComputeShader cpShader = new ComputeShader(hostProgram, shader);
  62. if (!isCached)
  63. {
  64. list = new List<ComputeShader>();
  65. _cpPrograms.Add(gpuVa, list);
  66. }
  67. list.Add(cpShader);
  68. return cpShader;
  69. }
  70. /// <summary>
  71. /// Gets a graphics shader program from the shader cache.
  72. /// This includes all the specified shader stages.
  73. /// This automatically translates, compiles and adds the code to the cache if not present.
  74. /// </summary>
  75. /// <param name="state">Current GPU state</param>
  76. /// <param name="addresses">Addresses of the shaders for each stage</param>
  77. /// <returns>Compiled graphics shader code</returns>
  78. public GraphicsShader GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  79. {
  80. bool isCached = _gpPrograms.TryGetValue(addresses, out List<GraphicsShader> list);
  81. if (isCached)
  82. {
  83. foreach (GraphicsShader cachedGpShaders in list)
  84. {
  85. if (!IsShaderDifferent(cachedGpShaders, addresses))
  86. {
  87. return cachedGpShaders;
  88. }
  89. }
  90. }
  91. GraphicsShader gpShaders = new GraphicsShader();
  92. if (addresses.VertexA != 0)
  93. {
  94. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  95. }
  96. else
  97. {
  98. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  99. }
  100. gpShaders.Shader[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  101. gpShaders.Shader[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  102. gpShaders.Shader[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  103. gpShaders.Shader[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  104. BackpropQualifiers(gpShaders);
  105. List<IShader> hostShaders = new List<IShader>();
  106. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  107. {
  108. ShaderProgram program = gpShaders.Shader[stage].Program;
  109. if (program == null)
  110. {
  111. continue;
  112. }
  113. IShader hostShader = _context.Renderer.CompileShader(program);
  114. gpShaders.Shader[stage].Shader = hostShader;
  115. hostShaders.Add(hostShader);
  116. }
  117. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  118. if (!isCached)
  119. {
  120. list = new List<GraphicsShader>();
  121. _gpPrograms.Add(addresses, list);
  122. }
  123. list.Add(gpShaders);
  124. return gpShaders;
  125. }
  126. /// <summary>
  127. /// Checks if compute shader code in memory is different from the cached shader.
  128. /// </summary>
  129. /// <param name="cpShader">Cached compute shader</param>
  130. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  131. /// <returns>True if the code is different, false otherwise</returns>
  132. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  133. {
  134. return IsShaderDifferent(cpShader.Shader, gpuVa);
  135. }
  136. /// <summary>
  137. /// Checks if graphics shader code from all stages in memory is different from the cached shaders.
  138. /// </summary>
  139. /// <param name="gpShaders">Cached graphics shaders</param>
  140. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  141. /// <returns>True if the code is different, false otherwise</returns>
  142. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  143. {
  144. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  145. {
  146. CachedShader shader = gpShaders.Shader[stage];
  147. if (shader.Code == null)
  148. {
  149. continue;
  150. }
  151. ulong gpuVa = 0;
  152. switch (stage)
  153. {
  154. case 0: gpuVa = addresses.Vertex; break;
  155. case 1: gpuVa = addresses.TessControl; break;
  156. case 2: gpuVa = addresses.TessEvaluation; break;
  157. case 3: gpuVa = addresses.Geometry; break;
  158. case 4: gpuVa = addresses.Fragment; break;
  159. }
  160. if (IsShaderDifferent(shader, gpuVa))
  161. {
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. /// <summary>
  168. /// Checks if the code of the specified cached shader is different from the code in memory.
  169. /// </summary>
  170. /// <param name="shader">Cached shader to compare with</param>
  171. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  172. /// <returns>True if the code is different, false otherwise</returns>
  173. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  174. {
  175. for (int index = 0; index < shader.Code.Length; index++)
  176. {
  177. if (_context.MemoryAccessor.ReadInt32(gpuVa + (ulong)index * 4) != shader.Code[index])
  178. {
  179. return true;
  180. }
  181. }
  182. return false;
  183. }
  184. /// <summary>
  185. /// Translates the binary Maxwell shader code to something that the host API accepts.
  186. /// </summary>
  187. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  188. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  189. /// <param name="localSizeX">Local group size X of the computer shader</param>
  190. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  191. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  192. /// <returns>Compiled compute shader code</returns>
  193. private CachedShader TranslateComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  194. {
  195. if (gpuVa == 0)
  196. {
  197. return null;
  198. }
  199. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  200. {
  201. switch (info)
  202. {
  203. case QueryInfoName.ComputeLocalSizeX:
  204. return localSizeX;
  205. case QueryInfoName.ComputeLocalSizeY:
  206. return localSizeY;
  207. case QueryInfoName.ComputeLocalSizeZ:
  208. return localSizeZ;
  209. case QueryInfoName.ComputeSharedMemorySize:
  210. return sharedMemorySize;
  211. }
  212. return QueryInfoCommon(info);
  213. };
  214. ShaderProgram program;
  215. Span<byte> code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  216. program = Translator.Translate(code, queryInfo, DefaultFlags | TranslationFlags.Compute);
  217. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  218. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  219. if (fullPath != null && codePath != null)
  220. {
  221. program.Prepend("// " + codePath);
  222. program.Prepend("// " + fullPath);
  223. }
  224. return new CachedShader(program, codeCached);
  225. }
  226. /// <summary>
  227. /// Translates the binary Maxwell shader code to something that the host API accepts.
  228. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  229. /// </summary>
  230. /// <param name="state">Current GPU state</param>
  231. /// <param name="stage">Shader stage</param>
  232. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  233. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  234. /// <returns></returns>
  235. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  236. {
  237. if (gpuVa == 0)
  238. {
  239. return new CachedShader(null, null);
  240. }
  241. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  242. {
  243. switch (info)
  244. {
  245. case QueryInfoName.IsTextureBuffer:
  246. return Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index));
  247. case QueryInfoName.IsTextureRectangle:
  248. return Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index));
  249. case QueryInfoName.PrimitiveTopology:
  250. return (int)GetPrimitiveTopology();
  251. case QueryInfoName.ViewportTransformEnable:
  252. return Convert.ToInt32(_context.Methods.GetViewportTransformEnable(state));
  253. }
  254. return QueryInfoCommon(info);
  255. };
  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, queryInfo, 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, queryInfo, 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.Shader[4].Program;
  299. bool isFirst = true;
  300. for (int stage = 3; stage >= 0; stage--)
  301. {
  302. if (program.Shader[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.Shader[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
  314. }
  315. else
  316. {
  317. program.Shader[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. switch (info)
  400. {
  401. case QueryInfoName.MaximumViewportDimensions:
  402. return _context.Capabilities.MaximumViewportDimensions;
  403. case QueryInfoName.StorageBufferOffsetAlignment:
  404. return _context.Capabilities.StorageBufferOffsetAlignment;
  405. case QueryInfoName.SupportsNonConstantTextureOffset:
  406. return Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset);
  407. }
  408. return 0;
  409. }
  410. }
  411. }