ShaderCache.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Shader.Cache;
  5. using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
  6. using Ryujinx.Graphics.Gpu.State;
  7. using Ryujinx.Graphics.Shader;
  8. using Ryujinx.Graphics.Shader.Translation;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. namespace Ryujinx.Graphics.Gpu.Shader
  13. {
  14. /// <summary>
  15. /// Memory cache of shader code.
  16. /// </summary>
  17. class ShaderCache : IDisposable
  18. {
  19. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  20. private readonly GpuContext _context;
  21. private readonly ShaderDumper _dumper;
  22. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  23. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  24. private CacheManager _cacheManager;
  25. private Dictionary<Hash128, ShaderBundle> _gpProgramsDiskCache;
  26. private Dictionary<Hash128, ShaderBundle> _cpProgramsDiskCache;
  27. /// <summary>
  28. /// Version of the codegen (to be changed when codegen or guest format change).
  29. /// </summary>
  30. private const ulong ShaderCodeGenVersion = 1759;
  31. /// <summary>
  32. /// Creates a new instance of the shader cache.
  33. /// </summary>
  34. /// <param name="context">GPU context that the shader cache belongs to</param>
  35. public ShaderCache(GpuContext context)
  36. {
  37. _context = context;
  38. _dumper = new ShaderDumper();
  39. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  40. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  41. _gpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  42. _cpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  43. }
  44. /// <summary>
  45. /// Initialize the cache.
  46. /// </summary>
  47. internal void Initialize()
  48. {
  49. if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
  50. {
  51. _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);
  52. HashSet<Hash128> invalidEntries = new HashSet<Hash128>();
  53. ReadOnlySpan<Hash128> guestProgramList = _cacheManager.GetGuestProgramList();
  54. for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
  55. {
  56. Hash128 key = guestProgramList[programIndex];
  57. Logger.Info?.Print(LogClass.Gpu, $"Compiling shader {key} ({programIndex + 1} / {guestProgramList.Length})");
  58. byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
  59. bool hasHostCache = hostProgramBinary != null;
  60. IProgram hostProgram = null;
  61. // If the program sources aren't in the cache, compile from saved guest program.
  62. byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);
  63. if (guestProgram == null)
  64. {
  65. Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");
  66. // Should not happen, but if someone messed with the cache it's better to catch it.
  67. invalidEntries.Add(key);
  68. continue;
  69. }
  70. ReadOnlySpan<byte> guestProgramReadOnlySpan = guestProgram;
  71. ReadOnlySpan<GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);
  72. if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
  73. {
  74. Debug.Assert(cachedShaderEntries.Length == 1);
  75. GuestShaderCacheEntry entry = cachedShaderEntries[0];
  76. HostShaderCacheEntry[] hostShaderEntries = null;
  77. // Try loading host shader binary.
  78. if (hasHostCache)
  79. {
  80. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  81. hostProgramBinary = hostProgramBinarySpan.ToArray();
  82. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  83. }
  84. bool isHostProgramValid = hostProgram != null;
  85. ShaderProgram program;
  86. ShaderProgramInfo shaderProgramInfo;
  87. // Reconstruct code holder.
  88. if (isHostProgramValid)
  89. {
  90. program = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
  91. shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
  92. }
  93. else
  94. {
  95. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  96. program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
  97. }
  98. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  99. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  100. if (hostProgram == null)
  101. {
  102. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  103. // Compile shader and create program as the shader program binary got invalidated.
  104. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  105. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  106. // As the host program was invalidated, save the new entry in the cache.
  107. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  108. if (hasHostCache)
  109. {
  110. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  111. }
  112. else
  113. {
  114. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  115. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  116. }
  117. }
  118. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  119. }
  120. else
  121. {
  122. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  123. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  124. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  125. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformationFeedbackInformations(ref guestProgramReadOnlySpan, fileHeader);
  126. TranslationFlags flags = DefaultFlags;
  127. if (tfd != null)
  128. {
  129. flags = TranslationFlags.Feedback;
  130. }
  131. TranslationCounts counts = new TranslationCounts();
  132. HostShaderCacheEntry[] hostShaderEntries = null;
  133. // Try loading host shader binary.
  134. if (hasHostCache)
  135. {
  136. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  137. hostProgramBinary = hostProgramBinarySpan.ToArray();
  138. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  139. }
  140. bool isHostProgramValid = hostProgram != null;
  141. // Reconstruct code holder.
  142. for (int i = 0; i < cachedShaderEntries.Length; i++)
  143. {
  144. GuestShaderCacheEntry entry = cachedShaderEntries[i];
  145. if (entry == null)
  146. {
  147. continue;
  148. }
  149. ShaderProgram program;
  150. if (entry.Header.SizeA != 0)
  151. {
  152. ShaderProgramInfo shaderProgramInfo;
  153. if (isHostProgramValid)
  154. {
  155. program = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
  156. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  157. }
  158. else
  159. {
  160. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  161. program = Translator.CreateContext((ulong)entry.Header.Size, 0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
  162. }
  163. // NOTE: Vertex B comes first in the shader cache.
  164. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
  165. byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();
  166. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
  167. }
  168. else
  169. {
  170. ShaderProgramInfo shaderProgramInfo;
  171. if (isHostProgramValid)
  172. {
  173. program = new ShaderProgram(entry.Header.Stage, "", entry.Header.Size, entry.Header.SizeA);
  174. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  175. }
  176. else
  177. {
  178. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  179. program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
  180. }
  181. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  182. }
  183. shaderPrograms.Add(program);
  184. }
  185. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  186. if (!isHostProgramValid)
  187. {
  188. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  189. List<IShader> hostShaders = new List<IShader>();
  190. // Compile shaders and create program as the shader program binary got invalidated.
  191. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  192. {
  193. ShaderProgram program = shaders[stage]?.Program;
  194. if (program == null)
  195. {
  196. continue;
  197. }
  198. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  199. shaders[stage].HostShader = hostShader;
  200. hostShaders.Add(hostShader);
  201. }
  202. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  203. // As the host program was invalidated, save the new entry in the cache.
  204. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  205. if (hasHostCache)
  206. {
  207. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  208. }
  209. else
  210. {
  211. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  212. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  213. }
  214. }
  215. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  216. }
  217. }
  218. // Remove entries that are broken in the cache
  219. _cacheManager.RemoveManifestEntries(invalidEntries);
  220. _cacheManager.FlushToArchive();
  221. _cacheManager.Synchronize();
  222. Logger.Info?.Print(LogClass.Gpu, "Shader cache loaded.");
  223. }
  224. }
  225. /// <summary>
  226. /// Gets a compute shader from the cache.
  227. /// </summary>
  228. /// <remarks>
  229. /// This automatically translates, compiles and adds the code to the cache if not present.
  230. /// </remarks>
  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. public ShaderBundle GetComputeShader(
  240. GpuState state,
  241. ulong gpuVa,
  242. int localSizeX,
  243. int localSizeY,
  244. int localSizeZ,
  245. int localMemorySize,
  246. int sharedMemorySize)
  247. {
  248. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  249. if (isCached)
  250. {
  251. foreach (ShaderBundle cachedCpShader in list)
  252. {
  253. if (IsShaderEqual(cachedCpShader, gpuVa))
  254. {
  255. return cachedCpShader;
  256. }
  257. }
  258. }
  259. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  260. shaderContexts[0] = DecodeComputeShader(
  261. state,
  262. gpuVa,
  263. localSizeX,
  264. localSizeY,
  265. localSizeZ,
  266. localMemorySize,
  267. sharedMemorySize);
  268. bool isShaderCacheEnabled = _cacheManager != null;
  269. Hash128 programCodeHash = default;
  270. GuestShaderCacheEntry[] shaderCacheEntries = null;
  271. if (isShaderCacheEnabled)
  272. {
  273. // Compute hash and prepare data for shader disk cache comparison.
  274. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  275. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  276. }
  277. ShaderBundle cpShader;
  278. // Search for the program hash in loaded shaders.
  279. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  280. {
  281. if (isShaderCacheEnabled)
  282. {
  283. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  284. }
  285. // The shader isn't currently cached, translate it and compile it.
  286. ShaderCodeHolder shader = TranslateShader(shaderContexts[0]);
  287. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  288. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  289. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  290. cpShader = new ShaderBundle(hostProgram, shader);
  291. if (isShaderCacheEnabled)
  292. {
  293. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  294. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  295. }
  296. }
  297. if (!isCached)
  298. {
  299. list = new List<ShaderBundle>();
  300. _cpPrograms.Add(gpuVa, list);
  301. }
  302. list.Add(cpShader);
  303. return cpShader;
  304. }
  305. /// <summary>
  306. /// Gets a graphics shader program from the shader cache.
  307. /// This includes all the specified shader stages.
  308. /// </summary>
  309. /// <remarks>
  310. /// This automatically translates, compiles and adds the code to the cache if not present.
  311. /// </remarks>
  312. /// <param name="state">Current GPU state</param>
  313. /// <param name="addresses">Addresses of the shaders for each stage</param>
  314. /// <returns>Compiled graphics shader code</returns>
  315. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  316. {
  317. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  318. if (isCached)
  319. {
  320. foreach (ShaderBundle cachedGpShaders in list)
  321. {
  322. if (IsShaderEqual(cachedGpShaders, addresses))
  323. {
  324. return cachedGpShaders;
  325. }
  326. }
  327. }
  328. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages];
  329. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  330. TranslationFlags flags = DefaultFlags;
  331. if (tfd != null)
  332. {
  333. flags |= TranslationFlags.Feedback;
  334. }
  335. TranslationCounts counts = new TranslationCounts();
  336. if (addresses.VertexA != 0)
  337. {
  338. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  339. }
  340. else
  341. {
  342. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  343. }
  344. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  345. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  346. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  347. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  348. bool isShaderCacheEnabled = _cacheManager != null;
  349. Hash128 programCodeHash = default;
  350. GuestShaderCacheEntry[] shaderCacheEntries = null;
  351. if (isShaderCacheEnabled)
  352. {
  353. // Compute hash and prepare data for shader disk cache comparison.
  354. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  355. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  356. }
  357. ShaderBundle gpShaders;
  358. // Search for the program hash in loaded shaders.
  359. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  360. {
  361. if (isShaderCacheEnabled)
  362. {
  363. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  364. }
  365. // The shader isn't currently cached, translate it and compile it.
  366. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  367. shaders[0] = TranslateShader(shaderContexts[0]);
  368. shaders[1] = TranslateShader(shaderContexts[1]);
  369. shaders[2] = TranslateShader(shaderContexts[2]);
  370. shaders[3] = TranslateShader(shaderContexts[3]);
  371. shaders[4] = TranslateShader(shaderContexts[4]);
  372. List<IShader> hostShaders = new List<IShader>();
  373. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  374. {
  375. ShaderProgram program = shaders[stage]?.Program;
  376. if (program == null)
  377. {
  378. continue;
  379. }
  380. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  381. shaders[stage].HostShader = hostShader;
  382. hostShaders.Add(hostShader);
  383. }
  384. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  385. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  386. gpShaders = new ShaderBundle(hostProgram, shaders);
  387. if (isShaderCacheEnabled)
  388. {
  389. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  390. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  391. }
  392. }
  393. if (!isCached)
  394. {
  395. list = new List<ShaderBundle>();
  396. _gpPrograms.Add(addresses, list);
  397. }
  398. list.Add(gpShaders);
  399. return gpShaders;
  400. }
  401. /// <summary>
  402. /// Gets transform feedback state from the current GPU state.
  403. /// </summary>
  404. /// <param name="state">Current GPU state</param>
  405. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  406. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  407. {
  408. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  409. if (!tfEnable)
  410. {
  411. return null;
  412. }
  413. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  414. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  415. {
  416. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  417. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  418. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  419. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  420. }
  421. return descs;
  422. }
  423. /// <summary>
  424. /// Checks if compute shader code in memory is equal to the cached shader.
  425. /// </summary>
  426. /// <param name="cpShader">Cached compute shader</param>
  427. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  428. /// <returns>True if the code is different, false otherwise</returns>
  429. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  430. {
  431. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  432. }
  433. /// <summary>
  434. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  435. /// </summary>
  436. /// <param name="gpShaders">Cached graphics shaders</param>
  437. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  438. /// <returns>True if the code is different, false otherwise</returns>
  439. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  440. {
  441. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  442. {
  443. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  444. ulong gpuVa = 0;
  445. switch (stage)
  446. {
  447. case 0: gpuVa = addresses.Vertex; break;
  448. case 1: gpuVa = addresses.TessControl; break;
  449. case 2: gpuVa = addresses.TessEvaluation; break;
  450. case 3: gpuVa = addresses.Geometry; break;
  451. case 4: gpuVa = addresses.Fragment; break;
  452. }
  453. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  454. {
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. /// <summary>
  461. /// Checks if the code of the specified cached shader is different from the code in memory.
  462. /// </summary>
  463. /// <param name="shader">Cached shader to compare with</param>
  464. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  465. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  466. /// <returns>True if the code is different, false otherwise</returns>
  467. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  468. {
  469. if (shader == null)
  470. {
  471. return true;
  472. }
  473. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  474. bool equals = memoryCode.SequenceEqual(shader.Code);
  475. if (equals && shader.Code2 != null)
  476. {
  477. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  478. equals = memoryCode.SequenceEqual(shader.Code2);
  479. }
  480. return equals;
  481. }
  482. /// <summary>
  483. /// Decode the binary Maxwell shader code to a translator context.
  484. /// </summary>
  485. /// <param name="state">Current GPU state</param>
  486. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  487. /// <param name="localSizeX">Local group size X of the computer shader</param>
  488. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  489. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  490. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  491. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  492. /// <returns>The generated translator context</returns>
  493. private TranslatorContext DecodeComputeShader(
  494. GpuState state,
  495. ulong gpuVa,
  496. int localSizeX,
  497. int localSizeY,
  498. int localSizeZ,
  499. int localMemorySize,
  500. int sharedMemorySize)
  501. {
  502. if (gpuVa == 0)
  503. {
  504. return null;
  505. }
  506. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  507. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  508. }
  509. /// <summary>
  510. /// Decode the binary Maxwell shader code to a translator context.
  511. /// </summary>
  512. /// <remarks>
  513. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  514. /// </remarks>
  515. /// <param name="state">Current GPU state</param>
  516. /// <param name="counts">Cumulative shader resource counts</param>
  517. /// <param name="flags">Flags that controls shader translation</param>
  518. /// <param name="stage">Shader stage</param>
  519. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  520. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  521. /// <returns>The generated translator context</returns>
  522. private TranslatorContext DecodeGraphicsShader(
  523. GpuState state,
  524. TranslationCounts counts,
  525. TranslationFlags flags,
  526. ShaderStage stage,
  527. ulong gpuVa,
  528. ulong gpuVaA = 0)
  529. {
  530. if (gpuVa == 0)
  531. {
  532. return null;
  533. }
  534. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  535. if (gpuVaA != 0)
  536. {
  537. return Translator.CreateContext(gpuVaA, gpuVa, gpuAccessor, flags, counts);
  538. }
  539. else
  540. {
  541. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  542. }
  543. }
  544. /// <summary>
  545. /// Translates a previously generated translator context to something that the host API accepts.
  546. /// </summary>
  547. /// <param name="translatorContext">Current translator context to translate</param>
  548. /// <returns>Compiled graphics shader code</returns>
  549. private ShaderCodeHolder TranslateShader(TranslatorContext translatorContext)
  550. {
  551. if (translatorContext == null)
  552. {
  553. return null;
  554. }
  555. if (translatorContext.AddressA != 0)
  556. {
  557. byte[] codeA = _context.MemoryManager.GetSpan(translatorContext.AddressA, translatorContext.SizeA).ToArray();
  558. byte[] codeB = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  559. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  560. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  561. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  562. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  563. {
  564. program.Prepend("// " + codePathB);
  565. program.Prepend("// " + fullPathB);
  566. program.Prepend("// " + codePathA);
  567. program.Prepend("// " + fullPathA);
  568. }
  569. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  570. }
  571. else
  572. {
  573. byte[] code = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  574. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  575. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  576. if (fullPath != null && codePath != null)
  577. {
  578. program.Prepend("// " + codePath);
  579. program.Prepend("// " + fullPath);
  580. }
  581. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  582. }
  583. }
  584. /// <summary>
  585. /// Disposes the shader cache, deleting all the cached shaders.
  586. /// It's an error to use the shader cache after disposal.
  587. /// </summary>
  588. public void Dispose()
  589. {
  590. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  591. {
  592. foreach (ShaderBundle bundle in list)
  593. {
  594. bundle.Dispose();
  595. }
  596. }
  597. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  598. {
  599. foreach (ShaderBundle bundle in list)
  600. {
  601. bundle.Dispose();
  602. }
  603. }
  604. _cacheManager?.Dispose();
  605. }
  606. }
  607. }