ShaderCache.cs 34 KB

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