ShaderCache.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Engine.Threed;
  5. using Ryujinx.Graphics.Gpu.Engine.Types;
  6. using Ryujinx.Graphics.Gpu.Image;
  7. using Ryujinx.Graphics.Gpu.Memory;
  8. using Ryujinx.Graphics.Gpu.Shader.DiskCache;
  9. using Ryujinx.Graphics.Shader;
  10. using Ryujinx.Graphics.Shader.Translation;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. namespace Ryujinx.Graphics.Gpu.Shader
  17. {
  18. /// <summary>
  19. /// Memory cache of shader code.
  20. /// </summary>
  21. class ShaderCache : IDisposable
  22. {
  23. /// <summary>
  24. /// Default flags used on the shader translation process.
  25. /// </summary>
  26. public const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  27. private struct TranslatedShader
  28. {
  29. public readonly CachedShaderStage Shader;
  30. public readonly ShaderProgram Program;
  31. public TranslatedShader(CachedShaderStage shader, ShaderProgram program)
  32. {
  33. Shader = shader;
  34. Program = program;
  35. }
  36. }
  37. private struct TranslatedShaderVertexPair
  38. {
  39. public readonly CachedShaderStage VertexA;
  40. public readonly CachedShaderStage VertexB;
  41. public readonly ShaderProgram Program;
  42. public TranslatedShaderVertexPair(CachedShaderStage vertexA, CachedShaderStage vertexB, ShaderProgram program)
  43. {
  44. VertexA = vertexA;
  45. VertexB = vertexB;
  46. Program = program;
  47. }
  48. }
  49. private readonly GpuContext _context;
  50. private readonly ShaderDumper _dumper;
  51. private readonly Dictionary<ulong, CachedShaderProgram> _cpPrograms;
  52. private readonly Dictionary<ShaderAddresses, CachedShaderProgram> _gpPrograms;
  53. private struct ProgramToSave
  54. {
  55. public readonly CachedShaderProgram CachedProgram;
  56. public readonly IProgram HostProgram;
  57. public readonly byte[] BinaryCode;
  58. public ProgramToSave(CachedShaderProgram cachedProgram, IProgram hostProgram, byte[] binaryCode)
  59. {
  60. CachedProgram = cachedProgram;
  61. HostProgram = hostProgram;
  62. BinaryCode = binaryCode;
  63. }
  64. }
  65. private Queue<ProgramToSave> _programsToSaveQueue;
  66. private readonly ComputeShaderCacheHashTable _computeShaderCache;
  67. private readonly ShaderCacheHashTable _graphicsShaderCache;
  68. private readonly DiskCacheHostStorage _diskCacheHostStorage;
  69. private readonly BackgroundDiskCacheWriter _cacheWriter;
  70. /// <summary>
  71. /// Event for signalling shader cache loading progress.
  72. /// </summary>
  73. public event Action<ShaderCacheState, int, int> ShaderCacheStateChanged;
  74. /// <summary>
  75. /// Creates a new instance of the shader cache.
  76. /// </summary>
  77. /// <param name="context">GPU context that the shader cache belongs to</param>
  78. public ShaderCache(GpuContext context)
  79. {
  80. _context = context;
  81. _dumper = new ShaderDumper();
  82. _cpPrograms = new Dictionary<ulong, CachedShaderProgram>();
  83. _gpPrograms = new Dictionary<ShaderAddresses, CachedShaderProgram>();
  84. _programsToSaveQueue = new Queue<ProgramToSave>();
  85. string diskCacheTitleId = GetDiskCachePath();
  86. _computeShaderCache = new ComputeShaderCacheHashTable();
  87. _graphicsShaderCache = new ShaderCacheHashTable();
  88. _diskCacheHostStorage = new DiskCacheHostStorage(diskCacheTitleId);
  89. if (_diskCacheHostStorage.CacheEnabled)
  90. {
  91. _cacheWriter = new BackgroundDiskCacheWriter(context, _diskCacheHostStorage);
  92. }
  93. }
  94. /// <summary>
  95. /// Gets the path where the disk cache for the current application is stored.
  96. /// </summary>
  97. private static string GetDiskCachePath()
  98. {
  99. return GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null
  100. ? Path.Combine(AppDataManager.GamesDirPath, GraphicsConfig.TitleId, "cache", "shader")
  101. : null;
  102. }
  103. /// <summary>
  104. /// Processes the queue of shaders that must save their binaries to the disk cache.
  105. /// </summary>
  106. public void ProcessShaderCacheQueue()
  107. {
  108. // Check to see if the binaries for previously compiled shaders are ready, and save them out.
  109. while (_programsToSaveQueue.TryPeek(out ProgramToSave programToSave))
  110. {
  111. ProgramLinkStatus result = programToSave.HostProgram.CheckProgramLink(false);
  112. if (result != ProgramLinkStatus.Incomplete)
  113. {
  114. if (result == ProgramLinkStatus.Success)
  115. {
  116. _cacheWriter.AddShader(programToSave.CachedProgram, programToSave.BinaryCode ?? programToSave.HostProgram.GetBinary());
  117. }
  118. _programsToSaveQueue.Dequeue();
  119. }
  120. else
  121. {
  122. break;
  123. }
  124. }
  125. }
  126. /// <summary>
  127. /// Initialize the cache.
  128. /// </summary>
  129. /// <param name="cancellationToken">Cancellation token to cancel the shader cache initialization process</param>
  130. internal void Initialize(CancellationToken cancellationToken)
  131. {
  132. if (_diskCacheHostStorage.CacheEnabled)
  133. {
  134. ParallelDiskCacheLoader loader = new ParallelDiskCacheLoader(
  135. _context,
  136. _graphicsShaderCache,
  137. _computeShaderCache,
  138. _diskCacheHostStorage,
  139. cancellationToken,
  140. ShaderCacheStateUpdate);
  141. loader.LoadShaders();
  142. int errorCount = loader.ErrorCount;
  143. if (errorCount != 0)
  144. {
  145. Logger.Warning?.Print(LogClass.Gpu, $"Failed to load {errorCount} shaders from the disk cache.");
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Shader cache state update handler.
  151. /// </summary>
  152. /// <param name="state">Current state of the shader cache load process</param>
  153. /// <param name="current">Number of the current shader being processed</param>
  154. /// <param name="total">Total number of shaders to process</param>
  155. private void ShaderCacheStateUpdate(ShaderCacheState state, int current, int total)
  156. {
  157. ShaderCacheStateChanged?.Invoke(state, current, total);
  158. }
  159. /// <summary>
  160. /// Gets a compute shader from the cache.
  161. /// </summary>
  162. /// <remarks>
  163. /// This automatically translates, compiles and adds the code to the cache if not present.
  164. /// </remarks>
  165. /// <param name="channel">GPU channel</param>
  166. /// <param name="poolState">Texture pool state</param>
  167. /// <param name="computeState">Compute engine state</param>
  168. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  169. /// <returns>Compiled compute shader code</returns>
  170. public CachedShaderProgram GetComputeShader(
  171. GpuChannel channel,
  172. GpuChannelPoolState poolState,
  173. GpuChannelComputeState computeState,
  174. ulong gpuVa)
  175. {
  176. if (_cpPrograms.TryGetValue(gpuVa, out var cpShader) && IsShaderEqual(channel, poolState, cpShader, gpuVa))
  177. {
  178. return cpShader;
  179. }
  180. if (_computeShaderCache.TryFind(channel, poolState, gpuVa, out cpShader, out byte[] cachedGuestCode))
  181. {
  182. _cpPrograms[gpuVa] = cpShader;
  183. return cpShader;
  184. }
  185. ShaderSpecializationState specState = new ShaderSpecializationState(ref computeState);
  186. GpuAccessorState gpuAccessorState = new GpuAccessorState(poolState, computeState, default, specState);
  187. GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gpuAccessorState);
  188. TranslatorContext translatorContext = DecodeComputeShader(gpuAccessor, _context.Capabilities.Api, gpuVa);
  189. TranslatedShader translatedShader = TranslateShader(_dumper, channel, translatorContext, cachedGuestCode);
  190. ShaderSource[] shaderSourcesArray = new ShaderSource[] { CreateShaderSource(translatedShader.Program) };
  191. IProgram hostProgram = _context.Renderer.CreateProgram(shaderSourcesArray, new ShaderInfo(-1));
  192. cpShader = new CachedShaderProgram(hostProgram, specState, translatedShader.Shader);
  193. _computeShaderCache.Add(cpShader);
  194. EnqueueProgramToSave(cpShader, hostProgram, shaderSourcesArray);
  195. _cpPrograms[gpuVa] = cpShader;
  196. return cpShader;
  197. }
  198. /// <summary>
  199. /// Updates the shader pipeline state based on the current GPU state.
  200. /// </summary>
  201. /// <param name="state">Current GPU 3D engine state</param>
  202. /// <param name="pipeline">Shader pipeline state to be updated</param>
  203. /// <param name="graphicsState">Current graphics state</param>
  204. /// <param name="channel">Current GPU channel</param>
  205. private void UpdatePipelineInfo(
  206. ref ThreedClassState state,
  207. ref ProgramPipelineState pipeline,
  208. GpuChannelGraphicsState graphicsState,
  209. GpuChannel channel)
  210. {
  211. channel.TextureManager.UpdateRenderTargets();
  212. var rtControl = state.RtControl;
  213. var msaaMode = state.RtMsaaMode;
  214. pipeline.SamplesCount = msaaMode.SamplesInX() * msaaMode.SamplesInY();
  215. int count = rtControl.UnpackCount();
  216. for (int index = 0; index < Constants.TotalRenderTargets; index++)
  217. {
  218. int rtIndex = rtControl.UnpackPermutationIndex(index);
  219. var colorState = state.RtColorState[rtIndex];
  220. if (index >= count || colorState.Format == 0 || colorState.WidthOrStride == 0)
  221. {
  222. pipeline.AttachmentEnable[index] = false;
  223. pipeline.AttachmentFormats[index] = Format.R8G8B8A8Unorm;
  224. }
  225. else
  226. {
  227. pipeline.AttachmentEnable[index] = true;
  228. pipeline.AttachmentFormats[index] = colorState.Format.Convert().Format;
  229. }
  230. }
  231. pipeline.DepthStencilEnable = state.RtDepthStencilEnable;
  232. pipeline.DepthStencilFormat = pipeline.DepthStencilEnable ? state.RtDepthStencilState.Format.Convert().Format : Format.D24UnormS8Uint;
  233. pipeline.VertexBufferCount = Constants.TotalVertexBuffers;
  234. pipeline.Topology = graphicsState.Topology;
  235. }
  236. /// <summary>
  237. /// Gets a graphics shader program from the shader cache.
  238. /// This includes all the specified shader stages.
  239. /// </summary>
  240. /// <remarks>
  241. /// This automatically translates, compiles and adds the code to the cache if not present.
  242. /// </remarks>
  243. /// <param name="state">GPU state</param>
  244. /// <param name="pipeline">Pipeline state</param>
  245. /// <param name="channel">GPU channel</param>
  246. /// <param name="poolState">Texture pool state</param>
  247. /// <param name="graphicsState">3D engine state</param>
  248. /// <param name="addresses">Addresses of the shaders for each stage</param>
  249. /// <returns>Compiled graphics shader code</returns>
  250. public CachedShaderProgram GetGraphicsShader(
  251. ref ThreedClassState state,
  252. ref ProgramPipelineState pipeline,
  253. GpuChannel channel,
  254. GpuChannelPoolState poolState,
  255. GpuChannelGraphicsState graphicsState,
  256. ShaderAddresses addresses)
  257. {
  258. if (_gpPrograms.TryGetValue(addresses, out var gpShaders) && IsShaderEqual(channel, poolState, graphicsState, gpShaders, addresses))
  259. {
  260. return gpShaders;
  261. }
  262. if (_graphicsShaderCache.TryFind(channel, poolState, graphicsState, addresses, out gpShaders, out var cachedGuestCode))
  263. {
  264. _gpPrograms[addresses] = gpShaders;
  265. return gpShaders;
  266. }
  267. TransformFeedbackDescriptor[] transformFeedbackDescriptors = GetTransformFeedbackDescriptors(ref state);
  268. UpdatePipelineInfo(ref state, ref pipeline, graphicsState, channel);
  269. ShaderSpecializationState specState = new ShaderSpecializationState(ref graphicsState, ref pipeline, transformFeedbackDescriptors);
  270. GpuAccessorState gpuAccessorState = new GpuAccessorState(poolState, default, graphicsState, specState, transformFeedbackDescriptors);
  271. ReadOnlySpan<ulong> addressesSpan = addresses.AsSpan();
  272. TranslatorContext[] translatorContexts = new TranslatorContext[Constants.ShaderStages + 1];
  273. TranslatorContext nextStage = null;
  274. TargetApi api = _context.Capabilities.Api;
  275. for (int stageIndex = Constants.ShaderStages - 1; stageIndex >= 0; stageIndex--)
  276. {
  277. ulong gpuVa = addressesSpan[stageIndex + 1];
  278. if (gpuVa != 0)
  279. {
  280. GpuAccessor gpuAccessor = new GpuAccessor(_context, channel, gpuAccessorState, stageIndex);
  281. TranslatorContext currentStage = DecodeGraphicsShader(gpuAccessor, api, DefaultFlags, gpuVa);
  282. if (nextStage != null)
  283. {
  284. currentStage.SetNextStage(nextStage);
  285. }
  286. if (stageIndex == 0 && addresses.VertexA != 0)
  287. {
  288. translatorContexts[0] = DecodeGraphicsShader(gpuAccessor, api, DefaultFlags | TranslationFlags.VertexA, addresses.VertexA);
  289. }
  290. translatorContexts[stageIndex + 1] = currentStage;
  291. nextStage = currentStage;
  292. }
  293. }
  294. CachedShaderStage[] shaders = new CachedShaderStage[Constants.ShaderStages + 1];
  295. List<ShaderSource> shaderSources = new List<ShaderSource>();
  296. for (int stageIndex = 0; stageIndex < Constants.ShaderStages; stageIndex++)
  297. {
  298. TranslatorContext currentStage = translatorContexts[stageIndex + 1];
  299. if (currentStage != null)
  300. {
  301. ShaderProgram program;
  302. if (stageIndex == 0 && translatorContexts[0] != null)
  303. {
  304. TranslatedShaderVertexPair translatedShader = TranslateShader(
  305. _dumper,
  306. channel,
  307. currentStage,
  308. translatorContexts[0],
  309. cachedGuestCode.VertexACode,
  310. cachedGuestCode.VertexBCode);
  311. shaders[0] = translatedShader.VertexA;
  312. shaders[1] = translatedShader.VertexB;
  313. program = translatedShader.Program;
  314. }
  315. else
  316. {
  317. byte[] code = cachedGuestCode.GetByIndex(stageIndex);
  318. TranslatedShader translatedShader = TranslateShader(_dumper, channel, currentStage, code);
  319. shaders[stageIndex + 1] = translatedShader.Shader;
  320. program = translatedShader.Program;
  321. }
  322. if (program != null)
  323. {
  324. shaderSources.Add(CreateShaderSource(program));
  325. }
  326. }
  327. }
  328. ShaderSource[] shaderSourcesArray = shaderSources.ToArray();
  329. int fragmentOutputMap = shaders[5]?.Info.FragmentOutputMap ?? -1;
  330. IProgram hostProgram = _context.Renderer.CreateProgram(shaderSourcesArray, new ShaderInfo(fragmentOutputMap, pipeline));
  331. gpShaders = new CachedShaderProgram(hostProgram, specState, shaders);
  332. _graphicsShaderCache.Add(gpShaders);
  333. EnqueueProgramToSave(gpShaders, hostProgram, shaderSourcesArray);
  334. _gpPrograms[addresses] = gpShaders;
  335. return gpShaders;
  336. }
  337. /// <summary>
  338. /// Creates a shader source for use with the backend from a translated shader program.
  339. /// </summary>
  340. /// <param name="program">Translated shader program</param>
  341. /// <returns>Shader source</returns>
  342. public static ShaderSource CreateShaderSource(ShaderProgram program)
  343. {
  344. return new ShaderSource(program.Code, program.BinaryCode, GetBindings(program.Info), program.Info.Stage, program.Language);
  345. }
  346. /// <summary>
  347. /// Puts a program on the queue of programs to be saved on the disk cache.
  348. /// </summary>
  349. /// <remarks>
  350. /// This will not do anything if disk shader cache is disabled.
  351. /// </remarks>
  352. /// <param name="program">Cached shader program</param>
  353. /// <param name="hostProgram">Host program</param>
  354. /// <param name="sources">Source for each shader stage</param>
  355. private void EnqueueProgramToSave(CachedShaderProgram program, IProgram hostProgram, ShaderSource[] sources)
  356. {
  357. if (_diskCacheHostStorage.CacheEnabled)
  358. {
  359. byte[] binaryCode = _context.Capabilities.Api == TargetApi.Vulkan ? ShaderBinarySerializer.Pack(sources) : null;
  360. ProgramToSave programToSave = new ProgramToSave(program, hostProgram, binaryCode);
  361. _programsToSaveQueue.Enqueue(programToSave);
  362. }
  363. }
  364. /// <summary>
  365. /// Gets transform feedback state from the current GPU state.
  366. /// </summary>
  367. /// <param name="state">Current GPU state</param>
  368. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  369. private static TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(ref ThreedClassState state)
  370. {
  371. bool tfEnable = state.TfEnable;
  372. if (!tfEnable)
  373. {
  374. return null;
  375. }
  376. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  377. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  378. {
  379. var tf = state.TfState[i];
  380. descs[i] = new TransformFeedbackDescriptor(
  381. tf.BufferIndex,
  382. tf.Stride,
  383. tf.VaryingsCount,
  384. ref state.TfVaryingLocations[i]);
  385. }
  386. return descs;
  387. }
  388. /// <summary>
  389. /// Checks if compute shader code in memory is equal to the cached shader.
  390. /// </summary>
  391. /// <param name="channel">GPU channel using the shader</param>
  392. /// <param name="poolState">GPU channel state to verify shader compatibility</param>
  393. /// <param name="cpShader">Cached compute shader</param>
  394. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  395. /// <returns>True if the code is different, false otherwise</returns>
  396. private static bool IsShaderEqual(
  397. GpuChannel channel,
  398. GpuChannelPoolState poolState,
  399. CachedShaderProgram cpShader,
  400. ulong gpuVa)
  401. {
  402. if (IsShaderEqual(channel.MemoryManager, cpShader.Shaders[0], gpuVa))
  403. {
  404. return cpShader.SpecializationState.MatchesCompute(channel, poolState, true);
  405. }
  406. return false;
  407. }
  408. /// <summary>
  409. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  410. /// </summary>
  411. /// <param name="channel">GPU channel using the shader</param>
  412. /// <param name="poolState">GPU channel state to verify shader compatibility</param>
  413. /// <param name="graphicsState">GPU channel graphics state to verify shader compatibility</param>
  414. /// <param name="gpShaders">Cached graphics shaders</param>
  415. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  416. /// <returns>True if the code is different, false otherwise</returns>
  417. private static bool IsShaderEqual(
  418. GpuChannel channel,
  419. GpuChannelPoolState poolState,
  420. GpuChannelGraphicsState graphicsState,
  421. CachedShaderProgram gpShaders,
  422. ShaderAddresses addresses)
  423. {
  424. ReadOnlySpan<ulong> addressesSpan = addresses.AsSpan();
  425. for (int stageIndex = 0; stageIndex < gpShaders.Shaders.Length; stageIndex++)
  426. {
  427. CachedShaderStage shader = gpShaders.Shaders[stageIndex];
  428. ulong gpuVa = addressesSpan[stageIndex];
  429. if (!IsShaderEqual(channel.MemoryManager, shader, gpuVa))
  430. {
  431. return false;
  432. }
  433. }
  434. return gpShaders.SpecializationState.MatchesGraphics(channel, poolState, graphicsState, true);
  435. }
  436. /// <summary>
  437. /// Checks if the code of the specified cached shader is different from the code in memory.
  438. /// </summary>
  439. /// <param name="memoryManager">Memory manager used to access the GPU memory where the shader is located</param>
  440. /// <param name="shader">Cached shader to compare with</param>
  441. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  442. /// <returns>True if the code is different, false otherwise</returns>
  443. private static bool IsShaderEqual(MemoryManager memoryManager, CachedShaderStage shader, ulong gpuVa)
  444. {
  445. if (shader == null)
  446. {
  447. return true;
  448. }
  449. ReadOnlySpan<byte> memoryCode = memoryManager.GetSpan(gpuVa, shader.Code.Length);
  450. return memoryCode.SequenceEqual(shader.Code);
  451. }
  452. /// <summary>
  453. /// Decode the binary Maxwell shader code to a translator context.
  454. /// </summary>
  455. /// <param name="gpuAccessor">GPU state accessor</param>
  456. /// <param name="api">Graphics API that will be used with the shader</param>
  457. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  458. /// <returns>The generated translator context</returns>
  459. public static TranslatorContext DecodeComputeShader(IGpuAccessor gpuAccessor, TargetApi api, ulong gpuVa)
  460. {
  461. var options = CreateTranslationOptions(api, DefaultFlags | TranslationFlags.Compute);
  462. return Translator.CreateContext(gpuVa, gpuAccessor, options);
  463. }
  464. /// <summary>
  465. /// Decode the binary Maxwell shader code to a translator context.
  466. /// </summary>
  467. /// <remarks>
  468. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  469. /// </remarks>
  470. /// <param name="gpuAccessor">GPU state accessor</param>
  471. /// <param name="api">Graphics API that will be used with the shader</param>
  472. /// <param name="flags">Flags that controls shader translation</param>
  473. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  474. /// <returns>The generated translator context</returns>
  475. public static TranslatorContext DecodeGraphicsShader(IGpuAccessor gpuAccessor, TargetApi api, TranslationFlags flags, ulong gpuVa)
  476. {
  477. var options = CreateTranslationOptions(api, flags);
  478. return Translator.CreateContext(gpuVa, gpuAccessor, options);
  479. }
  480. /// <summary>
  481. /// Translates a previously generated translator context to something that the host API accepts.
  482. /// </summary>
  483. /// <param name="dumper">Optional shader code dumper</param>
  484. /// <param name="channel">GPU channel using the shader</param>
  485. /// <param name="currentStage">Translator context of the stage to be translated</param>
  486. /// <param name="vertexA">Optional translator context of the shader that should be combined</param>
  487. /// <param name="codeA">Optional Maxwell binary code of the Vertex A shader, if present</param>
  488. /// <param name="codeB">Optional Maxwell binary code of the Vertex B or current stage shader, if present on cache</param>
  489. /// <returns>Compiled graphics shader code</returns>
  490. private static TranslatedShaderVertexPair TranslateShader(
  491. ShaderDumper dumper,
  492. GpuChannel channel,
  493. TranslatorContext currentStage,
  494. TranslatorContext vertexA,
  495. byte[] codeA,
  496. byte[] codeB)
  497. {
  498. ulong cb1DataAddress = channel.BufferManager.GetGraphicsUniformBufferAddress(0, 1);
  499. var memoryManager = channel.MemoryManager;
  500. codeA ??= memoryManager.GetSpan(vertexA.Address, vertexA.Size).ToArray();
  501. codeB ??= memoryManager.GetSpan(currentStage.Address, currentStage.Size).ToArray();
  502. byte[] cb1DataA = memoryManager.Physical.GetSpan(cb1DataAddress, vertexA.Cb1DataSize).ToArray();
  503. byte[] cb1DataB = memoryManager.Physical.GetSpan(cb1DataAddress, currentStage.Cb1DataSize).ToArray();
  504. ShaderDumpPaths pathsA = default;
  505. ShaderDumpPaths pathsB = default;
  506. if (dumper != null)
  507. {
  508. pathsA = dumper.Dump(codeA, compute: false);
  509. pathsB = dumper.Dump(codeB, compute: false);
  510. }
  511. ShaderProgram program = currentStage.Translate(vertexA);
  512. pathsB.Prepend(program);
  513. pathsA.Prepend(program);
  514. CachedShaderStage vertexAStage = new CachedShaderStage(null, codeA, cb1DataA);
  515. CachedShaderStage vertexBStage = new CachedShaderStage(program.Info, codeB, cb1DataB);
  516. return new TranslatedShaderVertexPair(vertexAStage, vertexBStage, program);
  517. }
  518. /// <summary>
  519. /// Translates a previously generated translator context to something that the host API accepts.
  520. /// </summary>
  521. /// <param name="dumper">Optional shader code dumper</param>
  522. /// <param name="channel">GPU channel using the shader</param>
  523. /// <param name="context">Translator context of the stage to be translated</param>
  524. /// <param name="code">Optional Maxwell binary code of the current stage shader, if present on cache</param>
  525. /// <returns>Compiled graphics shader code</returns>
  526. private static TranslatedShader TranslateShader(ShaderDumper dumper, GpuChannel channel, TranslatorContext context, byte[] code)
  527. {
  528. var memoryManager = channel.MemoryManager;
  529. ulong cb1DataAddress = context.Stage == ShaderStage.Compute
  530. ? channel.BufferManager.GetComputeUniformBufferAddress(1)
  531. : channel.BufferManager.GetGraphicsUniformBufferAddress(StageToStageIndex(context.Stage), 1);
  532. byte[] cb1Data = memoryManager.Physical.GetSpan(cb1DataAddress, context.Cb1DataSize).ToArray();
  533. code ??= memoryManager.GetSpan(context.Address, context.Size).ToArray();
  534. ShaderDumpPaths paths = dumper?.Dump(code, context.Stage == ShaderStage.Compute) ?? default;
  535. ShaderProgram program = context.Translate();
  536. paths.Prepend(program);
  537. return new TranslatedShader(new CachedShaderStage(program.Info, code, cb1Data), program);
  538. }
  539. /// <summary>
  540. /// Gets the index of a stage from a <see cref="ShaderStage"/>.
  541. /// </summary>
  542. /// <param name="stage">Stage to get the index from</param>
  543. /// <returns>Stage index</returns>
  544. private static int StageToStageIndex(ShaderStage stage)
  545. {
  546. return stage switch
  547. {
  548. ShaderStage.TessellationControl => 1,
  549. ShaderStage.TessellationEvaluation => 2,
  550. ShaderStage.Geometry => 3,
  551. ShaderStage.Fragment => 4,
  552. _ => 0
  553. };
  554. }
  555. /// <summary>
  556. /// Gets information about the bindings used by a shader program.
  557. /// </summary>
  558. /// <param name="info">Shader program information to get the information from</param>
  559. /// <returns>Shader bindings</returns>
  560. public static ShaderBindings GetBindings(ShaderProgramInfo info)
  561. {
  562. var uniformBufferBindings = info.CBuffers.Select(x => x.Binding).ToArray();
  563. var storageBufferBindings = info.SBuffers.Select(x => x.Binding).ToArray();
  564. var textureBindings = info.Textures.Select(x => x.Binding).ToArray();
  565. var imageBindings = info.Images.Select(x => x.Binding).ToArray();
  566. return new ShaderBindings(
  567. uniformBufferBindings,
  568. storageBufferBindings,
  569. textureBindings,
  570. imageBindings);
  571. }
  572. /// <summary>
  573. /// Creates shader translation options with the requested graphics API and flags.
  574. /// The shader language is choosen based on the current configuration and graphics API.
  575. /// </summary>
  576. /// <param name="api">Target graphics API</param>
  577. /// <param name="flags">Translation flags</param>
  578. /// <returns>Translation options</returns>
  579. private static TranslationOptions CreateTranslationOptions(TargetApi api, TranslationFlags flags)
  580. {
  581. TargetLanguage lang = GraphicsConfig.EnableSpirvCompilationOnVulkan && api == TargetApi.Vulkan
  582. ? TargetLanguage.Spirv
  583. : TargetLanguage.Glsl;
  584. return new TranslationOptions(lang, api, flags);
  585. }
  586. /// <summary>
  587. /// Disposes the shader cache, deleting all the cached shaders.
  588. /// It's an error to use the shader cache after disposal.
  589. /// </summary>
  590. public void Dispose()
  591. {
  592. foreach (CachedShaderProgram program in _graphicsShaderCache.GetPrograms())
  593. {
  594. program.Dispose();
  595. }
  596. foreach (CachedShaderProgram program in _computeShaderCache.GetPrograms())
  597. {
  598. program.Dispose();
  599. }
  600. _cacheWriter?.Dispose();
  601. }
  602. }
  603. }