ShaderCache.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. class ShaderCache
  13. {
  14. private const int MaxProgramSize = 0x100000;
  15. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  16. private GpuContext _context;
  17. private ShaderDumper _dumper;
  18. private Dictionary<ulong, List<ComputeShader>> _cpPrograms;
  19. private Dictionary<ShaderAddresses, List<GraphicsShader>> _gpPrograms;
  20. public ShaderCache(GpuContext context)
  21. {
  22. _context = context;
  23. _dumper = new ShaderDumper(context);
  24. _cpPrograms = new Dictionary<ulong, List<ComputeShader>>();
  25. _gpPrograms = new Dictionary<ShaderAddresses, List<GraphicsShader>>();
  26. }
  27. public ComputeShader GetComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  28. {
  29. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ComputeShader> list);
  30. if (isCached)
  31. {
  32. foreach (ComputeShader cachedCpShader in list)
  33. {
  34. if (!IsShaderDifferent(cachedCpShader, gpuVa))
  35. {
  36. return cachedCpShader;
  37. }
  38. }
  39. }
  40. CachedShader shader = TranslateComputeShader(gpuVa, sharedMemorySize, localSizeX, localSizeY, localSizeZ);
  41. IShader hostShader = _context.Renderer.CompileShader(shader.Program);
  42. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { hostShader });
  43. ulong address = _context.MemoryManager.Translate(gpuVa);
  44. ComputeShader cpShader = new ComputeShader(hostProgram, shader);
  45. if (!isCached)
  46. {
  47. list = new List<ComputeShader>();
  48. _cpPrograms.Add(gpuVa, list);
  49. }
  50. list.Add(cpShader);
  51. return cpShader;
  52. }
  53. public GraphicsShader GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  54. {
  55. bool isCached = _gpPrograms.TryGetValue(addresses, out List<GraphicsShader> list);
  56. if (isCached)
  57. {
  58. foreach (GraphicsShader cachedGpShaders in list)
  59. {
  60. if (!IsShaderDifferent(cachedGpShaders, addresses))
  61. {
  62. return cachedGpShaders;
  63. }
  64. }
  65. }
  66. GraphicsShader gpShaders = new GraphicsShader();
  67. if (addresses.VertexA != 0)
  68. {
  69. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  70. }
  71. else
  72. {
  73. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  74. }
  75. gpShaders.Shader[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  76. gpShaders.Shader[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  77. gpShaders.Shader[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  78. gpShaders.Shader[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  79. BackpropQualifiers(gpShaders);
  80. List<IShader> hostShaders = new List<IShader>();
  81. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  82. {
  83. ShaderProgram program = gpShaders.Shader[stage].Program;
  84. if (program == null)
  85. {
  86. continue;
  87. }
  88. IShader hostShader = _context.Renderer.CompileShader(program);
  89. gpShaders.Shader[stage].Shader = hostShader;
  90. hostShaders.Add(hostShader);
  91. }
  92. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  93. if (!isCached)
  94. {
  95. list = new List<GraphicsShader>();
  96. _gpPrograms.Add(addresses, list);
  97. }
  98. list.Add(gpShaders);
  99. return gpShaders;
  100. }
  101. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  102. {
  103. return IsShaderDifferent(cpShader.Shader, gpuVa);
  104. }
  105. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  106. {
  107. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  108. {
  109. CachedShader shader = gpShaders.Shader[stage];
  110. if (shader.Code == null)
  111. {
  112. continue;
  113. }
  114. ulong gpuVa = 0;
  115. switch (stage)
  116. {
  117. case 0: gpuVa = addresses.Vertex; break;
  118. case 1: gpuVa = addresses.TessControl; break;
  119. case 2: gpuVa = addresses.TessEvaluation; break;
  120. case 3: gpuVa = addresses.Geometry; break;
  121. case 4: gpuVa = addresses.Fragment; break;
  122. }
  123. if (IsShaderDifferent(shader, gpuVa))
  124. {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  131. {
  132. for (int index = 0; index < shader.Code.Length; index++)
  133. {
  134. if (_context.MemoryAccessor.ReadInt32(gpuVa + (ulong)index * 4) != shader.Code[index])
  135. {
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. private CachedShader TranslateComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  142. {
  143. if (gpuVa == 0)
  144. {
  145. return null;
  146. }
  147. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  148. {
  149. switch (info)
  150. {
  151. case QueryInfoName.ComputeLocalSizeX:
  152. return localSizeX;
  153. case QueryInfoName.ComputeLocalSizeY:
  154. return localSizeY;
  155. case QueryInfoName.ComputeLocalSizeZ:
  156. return localSizeZ;
  157. case QueryInfoName.ComputeSharedMemorySize:
  158. return sharedMemorySize;
  159. }
  160. return QueryInfoCommon(info);
  161. };
  162. ShaderProgram program;
  163. Span<byte> code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  164. program = Translator.Translate(code, queryInfo, DefaultFlags | TranslationFlags.Compute);
  165. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  166. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  167. if (fullPath != null && codePath != null)
  168. {
  169. program.Prepend("// " + codePath);
  170. program.Prepend("// " + fullPath);
  171. }
  172. return new CachedShader(program, codeCached);
  173. }
  174. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  175. {
  176. if (gpuVa == 0)
  177. {
  178. return new CachedShader(null, null);
  179. }
  180. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  181. {
  182. switch (info)
  183. {
  184. case QueryInfoName.IsTextureBuffer:
  185. return Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index));
  186. case QueryInfoName.IsTextureRectangle:
  187. return Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index));
  188. case QueryInfoName.PrimitiveTopology:
  189. return (int)GetPrimitiveTopology();
  190. case QueryInfoName.ViewportTransformEnable:
  191. return Convert.ToInt32(_context.Methods.GetViewportTransformEnable(state));
  192. }
  193. return QueryInfoCommon(info);
  194. };
  195. ShaderProgram program;
  196. int[] codeCached = null;
  197. if (gpuVaA != 0)
  198. {
  199. Span<byte> codeA = _context.MemoryAccessor.Read(gpuVaA, MaxProgramSize);
  200. Span<byte> codeB = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  201. program = Translator.Translate(codeA, codeB, queryInfo, DefaultFlags);
  202. // TODO: We should also take "codeA" into account.
  203. codeCached = MemoryMarshal.Cast<byte, int>(codeB.Slice(0, program.Size)).ToArray();
  204. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  205. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  206. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  207. {
  208. program.Prepend("// " + codePathB);
  209. program.Prepend("// " + fullPathB);
  210. program.Prepend("// " + codePathA);
  211. program.Prepend("// " + fullPathA);
  212. }
  213. }
  214. else
  215. {
  216. Span<byte> code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  217. program = Translator.Translate(code, queryInfo, DefaultFlags);
  218. codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  219. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  220. if (fullPath != null && codePath != null)
  221. {
  222. program.Prepend("// " + codePath);
  223. program.Prepend("// " + fullPath);
  224. }
  225. }
  226. ulong address = _context.MemoryManager.Translate(gpuVa);
  227. return new CachedShader(program, codeCached);
  228. }
  229. private void BackpropQualifiers(GraphicsShader program)
  230. {
  231. ShaderProgram fragmentShader = program.Shader[4].Program;
  232. bool isFirst = true;
  233. for (int stage = 3; stage >= 0; stage--)
  234. {
  235. if (program.Shader[stage].Program == null)
  236. {
  237. continue;
  238. }
  239. // We need to iterate backwards, since we do name replacement,
  240. // and it would otherwise replace a subset of the longer names.
  241. for (int attr = 31; attr >= 0; attr--)
  242. {
  243. string iq = fragmentShader?.Info.InterpolationQualifiers[attr].ToGlslQualifier() ?? string.Empty;
  244. if (isFirst && iq != string.Empty)
  245. {
  246. program.Shader[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
  247. }
  248. else
  249. {
  250. program.Shader[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr} ", string.Empty);
  251. }
  252. }
  253. isFirst = false;
  254. }
  255. }
  256. private InputTopology GetPrimitiveTopology()
  257. {
  258. switch (_context.Methods.PrimitiveType)
  259. {
  260. case PrimitiveType.Points:
  261. return InputTopology.Points;
  262. case PrimitiveType.Lines:
  263. case PrimitiveType.LineLoop:
  264. case PrimitiveType.LineStrip:
  265. return InputTopology.Lines;
  266. case PrimitiveType.LinesAdjacency:
  267. case PrimitiveType.LineStripAdjacency:
  268. return InputTopology.LinesAdjacency;
  269. case PrimitiveType.Triangles:
  270. case PrimitiveType.TriangleStrip:
  271. case PrimitiveType.TriangleFan:
  272. return InputTopology.Triangles;
  273. case PrimitiveType.TrianglesAdjacency:
  274. case PrimitiveType.TriangleStripAdjacency:
  275. return InputTopology.TrianglesAdjacency;
  276. }
  277. return InputTopology.Points;
  278. }
  279. private bool QueryIsTextureBuffer(GpuState state, int stageIndex, int index)
  280. {
  281. return GetTextureDescriptor(state, stageIndex, index).UnpackTextureTarget() == TextureTarget.TextureBuffer;
  282. }
  283. private bool QueryIsTextureRectangle(GpuState state, int stageIndex, int index)
  284. {
  285. var descriptor = GetTextureDescriptor(state, stageIndex, index);
  286. TextureTarget target = descriptor.UnpackTextureTarget();
  287. bool is2DTexture = target == TextureTarget.Texture2D ||
  288. target == TextureTarget.Texture2DRect;
  289. return !descriptor.UnpackTextureCoordNormalized() && is2DTexture;
  290. }
  291. private TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int index)
  292. {
  293. return _context.Methods.TextureManager.GetGraphicsTextureDescriptor(state, stageIndex, index);
  294. }
  295. private int QueryInfoCommon(QueryInfoName info)
  296. {
  297. switch (info)
  298. {
  299. case QueryInfoName.MaximumViewportDimensions:
  300. return _context.Capabilities.MaximumViewportDimensions;
  301. case QueryInfoName.StorageBufferOffsetAlignment:
  302. return _context.Capabilities.StorageBufferOffsetAlignment;
  303. case QueryInfoName.SupportsNonConstantTextureOffset:
  304. return Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset);
  305. }
  306. return 0;
  307. }
  308. }
  309. }