ShaderCache.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
  90. // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.
  91. while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
  92. {
  93. if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
  94. {
  95. // Begin a new shader compilation.
  96. Hash128 key = guestProgramList[programIndex];
  97. byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
  98. bool hasHostCache = hostProgramBinary != null;
  99. IProgram hostProgram = null;
  100. // If the program sources aren't in the cache, compile from saved guest program.
  101. byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);
  102. if (guestProgram == null)
  103. {
  104. Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");
  105. // Should not happen, but if someone messed with the cache it's better to catch it.
  106. invalidEntries?.Add(key);
  107. continue;
  108. }
  109. ReadOnlySpan<byte> guestProgramReadOnlySpan = guestProgram;
  110. ReadOnlySpan<GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);
  111. if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
  112. {
  113. Debug.Assert(cachedShaderEntries.Length == 1);
  114. GuestShaderCacheEntry entry = cachedShaderEntries[0];
  115. HostShaderCacheEntry[] hostShaderEntries = null;
  116. // Try loading host shader binary.
  117. if (hasHostCache)
  118. {
  119. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  120. hostProgramBinary = hostProgramBinarySpan.ToArray();
  121. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  122. }
  123. ShaderCompileTask task = new ShaderCompileTask();
  124. activeTasks.Add(task);
  125. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  126. {
  127. ShaderProgram program = null;
  128. ShaderProgramInfo shaderProgramInfo = null;
  129. Task compileTask = Task.Run(() =>
  130. {
  131. // Reconstruct code holder.
  132. if (isHostProgramValid)
  133. {
  134. program = new ShaderProgram(entry.Header.Stage, "");
  135. shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
  136. }
  137. else
  138. {
  139. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  140. program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
  141. }
  142. });
  143. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  144. {
  145. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  146. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  147. if (!isHostProgramValid)
  148. {
  149. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  150. // Compile shader and create program as the shader program binary got invalidated.
  151. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  152. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  153. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  154. {
  155. if (!isNewProgramValid)
  156. {
  157. return true;
  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. else
  179. {
  180. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  181. return true;
  182. }
  183. });
  184. return false; // Not finished: translating the shaders.
  185. });
  186. }
  187. else
  188. {
  189. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  190. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  191. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  192. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);
  193. TranslationFlags flags = DefaultFlags;
  194. if (tfd != null)
  195. {
  196. flags |= TranslationFlags.Feedback;
  197. }
  198. TranslationCounts counts = new TranslationCounts();
  199. HostShaderCacheEntry[] hostShaderEntries = null;
  200. // Try loading host shader binary.
  201. if (hasHostCache)
  202. {
  203. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  204. hostProgramBinary = hostProgramBinarySpan.ToArray();
  205. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  206. }
  207. ShaderCompileTask task = new ShaderCompileTask();
  208. activeTasks.Add(task);
  209. GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();
  210. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  211. {
  212. Task compileTask = Task.Run(() =>
  213. {
  214. // Reconstruct code holder.
  215. for (int i = 0; i < entries.Length; i++)
  216. {
  217. GuestShaderCacheEntry entry = entries[i];
  218. if (entry == null)
  219. {
  220. continue;
  221. }
  222. ShaderProgram program;
  223. if (entry.Header.SizeA != 0)
  224. {
  225. ShaderProgramInfo shaderProgramInfo;
  226. if (isHostProgramValid)
  227. {
  228. program = new ShaderProgram(entry.Header.Stage, "");
  229. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  230. }
  231. else
  232. {
  233. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  234. TranslatorContext translatorContext = Translator.CreateContext(0, gpuAccessor, flags, counts);
  235. TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, flags | TranslationFlags.VertexA, counts);
  236. program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
  237. }
  238. // NOTE: Vertex B comes first in the shader cache.
  239. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
  240. byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();
  241. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
  242. }
  243. else
  244. {
  245. ShaderProgramInfo shaderProgramInfo;
  246. if (isHostProgramValid)
  247. {
  248. program = new ShaderProgram(entry.Header.Stage, "");
  249. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  250. }
  251. else
  252. {
  253. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  254. program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
  255. }
  256. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  257. }
  258. shaderPrograms.Add(program);
  259. }
  260. });
  261. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  262. {
  263. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  264. if (!isHostProgramValid)
  265. {
  266. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  267. List<IShader> hostShaders = new List<IShader>();
  268. // Compile shaders and create program as the shader program binary got invalidated.
  269. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  270. {
  271. ShaderProgram program = shaders[stage]?.Program;
  272. if (program == null)
  273. {
  274. continue;
  275. }
  276. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  277. shaders[stage].HostShader = hostShader;
  278. hostShaders.Add(hostShader);
  279. }
  280. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  281. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  282. {
  283. if (!isNewProgramValid)
  284. {
  285. return true;
  286. }
  287. // As the host program was invalidated, save the new entry in the cache.
  288. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  289. if (!isReadOnly)
  290. {
  291. if (hasHostCache)
  292. {
  293. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  294. }
  295. else
  296. {
  297. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  298. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  299. }
  300. }
  301. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  302. return true;
  303. });
  304. return false; // Not finished: still need to compile the host program.
  305. }
  306. else
  307. {
  308. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  309. return true;
  310. }
  311. });
  312. return false; // Not finished: translating the shaders.
  313. });
  314. }
  315. _shaderCount = ++programIndex;
  316. }
  317. // Process the queue.
  318. for (int i = 0; i < activeTasks.Count; i++)
  319. {
  320. ShaderCompileTask task = activeTasks[i];
  321. if (task.IsDone())
  322. {
  323. activeTasks.RemoveAt(i--);
  324. }
  325. }
  326. if (activeTasks.Count == maxTaskCount)
  327. {
  328. Thread.Sleep(1);
  329. }
  330. }
  331. if (!isReadOnly)
  332. {
  333. // Remove entries that are broken in the cache
  334. _cacheManager.RemoveManifestEntries(invalidEntries);
  335. _cacheManager.FlushToArchive();
  336. _cacheManager.Synchronize();
  337. }
  338. progressReportEvent.Set();
  339. progressReportThread?.Join();
  340. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);
  341. Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
  342. }
  343. }
  344. /// <summary>
  345. /// Raises ShaderCacheStateChanged events periodically.
  346. /// </summary>
  347. private void ReportProgress(object state)
  348. {
  349. const int refreshRate = 50; // ms
  350. AutoResetEvent endEvent = (AutoResetEvent)state;
  351. int count = 0;
  352. do
  353. {
  354. int newCount = _shaderCount;
  355. if (count != newCount)
  356. {
  357. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loading, newCount, _totalShaderCount);
  358. count = newCount;
  359. }
  360. }
  361. while (!endEvent.WaitOne(refreshRate));
  362. }
  363. /// <summary>
  364. /// Gets a compute shader from the cache.
  365. /// </summary>
  366. /// <remarks>
  367. /// This automatically translates, compiles and adds the code to the cache if not present.
  368. /// </remarks>
  369. /// <param name="state">Current GPU state</param>
  370. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  371. /// <param name="localSizeX">Local group size X of the computer shader</param>
  372. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  373. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  374. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  375. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  376. /// <returns>Compiled compute shader code</returns>
  377. public ShaderBundle GetComputeShader(
  378. GpuState state,
  379. ulong gpuVa,
  380. int localSizeX,
  381. int localSizeY,
  382. int localSizeZ,
  383. int localMemorySize,
  384. int sharedMemorySize)
  385. {
  386. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  387. if (isCached)
  388. {
  389. foreach (ShaderBundle cachedCpShader in list)
  390. {
  391. if (IsShaderEqual(cachedCpShader, gpuVa))
  392. {
  393. return cachedCpShader;
  394. }
  395. }
  396. }
  397. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  398. shaderContexts[0] = DecodeComputeShader(
  399. state,
  400. gpuVa,
  401. localSizeX,
  402. localSizeY,
  403. localSizeZ,
  404. localMemorySize,
  405. sharedMemorySize);
  406. bool isShaderCacheEnabled = _cacheManager != null;
  407. bool isShaderCacheReadOnly = false;
  408. Hash128 programCodeHash = default;
  409. GuestShaderCacheEntry[] shaderCacheEntries = null;
  410. // Current shader cache doesn't support bindless textures
  411. if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  412. {
  413. isShaderCacheEnabled = false;
  414. }
  415. if (isShaderCacheEnabled)
  416. {
  417. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  418. // Compute hash and prepare data for shader disk cache comparison.
  419. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  420. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  421. }
  422. ShaderBundle cpShader;
  423. // Search for the program hash in loaded shaders.
  424. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  425. {
  426. if (isShaderCacheEnabled)
  427. {
  428. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  429. }
  430. // The shader isn't currently cached, translate it and compile it.
  431. ShaderCodeHolder shader = TranslateShader(shaderContexts[0]);
  432. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  433. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  434. hostProgram.CheckProgramLink(true);
  435. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  436. cpShader = new ShaderBundle(hostProgram, shader);
  437. if (isShaderCacheEnabled)
  438. {
  439. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  440. if (!isShaderCacheReadOnly)
  441. {
  442. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  443. }
  444. }
  445. }
  446. if (!isCached)
  447. {
  448. list = new List<ShaderBundle>();
  449. _cpPrograms.Add(gpuVa, list);
  450. }
  451. list.Add(cpShader);
  452. return cpShader;
  453. }
  454. /// <summary>
  455. /// Gets a graphics shader program from the shader cache.
  456. /// This includes all the specified shader stages.
  457. /// </summary>
  458. /// <remarks>
  459. /// This automatically translates, compiles and adds the code to the cache if not present.
  460. /// </remarks>
  461. /// <param name="state">Current GPU state</param>
  462. /// <param name="addresses">Addresses of the shaders for each stage</param>
  463. /// <returns>Compiled graphics shader code</returns>
  464. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  465. {
  466. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  467. if (isCached)
  468. {
  469. foreach (ShaderBundle cachedGpShaders in list)
  470. {
  471. if (IsShaderEqual(cachedGpShaders, addresses))
  472. {
  473. return cachedGpShaders;
  474. }
  475. }
  476. }
  477. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  478. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  479. TranslationFlags flags = DefaultFlags;
  480. if (tfd != null)
  481. {
  482. flags |= TranslationFlags.Feedback;
  483. }
  484. TranslationCounts counts = new TranslationCounts();
  485. if (addresses.VertexA != 0)
  486. {
  487. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  488. }
  489. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  490. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  491. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  492. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  493. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  494. bool isShaderCacheEnabled = _cacheManager != null;
  495. bool isShaderCacheReadOnly = false;
  496. Hash128 programCodeHash = default;
  497. GuestShaderCacheEntry[] shaderCacheEntries = null;
  498. // Current shader cache doesn't support bindless textures
  499. for (int i = 0; i < shaderContexts.Length; i++)
  500. {
  501. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  502. {
  503. isShaderCacheEnabled = false;
  504. break;
  505. }
  506. }
  507. if (isShaderCacheEnabled)
  508. {
  509. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  510. // Compute hash and prepare data for shader disk cache comparison.
  511. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  512. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  513. }
  514. ShaderBundle gpShaders;
  515. // Search for the program hash in loaded shaders.
  516. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  517. {
  518. if (isShaderCacheEnabled)
  519. {
  520. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  521. }
  522. // The shader isn't currently cached, translate it and compile it.
  523. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  524. shaders[0] = TranslateShader(shaderContexts[1], shaderContexts[0]);
  525. shaders[1] = TranslateShader(shaderContexts[2]);
  526. shaders[2] = TranslateShader(shaderContexts[3]);
  527. shaders[3] = TranslateShader(shaderContexts[4]);
  528. shaders[4] = TranslateShader(shaderContexts[5]);
  529. List<IShader> hostShaders = new List<IShader>();
  530. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  531. {
  532. ShaderProgram program = shaders[stage]?.Program;
  533. if (program == null)
  534. {
  535. continue;
  536. }
  537. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  538. shaders[stage].HostShader = hostShader;
  539. hostShaders.Add(hostShader);
  540. }
  541. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  542. hostProgram.CheckProgramLink(true);
  543. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  544. gpShaders = new ShaderBundle(hostProgram, shaders);
  545. if (isShaderCacheEnabled)
  546. {
  547. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  548. if (!isShaderCacheReadOnly)
  549. {
  550. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  551. }
  552. }
  553. }
  554. if (!isCached)
  555. {
  556. list = new List<ShaderBundle>();
  557. _gpPrograms.Add(addresses, list);
  558. }
  559. list.Add(gpShaders);
  560. return gpShaders;
  561. }
  562. /// <summary>
  563. /// Gets transform feedback state from the current GPU state.
  564. /// </summary>
  565. /// <param name="state">Current GPU state</param>
  566. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  567. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  568. {
  569. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  570. if (!tfEnable)
  571. {
  572. return null;
  573. }
  574. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  575. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  576. {
  577. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  578. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  579. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  580. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  581. }
  582. return descs;
  583. }
  584. /// <summary>
  585. /// Checks if compute shader code in memory is equal to the cached shader.
  586. /// </summary>
  587. /// <param name="cpShader">Cached compute shader</param>
  588. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  589. /// <returns>True if the code is different, false otherwise</returns>
  590. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  591. {
  592. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  593. }
  594. /// <summary>
  595. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  596. /// </summary>
  597. /// <param name="gpShaders">Cached graphics shaders</param>
  598. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  599. /// <returns>True if the code is different, false otherwise</returns>
  600. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  601. {
  602. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  603. {
  604. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  605. ulong gpuVa = 0;
  606. switch (stage)
  607. {
  608. case 0: gpuVa = addresses.Vertex; break;
  609. case 1: gpuVa = addresses.TessControl; break;
  610. case 2: gpuVa = addresses.TessEvaluation; break;
  611. case 3: gpuVa = addresses.Geometry; break;
  612. case 4: gpuVa = addresses.Fragment; break;
  613. }
  614. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  615. {
  616. return false;
  617. }
  618. }
  619. return true;
  620. }
  621. /// <summary>
  622. /// Checks if the code of the specified cached shader is different from the code in memory.
  623. /// </summary>
  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 bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  629. {
  630. if (shader == null)
  631. {
  632. return true;
  633. }
  634. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  635. bool equals = memoryCode.SequenceEqual(shader.Code);
  636. if (equals && shader.Code2 != null)
  637. {
  638. memoryCode = _context.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. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  669. }
  670. /// <summary>
  671. /// Decode the binary Maxwell shader code to a translator context.
  672. /// </summary>
  673. /// <remarks>
  674. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  675. /// </remarks>
  676. /// <param name="state">Current GPU state</param>
  677. /// <param name="counts">Cumulative shader resource counts</param>
  678. /// <param name="flags">Flags that controls shader translation</param>
  679. /// <param name="stage">Shader stage</param>
  680. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  681. /// <returns>The generated translator context</returns>
  682. private TranslatorContext DecodeGraphicsShader(
  683. GpuState state,
  684. TranslationCounts counts,
  685. TranslationFlags flags,
  686. ShaderStage stage,
  687. ulong gpuVa)
  688. {
  689. if (gpuVa == 0)
  690. {
  691. return null;
  692. }
  693. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  694. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  695. }
  696. /// <summary>
  697. /// Translates a previously generated translator context to something that the host API accepts.
  698. /// </summary>
  699. /// <param name="translatorContext">Current translator context to translate</param>
  700. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  701. /// <returns>Compiled graphics shader code</returns>
  702. private ShaderCodeHolder TranslateShader(TranslatorContext translatorContext, TranslatorContext translatorContext2 = null)
  703. {
  704. if (translatorContext == null)
  705. {
  706. return null;
  707. }
  708. if (translatorContext2 != null)
  709. {
  710. byte[] codeA = _context.MemoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  711. byte[] codeB = _context.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 = _context.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. }