ShaderCache.cs 42 KB

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