ShaderBinarySerializer.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Shader;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. namespace Ryujinx.Graphics.Gpu.Shader.DiskCache
  8. {
  9. static class ShaderBinarySerializer
  10. {
  11. public static byte[] Pack(ShaderSource[] sources)
  12. {
  13. using MemoryStream output = new MemoryStream();
  14. using BinaryWriter writer = new BinaryWriter(output);
  15. writer.Write(sources.Length);
  16. for (int i = 0; i < sources.Length; i++)
  17. {
  18. writer.Write((int)sources[i].Stage);
  19. writer.Write(sources[i].BinaryCode.Length);
  20. writer.Write(sources[i].BinaryCode);
  21. }
  22. return output.ToArray();
  23. }
  24. public static ShaderSource[] Unpack(CachedShaderStage[] stages, byte[] code)
  25. {
  26. using MemoryStream input = new MemoryStream(code);
  27. using BinaryReader reader = new BinaryReader(input);
  28. List<ShaderSource> output = new List<ShaderSource>();
  29. int count = reader.ReadInt32();
  30. for (int i = 0; i < count; i++)
  31. {
  32. ShaderStage stage = (ShaderStage)reader.ReadInt32();
  33. int binaryCodeLength = reader.ReadInt32();
  34. byte[] binaryCode = reader.ReadBytes(binaryCodeLength);
  35. output.Add(new ShaderSource(binaryCode, GetBindings(stages, stage), stage, TargetLanguage.Spirv));
  36. }
  37. return output.ToArray();
  38. }
  39. private static ShaderBindings GetBindings(CachedShaderStage[] stages, ShaderStage stage)
  40. {
  41. for (int i = 0; i < stages.Length; i++)
  42. {
  43. CachedShaderStage currentStage = stages[i];
  44. if (currentStage?.Info != null && currentStage.Info.Stage == stage)
  45. {
  46. return ShaderCache.GetBindings(currentStage.Info);
  47. }
  48. }
  49. return new ShaderBindings(Array.Empty<int>(), Array.Empty<int>(), Array.Empty<int>(), Array.Empty<int>());
  50. }
  51. }
  52. }