ShaderCache.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Engine.Threed;
  5. using Ryujinx.Graphics.Gpu.Memory;
  6. using Ryujinx.Graphics.Gpu.Shader.Cache;
  7. using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
  8. using Ryujinx.Graphics.Shader;
  9. using Ryujinx.Graphics.Shader.Translation;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.Runtime.InteropServices;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace Ryujinx.Graphics.Gpu.Shader
  17. {
  18. /// <summary>
  19. /// Memory cache of shader code.
  20. /// </summary>
  21. class ShaderCache : IDisposable
  22. {
  23. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  24. private readonly GpuContext _context;
  25. private readonly ShaderDumper _dumper;
  26. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  27. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  28. private CacheManager _cacheManager;
  29. private Dictionary<Hash128, ShaderBundle> _gpProgramsDiskCache;
  30. private Dictionary<Hash128, ShaderBundle> _cpProgramsDiskCache;
  31. /// <summary>
  32. /// Version of the codegen (to be changed when codegen or guest format change).
  33. /// </summary>
  34. private const ulong ShaderCodeGenVersion = 2542;
  35. // Progress reporting helpers
  36. private volatile int _shaderCount;
  37. private volatile int _totalShaderCount;
  38. public event Action<ShaderCacheState, int, int> ShaderCacheStateChanged;
  39. /// <summary>
  40. /// Creates a new instance of the shader cache.
  41. /// </summary>
  42. /// <param name="context">GPU context that the shader cache belongs to</param>
  43. public ShaderCache(GpuContext context)
  44. {
  45. _context = context;
  46. _dumper = new ShaderDumper();
  47. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  48. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  49. _gpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  50. _cpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  51. }
  52. /// <summary>
  53. /// Initialize the cache.
  54. /// </summary>
  55. internal void Initialize()
  56. {
  57. if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
  58. {
  59. _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);
  60. bool isReadOnly = _cacheManager.IsReadOnly;
  61. HashSet<Hash128> invalidEntries = null;
  62. if (isReadOnly)
  63. {
  64. Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
  65. }
  66. else
  67. {
  68. invalidEntries = new HashSet<Hash128>();
  69. }
  70. ReadOnlySpan<Hash128> guestProgramList = _cacheManager.GetGuestProgramList();
  71. using AutoResetEvent progressReportEvent = new AutoResetEvent(false);
  72. _shaderCount = 0;
  73. _totalShaderCount = guestProgramList.Length;
  74. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Start, _shaderCount, _totalShaderCount);
  75. Thread progressReportThread = null;
  76. if (guestProgramList.Length > 0)
  77. {
  78. progressReportThread = new Thread(ReportProgress)
  79. {
  80. Name = "ShaderCache.ProgressReporter",
  81. Priority = ThreadPriority.Lowest,
  82. IsBackground = true
  83. };
  84. progressReportThread.Start(progressReportEvent);
  85. }
  86. // Make sure these are initialized before doing compilation.
  87. Capabilities caps = _context.Capabilities;
  88. int maxTaskCount = Math.Min(Environment.ProcessorCount, 8);
  89. int programIndex = 0;
  90. List<ShaderCompileTask> activeTasks = new List<ShaderCompileTask>();
  91. using AutoResetEvent taskDoneEvent = new AutoResetEvent(false);
  92. // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
  93. // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.
  94. while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
  95. {
  96. if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
  97. {
  98. // Begin a new shader compilation.
  99. Hash128 key = guestProgramList[programIndex];
  100. byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
  101. bool hasHostCache = hostProgramBinary != null;
  102. IProgram hostProgram = null;
  103. // If the program sources aren't in the cache, compile from saved guest program.
  104. byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);
  105. if (guestProgram == null)
  106. {
  107. Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");
  108. // Should not happen, but if someone messed with the cache it's better to catch it.
  109. invalidEntries?.Add(key);
  110. _shaderCount = ++programIndex;
  111. continue;
  112. }
  113. ReadOnlySpan<byte> guestProgramReadOnlySpan = guestProgram;
  114. ReadOnlySpan<GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);
  115. if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
  116. {
  117. Debug.Assert(cachedShaderEntries.Length == 1);
  118. GuestShaderCacheEntry entry = cachedShaderEntries[0];
  119. HostShaderCacheEntry[] hostShaderEntries = null;
  120. // Try loading host shader binary.
  121. if (hasHostCache)
  122. {
  123. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  124. hostProgramBinary = hostProgramBinarySpan.ToArray();
  125. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  126. }
  127. ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
  128. activeTasks.Add(task);
  129. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  130. {
  131. ShaderProgram program = null;
  132. ShaderProgramInfo shaderProgramInfo = null;
  133. if (isHostProgramValid)
  134. {
  135. // Reconstruct code holder.
  136. program = new ShaderProgram(entry.Header.Stage, "");
  137. shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
  138. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size - entry.Header.Cb1DataSize).ToArray();
  139. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, code);
  140. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  141. return true;
  142. }
  143. else
  144. {
  145. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  146. Task compileTask = Task.Run(() =>
  147. {
  148. var binaryCode = new Memory<byte>(entry.Code);
  149. var gpuAccessor = new CachedGpuAccessor(
  150. _context,
  151. binaryCode,
  152. binaryCode.Slice(binaryCode.Length - entry.Header.Cb1DataSize),
  153. entry.Header.GpuAccessorHeader,
  154. entry.TextureDescriptors);
  155. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, DefaultFlags | TranslationFlags.Compute);
  156. program = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
  157. });
  158. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  159. {
  160. if (task.IsFaulted)
  161. {
  162. Logger.Warning?.Print(LogClass.Gpu, $"Host shader {key} is corrupted or incompatible, discarding...");
  163. _cacheManager.RemoveProgram(ref key);
  164. return true; // Exit early, the decoding step failed.
  165. }
  166. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size - entry.Header.Cb1DataSize).ToArray();
  167. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, code);
  168. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  169. // Compile shader and create program as the shader program binary got invalidated.
  170. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, program.Code);
  171. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  172. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  173. {
  174. // As the host program was invalidated, save the new entry in the cache.
  175. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  176. if (!isReadOnly)
  177. {
  178. if (hasHostCache)
  179. {
  180. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  181. }
  182. else
  183. {
  184. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  185. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  186. }
  187. }
  188. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  189. return true;
  190. });
  191. return false; // Not finished: still need to compile the host program.
  192. });
  193. return false; // Not finished: translating the program.
  194. }
  195. });
  196. }
  197. else
  198. {
  199. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  200. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  201. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  202. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);
  203. TranslationFlags flags = DefaultFlags;
  204. if (tfd != null)
  205. {
  206. flags |= TranslationFlags.Feedback;
  207. }
  208. TranslationCounts counts = new TranslationCounts();
  209. HostShaderCacheEntry[] hostShaderEntries = null;
  210. // Try loading host shader binary.
  211. if (hasHostCache)
  212. {
  213. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  214. hostProgramBinary = hostProgramBinarySpan.ToArray();
  215. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  216. }
  217. ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
  218. activeTasks.Add(task);
  219. GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();
  220. task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
  221. {
  222. Task compileTask = Task.Run(() =>
  223. {
  224. TranslatorContext[] shaderContexts = null;
  225. if (!isHostProgramValid)
  226. {
  227. shaderContexts = new TranslatorContext[1 + entries.Length];
  228. for (int i = 0; i < entries.Length; i++)
  229. {
  230. GuestShaderCacheEntry entry = entries[i];
  231. if (entry == null)
  232. {
  233. continue;
  234. }
  235. var binaryCode = new Memory<byte>(entry.Code);
  236. var gpuAccessor = new CachedGpuAccessor(
  237. _context,
  238. binaryCode,
  239. binaryCode.Slice(binaryCode.Length - entry.Header.Cb1DataSize),
  240. entry.Header.GpuAccessorHeader,
  241. entry.TextureDescriptors);
  242. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags);
  243. shaderContexts[i + 1] = Translator.CreateContext(0, gpuAccessor, options, counts);
  244. if (entry.Header.SizeA != 0)
  245. {
  246. var options2 = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags | TranslationFlags.VertexA);
  247. shaderContexts[0] = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, options2, counts);
  248. }
  249. }
  250. }
  251. // Reconstruct code holder.
  252. for (int i = 0; i < entries.Length; i++)
  253. {
  254. GuestShaderCacheEntry entry = entries[i];
  255. if (entry == null)
  256. {
  257. continue;
  258. }
  259. ShaderProgram program;
  260. ShaderProgramInfo shaderProgramInfo;
  261. if (isHostProgramValid)
  262. {
  263. program = new ShaderProgram(entry.Header.Stage, "");
  264. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  265. }
  266. else
  267. {
  268. int stageIndex = i + 1;
  269. TranslatorContext currentStage = shaderContexts[stageIndex];
  270. TranslatorContext nextStage = GetNextStageContext(shaderContexts, stageIndex);
  271. TranslatorContext vertexA = stageIndex == 1 ? shaderContexts[0] : null;
  272. program = currentStage.Translate(out shaderProgramInfo, nextStage, vertexA);
  273. }
  274. // NOTE: Vertex B comes first in the shader cache.
  275. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size - entry.Header.Cb1DataSize).ToArray();
  276. byte[] code2 = entry.Header.SizeA != 0 ? entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray() : null;
  277. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
  278. shaderPrograms.Add(program);
  279. }
  280. });
  281. task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
  282. {
  283. if (task.IsFaulted)
  284. {
  285. Logger.Warning?.Print(LogClass.Gpu, $"Host shader {key} is corrupted or incompatible, discarding...");
  286. _cacheManager.RemoveProgram(ref key);
  287. return true; // Exit early, the decoding step failed.
  288. }
  289. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  290. if (!isHostProgramValid)
  291. {
  292. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  293. List<IShader> hostShaders = new List<IShader>();
  294. // Compile shaders and create program as the shader program binary got invalidated.
  295. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  296. {
  297. ShaderProgram program = shaders[stage]?.Program;
  298. if (program == null)
  299. {
  300. continue;
  301. }
  302. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  303. shaders[stage].HostShader = hostShader;
  304. hostShaders.Add(hostShader);
  305. }
  306. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  307. task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
  308. {
  309. // As the host program was invalidated, save the new entry in the cache.
  310. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  311. if (!isReadOnly)
  312. {
  313. if (hasHostCache)
  314. {
  315. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  316. }
  317. else
  318. {
  319. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  320. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  321. }
  322. }
  323. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  324. return true;
  325. });
  326. return false; // Not finished: still need to compile the host program.
  327. }
  328. else
  329. {
  330. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  331. return true;
  332. }
  333. });
  334. return false; // Not finished: translating the program.
  335. });
  336. }
  337. _shaderCount = ++programIndex;
  338. }
  339. // Process the queue.
  340. for (int i = 0; i < activeTasks.Count; i++)
  341. {
  342. ShaderCompileTask task = activeTasks[i];
  343. if (task.IsDone())
  344. {
  345. activeTasks.RemoveAt(i--);
  346. }
  347. }
  348. if (activeTasks.Count == maxTaskCount)
  349. {
  350. // Wait for a task to be done, or for 1ms.
  351. // Host shader compilation cannot signal when it is done,
  352. // so the 1ms timeout is required to poll status.
  353. taskDoneEvent.WaitOne(1);
  354. }
  355. }
  356. if (!isReadOnly)
  357. {
  358. // Remove entries that are broken in the cache
  359. _cacheManager.RemoveManifestEntries(invalidEntries);
  360. _cacheManager.FlushToArchive();
  361. _cacheManager.Synchronize();
  362. }
  363. progressReportEvent.Set();
  364. progressReportThread?.Join();
  365. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);
  366. Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
  367. }
  368. }
  369. /// <summary>
  370. /// Raises ShaderCacheStateChanged events periodically.
  371. /// </summary>
  372. private void ReportProgress(object state)
  373. {
  374. const int refreshRate = 50; // ms
  375. AutoResetEvent endEvent = (AutoResetEvent)state;
  376. int count = 0;
  377. do
  378. {
  379. int newCount = _shaderCount;
  380. if (count != newCount)
  381. {
  382. ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loading, newCount, _totalShaderCount);
  383. count = newCount;
  384. }
  385. }
  386. while (!endEvent.WaitOne(refreshRate));
  387. }
  388. /// <summary>
  389. /// Gets a compute shader from the cache.
  390. /// </summary>
  391. /// <remarks>
  392. /// This automatically translates, compiles and adds the code to the cache if not present.
  393. /// </remarks>
  394. /// <param name="channel">GPU channel</param>
  395. /// <param name="gas">GPU accessor state</param>
  396. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  397. /// <param name="localSizeX">Local group size X of the computer shader</param>
  398. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  399. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  400. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  401. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  402. /// <returns>Compiled compute shader code</returns>
  403. public ShaderBundle GetComputeShader(
  404. GpuChannel channel,
  405. GpuAccessorState gas,
  406. ulong gpuVa,
  407. int localSizeX,
  408. int localSizeY,
  409. int localSizeZ,
  410. int localMemorySize,
  411. int sharedMemorySize)
  412. {
  413. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  414. if (isCached)
  415. {
  416. foreach (ShaderBundle cachedCpShader in list)
  417. {
  418. if (IsShaderEqual(channel.MemoryManager, cachedCpShader, gpuVa))
  419. {
  420. return cachedCpShader;
  421. }
  422. }
  423. }
  424. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  425. shaderContexts[0] = DecodeComputeShader(
  426. channel,
  427. gas,
  428. gpuVa,
  429. localSizeX,
  430. localSizeY,
  431. localSizeZ,
  432. localMemorySize,
  433. sharedMemorySize);
  434. bool isShaderCacheEnabled = _cacheManager != null;
  435. bool isShaderCacheReadOnly = false;
  436. Hash128 programCodeHash = default;
  437. GuestShaderCacheEntry[] shaderCacheEntries = null;
  438. // Current shader cache doesn't support bindless textures
  439. if (shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  440. {
  441. isShaderCacheEnabled = false;
  442. }
  443. if (isShaderCacheEnabled)
  444. {
  445. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  446. // Compute hash and prepare data for shader disk cache comparison.
  447. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(channel, shaderContexts);
  448. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  449. }
  450. ShaderBundle cpShader;
  451. // Search for the program hash in loaded shaders.
  452. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  453. {
  454. if (isShaderCacheEnabled)
  455. {
  456. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  457. }
  458. // The shader isn't currently cached, translate it and compile it.
  459. ShaderCodeHolder shader = TranslateShader(_dumper, channel.MemoryManager, shaderContexts[0], null, null);
  460. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  461. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  462. hostProgram.CheckProgramLink(true);
  463. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  464. cpShader = new ShaderBundle(hostProgram, shader);
  465. if (isShaderCacheEnabled)
  466. {
  467. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  468. if (!isShaderCacheReadOnly)
  469. {
  470. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  471. }
  472. }
  473. }
  474. if (!isCached)
  475. {
  476. list = new List<ShaderBundle>();
  477. _cpPrograms.Add(gpuVa, list);
  478. }
  479. list.Add(cpShader);
  480. return cpShader;
  481. }
  482. /// <summary>
  483. /// Gets a graphics shader program from the shader cache.
  484. /// This includes all the specified shader stages.
  485. /// </summary>
  486. /// <remarks>
  487. /// This automatically translates, compiles and adds the code to the cache if not present.
  488. /// </remarks>
  489. /// <param name="state">GPU state</param>
  490. /// <param name="channel">GPU channel</param>
  491. /// <param name="gas">GPU accessor state</param>
  492. /// <param name="addresses">Addresses of the shaders for each stage</param>
  493. /// <returns>Compiled graphics shader code</returns>
  494. public ShaderBundle GetGraphicsShader(ref ThreedClassState state, GpuChannel channel, GpuAccessorState gas, ShaderAddresses addresses)
  495. {
  496. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  497. if (isCached)
  498. {
  499. foreach (ShaderBundle cachedGpShaders in list)
  500. {
  501. if (IsShaderEqual(channel.MemoryManager, cachedGpShaders, addresses))
  502. {
  503. return cachedGpShaders;
  504. }
  505. }
  506. }
  507. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  508. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(ref state);
  509. TranslationFlags flags = DefaultFlags;
  510. if (tfd != null)
  511. {
  512. flags |= TranslationFlags.Feedback;
  513. }
  514. TranslationCounts counts = new TranslationCounts();
  515. if (addresses.VertexA != 0)
  516. {
  517. shaderContexts[0] = DecodeGraphicsShader(channel, gas, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  518. }
  519. shaderContexts[1] = DecodeGraphicsShader(channel, gas, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  520. shaderContexts[2] = DecodeGraphicsShader(channel, gas, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  521. shaderContexts[3] = DecodeGraphicsShader(channel, gas, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  522. shaderContexts[4] = DecodeGraphicsShader(channel, gas, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  523. shaderContexts[5] = DecodeGraphicsShader(channel, gas, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  524. bool isShaderCacheEnabled = _cacheManager != null;
  525. bool isShaderCacheReadOnly = false;
  526. Hash128 programCodeHash = default;
  527. GuestShaderCacheEntry[] shaderCacheEntries = null;
  528. // Current shader cache doesn't support bindless textures
  529. for (int i = 0; i < shaderContexts.Length; i++)
  530. {
  531. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  532. {
  533. isShaderCacheEnabled = false;
  534. break;
  535. }
  536. }
  537. if (isShaderCacheEnabled)
  538. {
  539. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  540. // Compute hash and prepare data for shader disk cache comparison.
  541. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(channel, shaderContexts);
  542. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  543. }
  544. ShaderBundle gpShaders;
  545. // Search for the program hash in loaded shaders.
  546. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  547. {
  548. if (isShaderCacheEnabled)
  549. {
  550. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  551. }
  552. // The shader isn't currently cached, translate it and compile it.
  553. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  554. for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++)
  555. {
  556. shaders[stageIndex] = TranslateShader(_dumper, channel.MemoryManager, shaderContexts, stageIndex + 1);
  557. }
  558. List<IShader> hostShaders = new List<IShader>();
  559. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  560. {
  561. ShaderProgram program = shaders[stage]?.Program;
  562. if (program == null)
  563. {
  564. continue;
  565. }
  566. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  567. shaders[stage].HostShader = hostShader;
  568. hostShaders.Add(hostShader);
  569. }
  570. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  571. hostProgram.CheckProgramLink(true);
  572. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  573. gpShaders = new ShaderBundle(hostProgram, shaders);
  574. if (isShaderCacheEnabled)
  575. {
  576. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  577. if (!isShaderCacheReadOnly)
  578. {
  579. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  580. }
  581. }
  582. }
  583. if (!isCached)
  584. {
  585. list = new List<ShaderBundle>();
  586. _gpPrograms.Add(addresses, list);
  587. }
  588. list.Add(gpShaders);
  589. return gpShaders;
  590. }
  591. /// <summary>
  592. /// Gets transform feedback state from the current GPU state.
  593. /// </summary>
  594. /// <param name="state">Current GPU state</param>
  595. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  596. private static TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(ref ThreedClassState state)
  597. {
  598. bool tfEnable = state.TfEnable;
  599. if (!tfEnable)
  600. {
  601. return null;
  602. }
  603. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  604. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  605. {
  606. var tf = state.TfState[i];
  607. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  608. var varyingLocations = MemoryMarshal.Cast<uint, byte>(state.TfVaryingLocations[i].ToSpan()).Slice(0, length);
  609. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations.ToArray());
  610. }
  611. return descs;
  612. }
  613. /// <summary>
  614. /// Checks if compute shader code in memory is equal to the cached shader.
  615. /// </summary>
  616. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  617. /// <param name="cpShader">Cached compute shader</param>
  618. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  619. /// <returns>True if the code is different, false otherwise</returns>
  620. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle cpShader, ulong gpuVa)
  621. {
  622. return IsShaderEqual(memoryManager, cpShader.Shaders[0], gpuVa);
  623. }
  624. /// <summary>
  625. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  626. /// </summary>
  627. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  628. /// <param name="gpShaders">Cached graphics shaders</param>
  629. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  630. /// <returns>True if the code is different, false otherwise</returns>
  631. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderBundle gpShaders, ShaderAddresses addresses)
  632. {
  633. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  634. {
  635. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  636. ulong gpuVa = 0;
  637. switch (stage)
  638. {
  639. case 0: gpuVa = addresses.Vertex; break;
  640. case 1: gpuVa = addresses.TessControl; break;
  641. case 2: gpuVa = addresses.TessEvaluation; break;
  642. case 3: gpuVa = addresses.Geometry; break;
  643. case 4: gpuVa = addresses.Fragment; break;
  644. }
  645. if (!IsShaderEqual(memoryManager, shader, gpuVa, addresses.VertexA))
  646. {
  647. return false;
  648. }
  649. }
  650. return true;
  651. }
  652. /// <summary>
  653. /// Checks if the code of the specified cached shader is different from the code in memory.
  654. /// </summary>
  655. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  656. /// <param name="shader">Cached shader to compare with</param>
  657. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  658. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  659. /// <returns>True if the code is different, false otherwise</returns>
  660. private static bool IsShaderEqual(MemoryManager memoryManager, ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  661. {
  662. if (shader == null)
  663. {
  664. return true;
  665. }
  666. ReadOnlySpan<byte> memoryCode = memoryManager.GetSpan(gpuVa, shader.Code.Length);
  667. bool equals = memoryCode.SequenceEqual(shader.Code);
  668. if (equals && shader.Code2 != null)
  669. {
  670. memoryCode = memoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  671. equals = memoryCode.SequenceEqual(shader.Code2);
  672. }
  673. return equals;
  674. }
  675. /// <summary>
  676. /// Decode the binary Maxwell shader code to a translator context.
  677. /// </summary>
  678. /// <param name="channel">GPU channel</param>
  679. /// <param name="gas">GPU accessor state</param>
  680. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  681. /// <param name="localSizeX">Local group size X of the computer shader</param>
  682. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  683. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  684. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  685. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  686. /// <returns>The generated translator context</returns>
  687. private TranslatorContext DecodeComputeShader(
  688. GpuChannel channel,
  689. GpuAccessorState gas,
  690. ulong gpuVa,
  691. int localSizeX,
  692. int localSizeY,
  693. int localSizeZ,
  694. int localMemorySize,
  695. int sharedMemorySize)
  696. {
  697. if (gpuVa == 0)
  698. {
  699. return null;
  700. }
  701. GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gas, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  702. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, DefaultFlags | TranslationFlags.Compute);
  703. return Translator.CreateContext(gpuVa, gpuAccessor, options);
  704. }
  705. /// <summary>
  706. /// Decode the binary Maxwell shader code to a translator context.
  707. /// </summary>
  708. /// <remarks>
  709. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  710. /// </remarks>
  711. /// <param name="channel">GPU channel</param>
  712. /// <param name="gas">GPU accessor state</param>
  713. /// <param name="counts">Cumulative shader resource counts</param>
  714. /// <param name="flags">Flags that controls shader translation</param>
  715. /// <param name="stage">Shader stage</param>
  716. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  717. /// <returns>The generated translator context</returns>
  718. private TranslatorContext DecodeGraphicsShader(
  719. GpuChannel channel,
  720. GpuAccessorState gas,
  721. TranslationCounts counts,
  722. TranslationFlags flags,
  723. ShaderStage stage,
  724. ulong gpuVa)
  725. {
  726. if (gpuVa == 0)
  727. {
  728. return null;
  729. }
  730. GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gas, (int)stage - 1);
  731. var options = new TranslationOptions(TargetLanguage.Glsl, TargetApi.OpenGL, flags);
  732. return Translator.CreateContext(gpuVa, gpuAccessor, options, counts);
  733. }
  734. /// <summary>
  735. /// Translates a previously generated translator context to something that the host API accepts.
  736. /// </summary>
  737. /// <param name="dumper">Optional shader code dumper</param>
  738. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  739. /// <param name="stages">Translator context of all available shader stages</param>
  740. /// <param name="stageIndex">Index on the stages array to translate</param>
  741. /// <returns>Compiled graphics shader code</returns>
  742. private static ShaderCodeHolder TranslateShader(
  743. ShaderDumper dumper,
  744. MemoryManager memoryManager,
  745. TranslatorContext[] stages,
  746. int stageIndex)
  747. {
  748. TranslatorContext currentStage = stages[stageIndex];
  749. TranslatorContext nextStage = GetNextStageContext(stages, stageIndex);
  750. TranslatorContext vertexA = stageIndex == 1 ? stages[0] : null;
  751. return TranslateShader(dumper, memoryManager, currentStage, nextStage, vertexA);
  752. }
  753. /// <summary>
  754. /// Gets the next shader stage context, from an array of contexts and index of the current stage.
  755. /// </summary>
  756. /// <param name="stages">Translator context of all available shader stages</param>
  757. /// <param name="stageIndex">Index on the stages array to translate</param>
  758. /// <returns>The translator context of the next stage, or null if inexistent</returns>
  759. private static TranslatorContext GetNextStageContext(TranslatorContext[] stages, int stageIndex)
  760. {
  761. for (int nextStageIndex = stageIndex + 1; nextStageIndex < stages.Length; nextStageIndex++)
  762. {
  763. if (stages[nextStageIndex] != null)
  764. {
  765. return stages[nextStageIndex];
  766. }
  767. }
  768. return null;
  769. }
  770. /// <summary>
  771. /// Translates a previously generated translator context to something that the host API accepts.
  772. /// </summary>
  773. /// <param name="dumper">Optional shader code dumper</param>
  774. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  775. /// <param name="currentStage">Translator context of the stage to be translated</param>
  776. /// <param name="nextStage">Translator context of the next active stage, if existent</param>
  777. /// <param name="vertexA">Optional translator context of the shader that should be combined</param>
  778. /// <returns>Compiled graphics shader code</returns>
  779. private static ShaderCodeHolder TranslateShader(
  780. ShaderDumper dumper,
  781. MemoryManager memoryManager,
  782. TranslatorContext currentStage,
  783. TranslatorContext nextStage,
  784. TranslatorContext vertexA)
  785. {
  786. if (currentStage == null)
  787. {
  788. return null;
  789. }
  790. if (vertexA != null)
  791. {
  792. byte[] codeA = memoryManager.GetSpan(vertexA.Address, vertexA.Size).ToArray();
  793. byte[] codeB = memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray();
  794. ShaderDumpPaths pathsA = default;
  795. ShaderDumpPaths pathsB = default;
  796. if (dumper != null)
  797. {
  798. pathsA = dumper.Dump(codeA, compute: false);
  799. pathsB = dumper.Dump(codeB, compute: false);
  800. }
  801. ShaderProgram program = currentStage.Translate(out ShaderProgramInfo shaderProgramInfo, nextStage, vertexA);
  802. pathsB.Prepend(program);
  803. pathsA.Prepend(program);
  804. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  805. }
  806. else
  807. {
  808. byte[] code = memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray();
  809. ShaderDumpPaths paths = dumper?.Dump(code, currentStage.Stage == ShaderStage.Compute) ?? default;
  810. ShaderProgram program = currentStage.Translate(out ShaderProgramInfo shaderProgramInfo, nextStage);
  811. paths.Prepend(program);
  812. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  813. }
  814. }
  815. /// <summary>
  816. /// Disposes the shader cache, deleting all the cached shaders.
  817. /// It's an error to use the shader cache after disposal.
  818. /// </summary>
  819. public void Dispose()
  820. {
  821. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  822. {
  823. foreach (ShaderBundle bundle in list)
  824. {
  825. bundle.Dispose();
  826. }
  827. }
  828. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  829. {
  830. foreach (ShaderBundle bundle in list)
  831. {
  832. bundle.Dispose();
  833. }
  834. }
  835. _cacheManager?.Dispose();
  836. }
  837. }
  838. }