ShaderCache.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 = 2261;
  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. // Current shader cache doesn't support bindless textures
  335. if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  336. {
  337. isShaderCacheEnabled = false;
  338. }
  339. if (isShaderCacheEnabled)
  340. {
  341. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  342. // Compute hash and prepare data for shader disk cache comparison.
  343. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  344. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  345. }
  346. ShaderBundle cpShader;
  347. // Search for the program hash in loaded shaders.
  348. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  349. {
  350. if (isShaderCacheEnabled)
  351. {
  352. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  353. }
  354. // The shader isn't currently cached, translate it and compile it.
  355. ShaderCodeHolder shader = TranslateShader(shaderContexts[0]);
  356. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  357. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  358. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  359. cpShader = new ShaderBundle(hostProgram, shader);
  360. if (isShaderCacheEnabled)
  361. {
  362. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  363. if (!isShaderCacheReadOnly)
  364. {
  365. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  366. }
  367. }
  368. }
  369. if (!isCached)
  370. {
  371. list = new List<ShaderBundle>();
  372. _cpPrograms.Add(gpuVa, list);
  373. }
  374. list.Add(cpShader);
  375. return cpShader;
  376. }
  377. /// <summary>
  378. /// Gets a graphics shader program from the shader cache.
  379. /// This includes all the specified shader stages.
  380. /// </summary>
  381. /// <remarks>
  382. /// This automatically translates, compiles and adds the code to the cache if not present.
  383. /// </remarks>
  384. /// <param name="state">Current GPU state</param>
  385. /// <param name="addresses">Addresses of the shaders for each stage</param>
  386. /// <returns>Compiled graphics shader code</returns>
  387. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  388. {
  389. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  390. if (isCached)
  391. {
  392. foreach (ShaderBundle cachedGpShaders in list)
  393. {
  394. if (IsShaderEqual(cachedGpShaders, addresses))
  395. {
  396. return cachedGpShaders;
  397. }
  398. }
  399. }
  400. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  401. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  402. TranslationFlags flags = DefaultFlags;
  403. if (tfd != null)
  404. {
  405. flags |= TranslationFlags.Feedback;
  406. }
  407. TranslationCounts counts = new TranslationCounts();
  408. if (addresses.VertexA != 0)
  409. {
  410. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  411. }
  412. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  413. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  414. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  415. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  416. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  417. bool isShaderCacheEnabled = _cacheManager != null;
  418. bool isShaderCacheReadOnly = false;
  419. Hash128 programCodeHash = default;
  420. GuestShaderCacheEntry[] shaderCacheEntries = null;
  421. // Current shader cache doesn't support bindless textures
  422. for (int i = 0; i < shaderContexts.Length; i++)
  423. {
  424. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  425. {
  426. isShaderCacheEnabled = false;
  427. break;
  428. }
  429. }
  430. if (isShaderCacheEnabled)
  431. {
  432. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  433. // Compute hash and prepare data for shader disk cache comparison.
  434. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  435. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  436. }
  437. ShaderBundle gpShaders;
  438. // Search for the program hash in loaded shaders.
  439. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  440. {
  441. if (isShaderCacheEnabled)
  442. {
  443. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  444. }
  445. // The shader isn't currently cached, translate it and compile it.
  446. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  447. shaders[0] = TranslateShader(shaderContexts[1], shaderContexts[0]);
  448. shaders[1] = TranslateShader(shaderContexts[2]);
  449. shaders[2] = TranslateShader(shaderContexts[3]);
  450. shaders[3] = TranslateShader(shaderContexts[4]);
  451. shaders[4] = TranslateShader(shaderContexts[5]);
  452. List<IShader> hostShaders = new List<IShader>();
  453. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  454. {
  455. ShaderProgram program = shaders[stage]?.Program;
  456. if (program == null)
  457. {
  458. continue;
  459. }
  460. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  461. shaders[stage].HostShader = hostShader;
  462. hostShaders.Add(hostShader);
  463. }
  464. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  465. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  466. gpShaders = new ShaderBundle(hostProgram, shaders);
  467. if (isShaderCacheEnabled)
  468. {
  469. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  470. if (!isShaderCacheReadOnly)
  471. {
  472. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  473. }
  474. }
  475. }
  476. if (!isCached)
  477. {
  478. list = new List<ShaderBundle>();
  479. _gpPrograms.Add(addresses, list);
  480. }
  481. list.Add(gpShaders);
  482. return gpShaders;
  483. }
  484. /// <summary>
  485. /// Gets transform feedback state from the current GPU state.
  486. /// </summary>
  487. /// <param name="state">Current GPU state</param>
  488. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  489. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  490. {
  491. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  492. if (!tfEnable)
  493. {
  494. return null;
  495. }
  496. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  497. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  498. {
  499. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  500. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  501. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  502. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  503. }
  504. return descs;
  505. }
  506. /// <summary>
  507. /// Checks if compute shader code in memory is equal to the cached shader.
  508. /// </summary>
  509. /// <param name="cpShader">Cached compute shader</param>
  510. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  511. /// <returns>True if the code is different, false otherwise</returns>
  512. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  513. {
  514. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  515. }
  516. /// <summary>
  517. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  518. /// </summary>
  519. /// <param name="gpShaders">Cached graphics shaders</param>
  520. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  521. /// <returns>True if the code is different, false otherwise</returns>
  522. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  523. {
  524. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  525. {
  526. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  527. ulong gpuVa = 0;
  528. switch (stage)
  529. {
  530. case 0: gpuVa = addresses.Vertex; break;
  531. case 1: gpuVa = addresses.TessControl; break;
  532. case 2: gpuVa = addresses.TessEvaluation; break;
  533. case 3: gpuVa = addresses.Geometry; break;
  534. case 4: gpuVa = addresses.Fragment; break;
  535. }
  536. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  537. {
  538. return false;
  539. }
  540. }
  541. return true;
  542. }
  543. /// <summary>
  544. /// Checks if the code of the specified cached shader is different from the code in memory.
  545. /// </summary>
  546. /// <param name="shader">Cached shader to compare with</param>
  547. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  548. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  549. /// <returns>True if the code is different, false otherwise</returns>
  550. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  551. {
  552. if (shader == null)
  553. {
  554. return true;
  555. }
  556. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  557. bool equals = memoryCode.SequenceEqual(shader.Code);
  558. if (equals && shader.Code2 != null)
  559. {
  560. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  561. equals = memoryCode.SequenceEqual(shader.Code2);
  562. }
  563. return equals;
  564. }
  565. /// <summary>
  566. /// Decode the binary Maxwell shader code to a translator context.
  567. /// </summary>
  568. /// <param name="state">Current GPU state</param>
  569. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  570. /// <param name="localSizeX">Local group size X of the computer shader</param>
  571. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  572. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  573. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  574. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  575. /// <returns>The generated translator context</returns>
  576. private TranslatorContext DecodeComputeShader(
  577. GpuState state,
  578. ulong gpuVa,
  579. int localSizeX,
  580. int localSizeY,
  581. int localSizeZ,
  582. int localMemorySize,
  583. int sharedMemorySize)
  584. {
  585. if (gpuVa == 0)
  586. {
  587. return null;
  588. }
  589. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  590. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  591. }
  592. /// <summary>
  593. /// Decode the binary Maxwell shader code to a translator context.
  594. /// </summary>
  595. /// <remarks>
  596. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  597. /// </remarks>
  598. /// <param name="state">Current GPU state</param>
  599. /// <param name="counts">Cumulative shader resource counts</param>
  600. /// <param name="flags">Flags that controls shader translation</param>
  601. /// <param name="stage">Shader stage</param>
  602. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  603. /// <returns>The generated translator context</returns>
  604. private TranslatorContext DecodeGraphicsShader(
  605. GpuState state,
  606. TranslationCounts counts,
  607. TranslationFlags flags,
  608. ShaderStage stage,
  609. ulong gpuVa)
  610. {
  611. if (gpuVa == 0)
  612. {
  613. return null;
  614. }
  615. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  616. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  617. }
  618. /// <summary>
  619. /// Translates a previously generated translator context to something that the host API accepts.
  620. /// </summary>
  621. /// <param name="translatorContext">Current translator context to translate</param>
  622. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  623. /// <returns>Compiled graphics shader code</returns>
  624. private ShaderCodeHolder TranslateShader(TranslatorContext translatorContext, TranslatorContext translatorContext2 = null)
  625. {
  626. if (translatorContext == null)
  627. {
  628. return null;
  629. }
  630. if (translatorContext2 != null)
  631. {
  632. byte[] codeA = _context.MemoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  633. byte[] codeB = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  634. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  635. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  636. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo, translatorContext2);
  637. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  638. {
  639. program.Prepend("// " + codePathB);
  640. program.Prepend("// " + fullPathB);
  641. program.Prepend("// " + codePathA);
  642. program.Prepend("// " + fullPathA);
  643. }
  644. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  645. }
  646. else
  647. {
  648. byte[] code = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  649. _dumper.Dump(code, translatorContext.Stage == ShaderStage.Compute, out string fullPath, out string codePath);
  650. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  651. if (fullPath != null && codePath != null)
  652. {
  653. program.Prepend("// " + codePath);
  654. program.Prepend("// " + fullPath);
  655. }
  656. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  657. }
  658. }
  659. /// <summary>
  660. /// Disposes the shader cache, deleting all the cached shaders.
  661. /// It's an error to use the shader cache after disposal.
  662. /// </summary>
  663. public void Dispose()
  664. {
  665. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  666. {
  667. foreach (ShaderBundle bundle in list)
  668. {
  669. bundle.Dispose();
  670. }
  671. }
  672. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  673. {
  674. foreach (ShaderBundle bundle in list)
  675. {
  676. bundle.Dispose();
  677. }
  678. }
  679. _cacheManager?.Dispose();
  680. }
  681. }
  682. }