ShaderCache.cs 36 KB

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