ShaderCache.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Gpu.Shader.Cache;
  6. using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
  7. using Ryujinx.Graphics.Gpu.State;
  8. using Ryujinx.Graphics.Shader;
  9. using Ryujinx.Graphics.Shader.Translation;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace Ryujinx.Graphics.Gpu.Shader
  16. {
  17. /// <summary>
  18. /// Memory cache of shader code.
  19. /// </summary>
  20. class ShaderCache : IDisposable
  21. {
  22. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  23. private readonly GpuContext _context;
  24. private readonly ShaderDumper _dumper;
  25. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  26. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  27. private CacheManager _cacheManager;
  28. private Dictionary<Hash128, ShaderBundle> _gpProgramsDiskCache;
  29. private Dictionary<Hash128, ShaderBundle> _cpProgramsDiskCache;
  30. /// <summary>
  31. /// Version of the codegen (to be changed when codegen or guest format change).
  32. /// </summary>
  33. private const ulong ShaderCodeGenVersion = 2412;
  34. // Progress reporting helpers
  35. private volatile int _shaderCount;
  36. private volatile int _totalShaderCount;
  37. public event Action<ShaderCacheState, int, int> ShaderCacheStateChanged;
  38. /// <summary>
  39. /// Creates a new instance of the shader cache.
  40. /// </summary>
  41. /// <param name="context">GPU context that the shader cache belongs to</param>
  42. public ShaderCache(GpuContext context)
  43. {
  44. _context = context;
  45. _dumper = new ShaderDumper();
  46. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  47. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  48. _gpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  49. _cpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  50. }
  51. /// <summary>
  52. /// Initialize the cache.
  53. /// </summary>
  54. internal void Initialize()
  55. {
  56. if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
  57. {
  58. _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);
  59. bool isReadOnly = _cacheManager.IsReadOnly;
  60. HashSet<Hash128> invalidEntries = null;
  61. if (isReadOnly)
  62. {
  63. Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
  64. }
  65. else
  66. {
  67. invalidEntries = new HashSet<Hash128>();
  68. }
  69. ReadOnlySpan<Hash128> guestProgramList = _cacheManager.GetGuestProgramList();
  70. using AutoResetEvent progressReportEvent = new AutoResetEvent(false);
  71. _shaderCount = 0;
  72. _totalShaderCount = guestProgramList.Length;
  73. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Start, _shaderCount, _totalShaderCount);
  74. Thread progressReportThread = null;
  75. if (guestProgramList.Length > 0)
  76. {
  77. progressReportThread = new Thread(ReportProgress)
  78. {
  79. Name = "ShaderCache.ProgressReporter",
  80. Priority = ThreadPriority.Lowest,
  81. IsBackground = true
  82. };
  83. progressReportThread.Start(progressReportEvent);
  84. }
  85. // Make sure these are initialized before doing compilation.
  86. Capabilities caps = _context.Capabilities;
  87. int maxTaskCount = Math.Min(Environment.ProcessorCount, 8);
  88. int programIndex = 0;
  89. List<ShaderCompileTask> activeTasks = new List<ShaderCompileTask>();
  90. AutoResetEvent taskDoneEvent = new AutoResetEvent(false);
  91. // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
  92. // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.
  93. while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
  94. {
  95. if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
  96. {
  97. // Begin a new shader compilation.
  98. Hash128 key = guestProgramList[programIndex];
  99. byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
  100. bool hasHostCache = hostProgramBinary != null;
  101. IProgram hostProgram = null;
  102. // If the program sources aren't in the cache, compile from saved guest program.
  103. byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);
  104. if (guestProgram == null)
  105. {
  106. Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");
  107. // Should not happen, but if someone messed with the cache it's better to catch it.
  108. invalidEntries?.Add(key);
  109. _shaderCount = ++programIndex;
  110. continue;
  111. }
  112. ReadOnlySpan<byte> guestProgramReadOnlySpan = guestProgram;
  113. ReadOnlySpan<GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);
  114. if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
  115. {
  116. Debug.Assert(cachedShaderEntries.Length == 1);
  117. GuestShaderCacheEntry entry = cachedShaderEntries[0];
  118. HostShaderCacheEntry[] hostShaderEntries = null;
  119. // Try loading host shader binary.
  120. if (hasHostCache)
  121. {
  122. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  123. hostProgramBinary = hostProgramBinarySpan.ToArray();
  124. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  125. }
  126. ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
  127. activeTasks.Add(task);
  128. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  129. {
  130. ShaderProgram program = null;
  131. ShaderProgramInfo shaderProgramInfo = null;
  132. if (isHostProgramValid)
  133. {
  134. // Reconstruct code holder.
  135. program = new ShaderProgram(entry.Header.Stage, "");
  136. shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
  137. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  138. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  139. return true;
  140. }
  141. else
  142. {
  143. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  144. Task compileTask = Task.Run(() =>
  145. {
  146. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  147. program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
  148. });
  149. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  150. {
  151. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  152. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  153. // Compile shader and create program as the shader program binary got invalidated.
  154. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  155. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  156. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  157. {
  158. // As the host program was invalidated, save the new entry in the cache.
  159. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  160. if (!isReadOnly)
  161. {
  162. if (hasHostCache)
  163. {
  164. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  165. }
  166. else
  167. {
  168. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  169. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  170. }
  171. }
  172. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  173. return true;
  174. });
  175. return false; // Not finished: still need to compile the host program.
  176. });
  177. return false; // Not finished: translating the program.
  178. }
  179. });
  180. }
  181. else
  182. {
  183. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  184. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  185. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  186. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);
  187. TranslationFlags flags = DefaultFlags;
  188. if (tfd != null)
  189. {
  190. flags |= TranslationFlags.Feedback;
  191. }
  192. TranslationCounts counts = new TranslationCounts();
  193. HostShaderCacheEntry[] hostShaderEntries = null;
  194. // Try loading host shader binary.
  195. if (hasHostCache)
  196. {
  197. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  198. hostProgramBinary = hostProgramBinarySpan.ToArray();
  199. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  200. }
  201. ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
  202. activeTasks.Add(task);
  203. GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();
  204. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  205. {
  206. Task compileTask = Task.Run(() =>
  207. {
  208. // Reconstruct code holder.
  209. for (int i = 0; i < entries.Length; i++)
  210. {
  211. GuestShaderCacheEntry entry = entries[i];
  212. if (entry == null)
  213. {
  214. continue;
  215. }
  216. ShaderProgram program;
  217. if (entry.Header.SizeA != 0)
  218. {
  219. ShaderProgramInfo shaderProgramInfo;
  220. if (isHostProgramValid)
  221. {
  222. program = new ShaderProgram(entry.Header.Stage, "");
  223. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  224. }
  225. else
  226. {
  227. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  228. TranslatorContext translatorContext = Translator.CreateContext(0, gpuAccessor, flags, counts);
  229. TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, flags | TranslationFlags.VertexA, counts);
  230. program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
  231. }
  232. // NOTE: Vertex B comes first in the shader cache.
  233. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
  234. byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();
  235. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
  236. }
  237. else
  238. {
  239. ShaderProgramInfo shaderProgramInfo;
  240. if (isHostProgramValid)
  241. {
  242. program = new ShaderProgram(entry.Header.Stage, "");
  243. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  244. }
  245. else
  246. {
  247. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  248. program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
  249. }
  250. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  251. }
  252. shaderPrograms.Add(program);
  253. }
  254. });
  255. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  256. {
  257. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  258. if (!isHostProgramValid)
  259. {
  260. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  261. List<IShader> hostShaders = new List<IShader>();
  262. // Compile shaders and create program as the shader program binary got invalidated.
  263. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  264. {
  265. ShaderProgram program = shaders[stage]?.Program;
  266. if (program == null)
  267. {
  268. continue;
  269. }
  270. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  271. shaders[stage].HostShader = hostShader;
  272. hostShaders.Add(hostShader);
  273. }
  274. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  275. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  276. {
  277. // As the host program was invalidated, save the new entry in the cache.
  278. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  279. if (!isReadOnly)
  280. {
  281. if (hasHostCache)
  282. {
  283. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  284. }
  285. else
  286. {
  287. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  288. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  289. }
  290. }
  291. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  292. return true;
  293. });
  294. return false; // Not finished: still need to compile the host program.
  295. }
  296. else
  297. {
  298. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  299. return true;
  300. }
  301. });
  302. return false; // Not finished: translating the program.
  303. });
  304. }
  305. _shaderCount = ++programIndex;
  306. }
  307. // Process the queue.
  308. for (int i = 0; i < activeTasks.Count; i++)
  309. {
  310. ShaderCompileTask task = activeTasks[i];
  311. if (task.IsDone())
  312. {
  313. activeTasks.RemoveAt(i--);
  314. }
  315. }
  316. if (activeTasks.Count == maxTaskCount)
  317. {
  318. // Wait for a task to be done, or for 1ms.
  319. // Host shader compilation cannot signal when it is done,
  320. // so the 1ms timeout is required to poll status.
  321. taskDoneEvent.WaitOne(1);
  322. }
  323. }
  324. if (!isReadOnly)
  325. {
  326. // Remove entries that are broken in the cache
  327. _cacheManager.RemoveManifestEntries(invalidEntries);
  328. _cacheManager.FlushToArchive();
  329. _cacheManager.Synchronize();
  330. }
  331. progressReportEvent.Set();
  332. progressReportThread?.Join();
  333. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);
  334. Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
  335. }
  336. }
  337. /// <summary>
  338. /// Raises ShaderCacheStateChanged events periodically.
  339. /// </summary>
  340. private void ReportProgress(object state)
  341. {
  342. const int refreshRate = 50; // ms
  343. AutoResetEvent endEvent = (AutoResetEvent)state;
  344. int count = 0;
  345. do
  346. {
  347. int newCount = _shaderCount;
  348. if (count != newCount)
  349. {
  350. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loading, newCount, _totalShaderCount);
  351. count = newCount;
  352. }
  353. }
  354. while (!endEvent.WaitOne(refreshRate));
  355. }
  356. /// <summary>
  357. /// Gets a compute shader from the cache.
  358. /// </summary>
  359. /// <remarks>
  360. /// This automatically translates, compiles and adds the code to the cache if not present.
  361. /// </remarks>
  362. /// <param name="state">Current GPU state</param>
  363. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  364. /// <param name="localSizeX">Local group size X of the computer shader</param>
  365. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  366. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  367. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  368. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  369. /// <returns>Compiled compute shader code</returns>
  370. public ShaderBundle GetComputeShader(
  371. GpuState state,
  372. ulong gpuVa,
  373. int localSizeX,
  374. int localSizeY,
  375. int localSizeZ,
  376. int localMemorySize,
  377. int sharedMemorySize)
  378. {
  379. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  380. if (isCached)
  381. {
  382. foreach (ShaderBundle cachedCpShader in list)
  383. {
  384. if (IsShaderEqual(state.Channel.MemoryManager, cachedCpShader, gpuVa))
  385. {
  386. return cachedCpShader;
  387. }
  388. }
  389. }
  390. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  391. shaderContexts[0] = DecodeComputeShader(
  392. state,
  393. gpuVa,
  394. localSizeX,
  395. localSizeY,
  396. localSizeZ,
  397. localMemorySize,
  398. sharedMemorySize);
  399. bool isShaderCacheEnabled = _cacheManager != null;
  400. bool isShaderCacheReadOnly = false;
  401. Hash128 programCodeHash = default;
  402. GuestShaderCacheEntry[] shaderCacheEntries = null;
  403. // Current shader cache doesn't support bindless textures
  404. if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  405. {
  406. isShaderCacheEnabled = false;
  407. }
  408. if (isShaderCacheEnabled)
  409. {
  410. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  411. // Compute hash and prepare data for shader disk cache comparison.
  412. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(state.Channel.MemoryManager, shaderContexts);
  413. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  414. }
  415. ShaderBundle cpShader;
  416. // Search for the program hash in loaded shaders.
  417. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  418. {
  419. if (isShaderCacheEnabled)
  420. {
  421. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  422. }
  423. // The shader isn't currently cached, translate it and compile it.
  424. ShaderCodeHolder shader = TranslateShader(state.Channel.MemoryManager, shaderContexts[0]);
  425. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  426. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  427. hostProgram.CheckProgramLink(true);
  428. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  429. cpShader = new ShaderBundle(hostProgram, shader);
  430. if (isShaderCacheEnabled)
  431. {
  432. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  433. if (!isShaderCacheReadOnly)
  434. {
  435. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  436. }
  437. }
  438. }
  439. if (!isCached)
  440. {
  441. list = new List<ShaderBundle>();
  442. _cpPrograms.Add(gpuVa, list);
  443. }
  444. list.Add(cpShader);
  445. return cpShader;
  446. }
  447. /// <summary>
  448. /// Gets a graphics shader program from the shader cache.
  449. /// This includes all the specified shader stages.
  450. /// </summary>
  451. /// <remarks>
  452. /// This automatically translates, compiles and adds the code to the cache if not present.
  453. /// </remarks>
  454. /// <param name="state">Current GPU state</param>
  455. /// <param name="addresses">Addresses of the shaders for each stage</param>
  456. /// <returns>Compiled graphics shader code</returns>
  457. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  458. {
  459. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  460. if (isCached)
  461. {
  462. foreach (ShaderBundle cachedGpShaders in list)
  463. {
  464. if (IsShaderEqual(state.Channel.MemoryManager, cachedGpShaders, addresses))
  465. {
  466. return cachedGpShaders;
  467. }
  468. }
  469. }
  470. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  471. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  472. TranslationFlags flags = DefaultFlags;
  473. if (tfd != null)
  474. {
  475. flags |= TranslationFlags.Feedback;
  476. }
  477. TranslationCounts counts = new TranslationCounts();
  478. if (addresses.VertexA != 0)
  479. {
  480. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  481. }
  482. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  483. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  484. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  485. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  486. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  487. bool isShaderCacheEnabled = _cacheManager != null;
  488. bool isShaderCacheReadOnly = false;
  489. Hash128 programCodeHash = default;
  490. GuestShaderCacheEntry[] shaderCacheEntries = null;
  491. // Current shader cache doesn't support bindless textures
  492. for (int i = 0; i < shaderContexts.Length; i++)
  493. {
  494. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  495. {
  496. isShaderCacheEnabled = false;
  497. break;
  498. }
  499. }
  500. if (isShaderCacheEnabled)
  501. {
  502. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  503. // Compute hash and prepare data for shader disk cache comparison.
  504. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(state.Channel.MemoryManager, shaderContexts);
  505. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  506. }
  507. ShaderBundle gpShaders;
  508. // Search for the program hash in loaded shaders.
  509. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  510. {
  511. if (isShaderCacheEnabled)
  512. {
  513. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  514. }
  515. // The shader isn't currently cached, translate it and compile it.
  516. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  517. shaders[0] = TranslateShader(state.Channel.MemoryManager, shaderContexts[1], shaderContexts[0]);
  518. shaders[1] = TranslateShader(state.Channel.MemoryManager, shaderContexts[2]);
  519. shaders[2] = TranslateShader(state.Channel.MemoryManager, shaderContexts[3]);
  520. shaders[3] = TranslateShader(state.Channel.MemoryManager, shaderContexts[4]);
  521. shaders[4] = TranslateShader(state.Channel.MemoryManager, shaderContexts[5]);
  522. List<IShader> hostShaders = new List<IShader>();
  523. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  524. {
  525. ShaderProgram program = shaders[stage]?.Program;
  526. if (program == null)
  527. {
  528. continue;
  529. }
  530. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  531. shaders[stage].HostShader = hostShader;
  532. hostShaders.Add(hostShader);
  533. }
  534. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  535. hostProgram.CheckProgramLink(true);
  536. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  537. gpShaders = new ShaderBundle(hostProgram, shaders);
  538. if (isShaderCacheEnabled)
  539. {
  540. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  541. if (!isShaderCacheReadOnly)
  542. {
  543. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  544. }
  545. }
  546. }
  547. if (!isCached)
  548. {
  549. list = new List<ShaderBundle>();
  550. _gpPrograms.Add(addresses, list);
  551. }
  552. list.Add(gpShaders);
  553. return gpShaders;
  554. }
  555. /// <summary>
  556. /// Gets transform feedback state from the current GPU state.
  557. /// </summary>
  558. /// <param name="state">Current GPU state</param>
  559. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  560. private static TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  561. {
  562. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  563. if (!tfEnable)
  564. {
  565. return null;
  566. }
  567. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  568. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  569. {
  570. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  571. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  572. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  573. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  574. }
  575. return descs;
  576. }
  577. /// <summary>
  578. /// Checks if compute shader code in memory is equal to the cached shader.
  579. /// </summary>
  580. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  581. /// <param name="cpShader">Cached compute shader</param>
  582. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  583. /// <returns>True if the code is different, false otherwise</returns>
  584. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle cpShader, ulong gpuVa)
  585. {
  586. return IsShaderEqual(memoryManager, cpShader.Shaders[0], gpuVa);
  587. }
  588. /// <summary>
  589. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  590. /// </summary>
  591. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  592. /// <param name="gpShaders">Cached graphics shaders</param>
  593. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  594. /// <returns>True if the code is different, false otherwise</returns>
  595. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle gpShaders, ShaderAddresses addresses)
  596. {
  597. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  598. {
  599. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  600. ulong gpuVa = 0;
  601. switch (stage)
  602. {
  603. case 0: gpuVa = addresses.Vertex; break;
  604. case 1: gpuVa = addresses.TessControl; break;
  605. case 2: gpuVa = addresses.TessEvaluation; break;
  606. case 3: gpuVa = addresses.Geometry; break;
  607. case 4: gpuVa = addresses.Fragment; break;
  608. }
  609. if (!IsShaderEqual(memoryManager, shader, gpuVa, addresses.VertexA))
  610. {
  611. return false;
  612. }
  613. }
  614. return true;
  615. }
  616. /// <summary>
  617. /// Checks if the code of the specified cached shader is different from the code in memory.
  618. /// </summary>
  619. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  620. /// <param name="shader">Cached shader to compare with</param>
  621. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  622. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  623. /// <returns>True if the code is different, false otherwise</returns>
  624. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  625. {
  626. if (shader == null)
  627. {
  628. return true;
  629. }
  630. ReadOnlySpan<byte> memoryCode = memoryManager.GetSpan(gpuVa, shader.Code.Length);
  631. bool equals = memoryCode.SequenceEqual(shader.Code);
  632. if (equals && shader.Code2 != null)
  633. {
  634. memoryCode = memoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  635. equals = memoryCode.SequenceEqual(shader.Code2);
  636. }
  637. return equals;
  638. }
  639. /// <summary>
  640. /// Decode the binary Maxwell shader code to a translator context.
  641. /// </summary>
  642. /// <param name="state">Current GPU state</param>
  643. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  644. /// <param name="localSizeX">Local group size X of the computer shader</param>
  645. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  646. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  647. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  648. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  649. /// <returns>The generated translator context</returns>
  650. private TranslatorContext DecodeComputeShader(
  651. GpuState state,
  652. ulong gpuVa,
  653. int localSizeX,
  654. int localSizeY,
  655. int localSizeZ,
  656. int localMemorySize,
  657. int sharedMemorySize)
  658. {
  659. if (gpuVa == 0)
  660. {
  661. return null;
  662. }
  663. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  664. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  665. }
  666. /// <summary>
  667. /// Decode the binary Maxwell shader code to a translator context.
  668. /// </summary>
  669. /// <remarks>
  670. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  671. /// </remarks>
  672. /// <param name="state">Current GPU state</param>
  673. /// <param name="counts">Cumulative shader resource counts</param>
  674. /// <param name="flags">Flags that controls shader translation</param>
  675. /// <param name="stage">Shader stage</param>
  676. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  677. /// <returns>The generated translator context</returns>
  678. private TranslatorContext DecodeGraphicsShader(
  679. GpuState state,
  680. TranslationCounts counts,
  681. TranslationFlags flags,
  682. ShaderStage stage,
  683. ulong gpuVa)
  684. {
  685. if (gpuVa == 0)
  686. {
  687. return null;
  688. }
  689. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  690. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  691. }
  692. /// <summary>
  693. /// Translates a previously generated translator context to something that the host API accepts.
  694. /// </summary>
  695. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  696. /// <param name="translatorContext">Current translator context to translate</param>
  697. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  698. /// <returns>Compiled graphics shader code</returns>
  699. private ShaderCodeHolder TranslateShader(
  700. MemoryManager memoryManager,
  701. TranslatorContext translatorContext,
  702. TranslatorContext translatorContext2 = null)
  703. {
  704. if (translatorContext == null)
  705. {
  706. return null;
  707. }
  708. if (translatorContext2 != null)
  709. {
  710. byte[] codeA = memoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  711. byte[] codeB = memoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  712. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  713. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  714. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo, translatorContext2);
  715. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  716. {
  717. program.Prepend("// " + codePathB);
  718. program.Prepend("// " + fullPathB);
  719. program.Prepend("// " + codePathA);
  720. program.Prepend("// " + fullPathA);
  721. }
  722. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  723. }
  724. else
  725. {
  726. byte[] code = memoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  727. _dumper.Dump(code, translatorContext.Stage == ShaderStage.Compute, out string fullPath, out string codePath);
  728. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  729. if (fullPath != null && codePath != null)
  730. {
  731. program.Prepend("// " + codePath);
  732. program.Prepend("// " + fullPath);
  733. }
  734. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  735. }
  736. }
  737. /// <summary>
  738. /// Disposes the shader cache, deleting all the cached shaders.
  739. /// It's an error to use the shader cache after disposal.
  740. /// </summary>
  741. public void Dispose()
  742. {
  743. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  744. {
  745. foreach (ShaderBundle bundle in list)
  746. {
  747. bundle.Dispose();
  748. }
  749. }
  750. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  751. {
  752. foreach (ShaderBundle bundle in list)
  753. {
  754. bundle.Dispose();
  755. }
  756. }
  757. _cacheManager?.Dispose();
  758. }
  759. }
  760. }