ShaderCache.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, DefaultFlags | TranslationFlags.Compute);
  148. program = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
  149. });
  150. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  151. {
  152. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  153. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  154. // Compile shader and create program as the shader program binary got invalidated.
  155. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  156. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  157. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  158. {
  159. // As the host program was invalidated, save the new entry in the cache.
  160. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  161. if (!isReadOnly)
  162. {
  163. if (hasHostCache)
  164. {
  165. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  166. }
  167. else
  168. {
  169. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  170. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  171. }
  172. }
  173. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  174. return true;
  175. });
  176. return false; // Not finished: still need to compile the host program.
  177. });
  178. return false; // Not finished: translating the program.
  179. }
  180. });
  181. }
  182. else
  183. {
  184. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  185. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  186. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  187. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);
  188. TranslationFlags flags = DefaultFlags;
  189. if (tfd != null)
  190. {
  191. flags |= TranslationFlags.Feedback;
  192. }
  193. TranslationCounts counts = new TranslationCounts();
  194. HostShaderCacheEntry[] hostShaderEntries = null;
  195. // Try loading host shader binary.
  196. if (hasHostCache)
  197. {
  198. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  199. hostProgramBinary = hostProgramBinarySpan.ToArray();
  200. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  201. }
  202. ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
  203. activeTasks.Add(task);
  204. GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();
  205. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  206. {
  207. Task compileTask = Task.Run(() =>
  208. {
  209. // Reconstruct code holder.
  210. for (int i = 0; i < entries.Length; i++)
  211. {
  212. GuestShaderCacheEntry entry = entries[i];
  213. if (entry == null)
  214. {
  215. continue;
  216. }
  217. ShaderProgram program;
  218. if (entry.Header.SizeA != 0)
  219. {
  220. ShaderProgramInfo shaderProgramInfo;
  221. if (isHostProgramValid)
  222. {
  223. program = new ShaderProgram(entry.Header.Stage, "");
  224. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  225. }
  226. else
  227. {
  228. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  229. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags);
  230. var options2 = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags | TranslationFlags.VertexA);
  231. TranslatorContext translatorContext = Translator.CreateContext(0, gpuAccessor, options, counts);
  232. TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, options2, 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. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags);
  252. program = Translator.CreateContext(0, gpuAccessor, options, counts).Translate(out shaderProgramInfo);
  253. }
  254. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  255. }
  256. shaderPrograms.Add(program);
  257. }
  258. });
  259. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  260. {
  261. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  262. if (!isHostProgramValid)
  263. {
  264. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  265. List<IShader> hostShaders = new List<IShader>();
  266. // Compile shaders and create program as the shader program binary got invalidated.
  267. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  268. {
  269. ShaderProgram program = shaders[stage]?.Program;
  270. if (program == null)
  271. {
  272. continue;
  273. }
  274. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  275. shaders[stage].HostShader = hostShader;
  276. hostShaders.Add(hostShader);
  277. }
  278. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  279. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  280. {
  281. // As the host program was invalidated, save the new entry in the cache.
  282. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  283. if (!isReadOnly)
  284. {
  285. if (hasHostCache)
  286. {
  287. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  288. }
  289. else
  290. {
  291. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  292. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  293. }
  294. }
  295. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  296. return true;
  297. });
  298. return false; // Not finished: still need to compile the host program.
  299. }
  300. else
  301. {
  302. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  303. return true;
  304. }
  305. });
  306. return false; // Not finished: translating the program.
  307. });
  308. }
  309. _shaderCount = ++programIndex;
  310. }
  311. // Process the queue.
  312. for (int i = 0; i < activeTasks.Count; i++)
  313. {
  314. ShaderCompileTask task = activeTasks[i];
  315. if (task.IsDone())
  316. {
  317. activeTasks.RemoveAt(i--);
  318. }
  319. }
  320. if (activeTasks.Count == maxTaskCount)
  321. {
  322. // Wait for a task to be done, or for 1ms.
  323. // Host shader compilation cannot signal when it is done,
  324. // so the 1ms timeout is required to poll status.
  325. taskDoneEvent.WaitOne(1);
  326. }
  327. }
  328. if (!isReadOnly)
  329. {
  330. // Remove entries that are broken in the cache
  331. _cacheManager.RemoveManifestEntries(invalidEntries);
  332. _cacheManager.FlushToArchive();
  333. _cacheManager.Synchronize();
  334. }
  335. progressReportEvent.Set();
  336. progressReportThread?.Join();
  337. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);
  338. Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
  339. }
  340. }
  341. /// <summary>
  342. /// Raises ShaderCacheStateChanged events periodically.
  343. /// </summary>
  344. private void ReportProgress(object state)
  345. {
  346. const int refreshRate = 50; // ms
  347. AutoResetEvent endEvent = (AutoResetEvent)state;
  348. int count = 0;
  349. do
  350. {
  351. int newCount = _shaderCount;
  352. if (count != newCount)
  353. {
  354. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loading, newCount, _totalShaderCount);
  355. count = newCount;
  356. }
  357. }
  358. while (!endEvent.WaitOne(refreshRate));
  359. }
  360. /// <summary>
  361. /// Gets a compute shader from the cache.
  362. /// </summary>
  363. /// <remarks>
  364. /// This automatically translates, compiles and adds the code to the cache if not present.
  365. /// </remarks>
  366. /// <param name="state">Current GPU state</param>
  367. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  368. /// <param name="localSizeX">Local group size X of the computer shader</param>
  369. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  370. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  371. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  372. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  373. /// <returns>Compiled compute shader code</returns>
  374. public ShaderBundle GetComputeShader(
  375. GpuState state,
  376. ulong gpuVa,
  377. int localSizeX,
  378. int localSizeY,
  379. int localSizeZ,
  380. int localMemorySize,
  381. int sharedMemorySize)
  382. {
  383. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  384. if (isCached)
  385. {
  386. foreach (ShaderBundle cachedCpShader in list)
  387. {
  388. if (IsShaderEqual(state.Channel.MemoryManager, cachedCpShader, gpuVa))
  389. {
  390. return cachedCpShader;
  391. }
  392. }
  393. }
  394. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  395. shaderContexts[0] = DecodeComputeShader(
  396. state,
  397. gpuVa,
  398. localSizeX,
  399. localSizeY,
  400. localSizeZ,
  401. localMemorySize,
  402. sharedMemorySize);
  403. bool isShaderCacheEnabled = _cacheManager != null;
  404. bool isShaderCacheReadOnly = false;
  405. Hash128 programCodeHash = default;
  406. GuestShaderCacheEntry[] shaderCacheEntries = null;
  407. // Current shader cache doesn't support bindless textures
  408. if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  409. {
  410. isShaderCacheEnabled = false;
  411. }
  412. if (isShaderCacheEnabled)
  413. {
  414. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  415. // Compute hash and prepare data for shader disk cache comparison.
  416. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(state.Channel.MemoryManager, shaderContexts);
  417. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  418. }
  419. ShaderBundle cpShader;
  420. // Search for the program hash in loaded shaders.
  421. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  422. {
  423. if (isShaderCacheEnabled)
  424. {
  425. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  426. }
  427. // The shader isn't currently cached, translate it and compile it.
  428. ShaderCodeHolder shader = TranslateShader(state.Channel.MemoryManager, shaderContexts[0]);
  429. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  430. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  431. hostProgram.CheckProgramLink(true);
  432. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  433. cpShader = new ShaderBundle(hostProgram, shader);
  434. if (isShaderCacheEnabled)
  435. {
  436. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  437. if (!isShaderCacheReadOnly)
  438. {
  439. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  440. }
  441. }
  442. }
  443. if (!isCached)
  444. {
  445. list = new List<ShaderBundle>();
  446. _cpPrograms.Add(gpuVa, list);
  447. }
  448. list.Add(cpShader);
  449. return cpShader;
  450. }
  451. /// <summary>
  452. /// Gets a graphics shader program from the shader cache.
  453. /// This includes all the specified shader stages.
  454. /// </summary>
  455. /// <remarks>
  456. /// This automatically translates, compiles and adds the code to the cache if not present.
  457. /// </remarks>
  458. /// <param name="state">Current GPU state</param>
  459. /// <param name="addresses">Addresses of the shaders for each stage</param>
  460. /// <returns>Compiled graphics shader code</returns>
  461. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  462. {
  463. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  464. if (isCached)
  465. {
  466. foreach (ShaderBundle cachedGpShaders in list)
  467. {
  468. if (IsShaderEqual(state.Channel.MemoryManager, cachedGpShaders, addresses))
  469. {
  470. return cachedGpShaders;
  471. }
  472. }
  473. }
  474. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  475. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  476. TranslationFlags flags = DefaultFlags;
  477. if (tfd != null)
  478. {
  479. flags |= TranslationFlags.Feedback;
  480. }
  481. TranslationCounts counts = new TranslationCounts();
  482. if (addresses.VertexA != 0)
  483. {
  484. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  485. }
  486. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  487. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  488. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  489. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  490. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  491. bool isShaderCacheEnabled = _cacheManager != null;
  492. bool isShaderCacheReadOnly = false;
  493. Hash128 programCodeHash = default;
  494. GuestShaderCacheEntry[] shaderCacheEntries = null;
  495. // Current shader cache doesn't support bindless textures
  496. for (int i = 0; i < shaderContexts.Length; i++)
  497. {
  498. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  499. {
  500. isShaderCacheEnabled = false;
  501. break;
  502. }
  503. }
  504. if (isShaderCacheEnabled)
  505. {
  506. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  507. // Compute hash and prepare data for shader disk cache comparison.
  508. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(state.Channel.MemoryManager, shaderContexts);
  509. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  510. }
  511. ShaderBundle gpShaders;
  512. // Search for the program hash in loaded shaders.
  513. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  514. {
  515. if (isShaderCacheEnabled)
  516. {
  517. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  518. }
  519. // The shader isn't currently cached, translate it and compile it.
  520. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  521. shaders[0] = TranslateShader(state.Channel.MemoryManager, shaderContexts[1], shaderContexts[0]);
  522. shaders[1] = TranslateShader(state.Channel.MemoryManager, shaderContexts[2]);
  523. shaders[2] = TranslateShader(state.Channel.MemoryManager, shaderContexts[3]);
  524. shaders[3] = TranslateShader(state.Channel.MemoryManager, shaderContexts[4]);
  525. shaders[4] = TranslateShader(state.Channel.MemoryManager, shaderContexts[5]);
  526. List<IShader> hostShaders = new List<IShader>();
  527. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  528. {
  529. ShaderProgram program = shaders[stage]?.Program;
  530. if (program == null)
  531. {
  532. continue;
  533. }
  534. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  535. shaders[stage].HostShader = hostShader;
  536. hostShaders.Add(hostShader);
  537. }
  538. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  539. hostProgram.CheckProgramLink(true);
  540. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  541. gpShaders = new ShaderBundle(hostProgram, shaders);
  542. if (isShaderCacheEnabled)
  543. {
  544. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  545. if (!isShaderCacheReadOnly)
  546. {
  547. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  548. }
  549. }
  550. }
  551. if (!isCached)
  552. {
  553. list = new List<ShaderBundle>();
  554. _gpPrograms.Add(addresses, list);
  555. }
  556. list.Add(gpShaders);
  557. return gpShaders;
  558. }
  559. /// <summary>
  560. /// Gets transform feedback state from the current GPU state.
  561. /// </summary>
  562. /// <param name="state">Current GPU state</param>
  563. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  564. private static TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  565. {
  566. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  567. if (!tfEnable)
  568. {
  569. return null;
  570. }
  571. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  572. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  573. {
  574. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  575. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  576. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  577. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  578. }
  579. return descs;
  580. }
  581. /// <summary>
  582. /// Checks if compute shader code in memory is equal to the cached shader.
  583. /// </summary>
  584. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  585. /// <param name="cpShader">Cached compute shader</param>
  586. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  587. /// <returns>True if the code is different, false otherwise</returns>
  588. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle cpShader, ulong gpuVa)
  589. {
  590. return IsShaderEqual(memoryManager, cpShader.Shaders[0], gpuVa);
  591. }
  592. /// <summary>
  593. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  594. /// </summary>
  595. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  596. /// <param name="gpShaders">Cached graphics shaders</param>
  597. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  598. /// <returns>True if the code is different, false otherwise</returns>
  599. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle gpShaders, ShaderAddresses addresses)
  600. {
  601. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  602. {
  603. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  604. ulong gpuVa = 0;
  605. switch (stage)
  606. {
  607. case 0: gpuVa = addresses.Vertex; break;
  608. case 1: gpuVa = addresses.TessControl; break;
  609. case 2: gpuVa = addresses.TessEvaluation; break;
  610. case 3: gpuVa = addresses.Geometry; break;
  611. case 4: gpuVa = addresses.Fragment; break;
  612. }
  613. if (!IsShaderEqual(memoryManager, shader, gpuVa, addresses.VertexA))
  614. {
  615. return false;
  616. }
  617. }
  618. return true;
  619. }
  620. /// <summary>
  621. /// Checks if the code of the specified cached shader is different from the code in memory.
  622. /// </summary>
  623. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  624. /// <param name="shader">Cached shader to compare with</param>
  625. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  626. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  627. /// <returns>True if the code is different, false otherwise</returns>
  628. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  629. {
  630. if (shader == null)
  631. {
  632. return true;
  633. }
  634. ReadOnlySpan<byte> memoryCode = memoryManager.GetSpan(gpuVa, shader.Code.Length);
  635. bool equals = memoryCode.SequenceEqual(shader.Code);
  636. if (equals && shader.Code2 != null)
  637. {
  638. memoryCode = memoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  639. equals = memoryCode.SequenceEqual(shader.Code2);
  640. }
  641. return equals;
  642. }
  643. /// <summary>
  644. /// Decode the binary Maxwell shader code to a translator context.
  645. /// </summary>
  646. /// <param name="state">Current GPU state</param>
  647. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  648. /// <param name="localSizeX">Local group size X of the computer shader</param>
  649. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  650. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  651. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  652. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  653. /// <returns>The generated translator context</returns>
  654. private TranslatorContext DecodeComputeShader(
  655. GpuState state,
  656. ulong gpuVa,
  657. int localSizeX,
  658. int localSizeY,
  659. int localSizeZ,
  660. int localMemorySize,
  661. int sharedMemorySize)
  662. {
  663. if (gpuVa == 0)
  664. {
  665. return null;
  666. }
  667. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  668. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, DefaultFlags | TranslationFlags.Compute);
  669. return Translator.CreateContext(gpuVa, gpuAccessor, options);
  670. }
  671. /// <summary>
  672. /// Decode the binary Maxwell shader code to a translator context.
  673. /// </summary>
  674. /// <remarks>
  675. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  676. /// </remarks>
  677. /// <param name="state">Current GPU state</param>
  678. /// <param name="counts">Cumulative shader resource counts</param>
  679. /// <param name="flags">Flags that controls shader translation</param>
  680. /// <param name="stage">Shader stage</param>
  681. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  682. /// <returns>The generated translator context</returns>
  683. private TranslatorContext DecodeGraphicsShader(
  684. GpuState state,
  685. TranslationCounts counts,
  686. TranslationFlags flags,
  687. ShaderStage stage,
  688. ulong gpuVa)
  689. {
  690. if (gpuVa == 0)
  691. {
  692. return null;
  693. }
  694. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  695. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags);
  696. return Translator.CreateContext(gpuVa, gpuAccessor, options, counts);
  697. }
  698. /// <summary>
  699. /// Translates a previously generated translator context to something that the host API accepts.
  700. /// </summary>
  701. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  702. /// <param name="translatorContext">Current translator context to translate</param>
  703. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  704. /// <returns>Compiled graphics shader code</returns>
  705. private ShaderCodeHolder TranslateShader(
  706. MemoryManager memoryManager,
  707. TranslatorContext translatorContext,
  708. TranslatorContext translatorContext2 = null)
  709. {
  710. if (translatorContext == null)
  711. {
  712. return null;
  713. }
  714. if (translatorContext2 != null)
  715. {
  716. byte[] codeA = memoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  717. byte[] codeB = memoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  718. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  719. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  720. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo, translatorContext2);
  721. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  722. {
  723. program.Prepend("// " + codePathB);
  724. program.Prepend("// " + fullPathB);
  725. program.Prepend("// " + codePathA);
  726. program.Prepend("// " + fullPathA);
  727. }
  728. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  729. }
  730. else
  731. {
  732. byte[] code = memoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  733. _dumper.Dump(code, translatorContext.Stage == ShaderStage.Compute, out string fullPath, out string codePath);
  734. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  735. if (fullPath != null && codePath != null)
  736. {
  737. program.Prepend("// " + codePath);
  738. program.Prepend("// " + fullPath);
  739. }
  740. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  741. }
  742. }
  743. /// <summary>
  744. /// Disposes the shader cache, deleting all the cached shaders.
  745. /// It's an error to use the shader cache after disposal.
  746. /// </summary>
  747. public void Dispose()
  748. {
  749. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  750. {
  751. foreach (ShaderBundle bundle in list)
  752. {
  753. bundle.Dispose();
  754. }
  755. }
  756. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  757. {
  758. foreach (ShaderBundle bundle in list)
  759. {
  760. bundle.Dispose();
  761. }
  762. }
  763. _cacheManager?.Dispose();
  764. }
  765. }
  766. }