SpirvCompilation.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. using System;
  2. using System.Text;
  3. namespace Veldrid.SPIRV
  4. {
  5. /// <summary>
  6. /// Static functions for cross-compiling SPIR-V bytecode to various shader languages, and for compiling GLSL to SPIR-V.
  7. /// </summary>
  8. public static class SpirvCompilation
  9. {
  10. /// <summary>
  11. /// Cross-compiles the given vertex-fragment pair into some target language.
  12. /// </summary>
  13. /// <param name="vsBytes">The vertex shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  14. /// <param name="fsBytes">The fragment shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  15. /// <param name="target">The target language.</param>
  16. /// <returns>A <see cref="VertexFragmentCompilationResult"/> containing the compiled output.</returns>
  17. public static unsafe VertexFragmentCompilationResult CompileVertexFragment(
  18. byte[] vsBytes,
  19. byte[] fsBytes,
  20. CrossCompileTarget target) => CompileVertexFragment(vsBytes, fsBytes, target, new CrossCompileOptions());
  21. /// <summary>
  22. /// Cross-compiles the given vertex-fragment pair into some target language.
  23. /// </summary>
  24. /// <param name="vsBytes">The vertex shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  25. /// <param name="fsBytes">The fragment shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  26. /// <param name="target">The target language.</param>
  27. /// <param name="options">The options for shader translation.</param>
  28. /// <returns>A <see cref="VertexFragmentCompilationResult"/> containing the compiled output.</returns>
  29. public static unsafe VertexFragmentCompilationResult CompileVertexFragment(
  30. byte[] vsBytes,
  31. byte[] fsBytes,
  32. CrossCompileTarget target,
  33. CrossCompileOptions options)
  34. {
  35. int size1 = sizeof(CrossCompileInfo);
  36. int size2 = sizeof(InteropArray);
  37. byte[] vsSpirvBytes;
  38. byte[] fsSpirvBytes;
  39. if (Util.HasSpirvHeader(vsBytes))
  40. {
  41. vsSpirvBytes = vsBytes;
  42. }
  43. else
  44. {
  45. fixed (byte* sourceTextPtr = vsBytes)
  46. {
  47. SpirvCompilationResult vsCompileResult = CompileGlslToSpirv(
  48. (uint)vsBytes.Length,
  49. sourceTextPtr,
  50. string.Empty,
  51. ShaderStages.Vertex,
  52. target == CrossCompileTarget.GLSL || target == CrossCompileTarget.ESSL,
  53. 0,
  54. null);
  55. vsSpirvBytes = vsCompileResult.SpirvBytes;
  56. }
  57. }
  58. if (Util.HasSpirvHeader(fsBytes))
  59. {
  60. fsSpirvBytes = fsBytes;
  61. }
  62. else
  63. {
  64. fixed (byte* sourceTextPtr = fsBytes)
  65. {
  66. SpirvCompilationResult fsCompileResult = CompileGlslToSpirv(
  67. (uint)fsBytes.Length,
  68. sourceTextPtr,
  69. string.Empty,
  70. ShaderStages.Fragment,
  71. target == CrossCompileTarget.GLSL || target == CrossCompileTarget.ESSL,
  72. 0,
  73. null);
  74. fsSpirvBytes = fsCompileResult.SpirvBytes;
  75. }
  76. }
  77. int specConstantsCount = options.Specializations.Length;
  78. NativeSpecializationConstant* nativeSpecConstants = stackalloc NativeSpecializationConstant[specConstantsCount];
  79. for (int i = 0; i < specConstantsCount; i++)
  80. {
  81. nativeSpecConstants[i].ID = options.Specializations[i].ID;
  82. nativeSpecConstants[i].Constant = options.Specializations[i].Data;
  83. }
  84. CrossCompileInfo info;
  85. info.Target = target;
  86. info.FixClipSpaceZ = options.FixClipSpaceZ;
  87. info.InvertY = options.InvertVertexOutputY;
  88. info.NormalizeResourceNames = options.NormalizeResourceNames;
  89. fixed (byte* vsBytesPtr = vsSpirvBytes)
  90. fixed (byte* fsBytesPtr = fsSpirvBytes)
  91. {
  92. info.VertexShader = new InteropArray((uint)vsSpirvBytes.Length / 4, vsBytesPtr);
  93. info.FragmentShader = new InteropArray((uint)fsSpirvBytes.Length / 4, fsBytesPtr);
  94. info.Specializations = new InteropArray((uint)specConstantsCount, nativeSpecConstants);
  95. CompilationResult* result = null;
  96. try
  97. {
  98. result = VeldridSpirvNative.Default.CrossCompile(&info);
  99. if (!result->Succeeded)
  100. {
  101. throw new SpirvCompilationException(
  102. "Compilation failed: " + Util.GetString((byte*)result->GetData(0), result->GetLength(0)));
  103. }
  104. string vsCode = Util.GetString((byte*)result->GetData(0), result->GetLength(0));
  105. string fsCode = Util.GetString((byte*)result->GetData(1), result->GetLength(1));
  106. ReflectionInfo* reflInfo = &result->ReflectionInfo;
  107. VertexElementDescription[] vertexElements = new VertexElementDescription[reflInfo->VertexElements.Count];
  108. for (uint i = 0; i < reflInfo->VertexElements.Count; i++)
  109. {
  110. ref NativeVertexElementDescription nativeDesc
  111. = ref reflInfo->VertexElements.Ref<NativeVertexElementDescription>(i);
  112. vertexElements[i] = new VertexElementDescription(
  113. Util.GetString((byte*)nativeDesc.Name.Data, nativeDesc.Name.Count),
  114. nativeDesc.Semantic,
  115. nativeDesc.Format,
  116. nativeDesc.Offset);
  117. }
  118. ResourceLayoutDescription[] layouts = new ResourceLayoutDescription[reflInfo->ResourceLayouts.Count];
  119. for (uint i = 0; i < reflInfo->ResourceLayouts.Count; i++)
  120. {
  121. ref NativeResourceLayoutDescription nativeDesc =
  122. ref reflInfo->ResourceLayouts.Ref<NativeResourceLayoutDescription>(i);
  123. layouts[i].Elements = new ResourceLayoutElementDescription[nativeDesc.ResourceElements.Count];
  124. for (uint j = 0; j < nativeDesc.ResourceElements.Count; j++)
  125. {
  126. ref NativeResourceElementDescription elemDesc =
  127. ref nativeDesc.ResourceElements.Ref<NativeResourceElementDescription>(j);
  128. layouts[i].Elements[j] = new ResourceLayoutElementDescription(
  129. Util.GetString((byte*)elemDesc.Name.Data, elemDesc.Name.Count),
  130. elemDesc.Kind,
  131. elemDesc.Stages,
  132. elemDesc.Options);
  133. }
  134. }
  135. SpirvReflection reflection = new SpirvReflection(
  136. vertexElements,
  137. layouts);
  138. return new VertexFragmentCompilationResult(vsCode, fsCode, reflection);
  139. }
  140. finally
  141. {
  142. if (result != null)
  143. {
  144. VeldridSpirvNative.Default.FreeResult(result);
  145. }
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// Cross-compiles the given vertex-fragment pair into some target language.
  151. /// </summary>
  152. /// <param name="csBytes">The compute shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  153. /// <param name="target">The target language.</param>
  154. /// <returns>A <see cref="ComputeCompilationResult"/> containing the compiled output.</returns>
  155. public static unsafe ComputeCompilationResult CompileCompute(
  156. byte[] csBytes,
  157. CrossCompileTarget target) => CompileCompute(csBytes, target, new CrossCompileOptions());
  158. /// <summary>
  159. /// Cross-compiles the given vertex-fragment pair into some target language.
  160. /// </summary>
  161. /// <param name="csBytes">The compute shader's SPIR-V bytecode or ASCII-encoded GLSL source code.</param>
  162. /// <param name="target">The target language.</param>
  163. /// <param name="options">The options for shader translation.</param>
  164. /// <returns>A <see cref="ComputeCompilationResult"/> containing the compiled output.</returns>
  165. public static unsafe ComputeCompilationResult CompileCompute(
  166. byte[] csBytes,
  167. CrossCompileTarget target,
  168. CrossCompileOptions options)
  169. {
  170. byte[] csSpirvBytes;
  171. if (Util.HasSpirvHeader(csBytes))
  172. {
  173. csSpirvBytes = csBytes;
  174. }
  175. else
  176. {
  177. fixed (byte* sourceTextPtr = csBytes)
  178. {
  179. SpirvCompilationResult vsCompileResult = CompileGlslToSpirv(
  180. (uint)csBytes.Length,
  181. sourceTextPtr,
  182. string.Empty,
  183. ShaderStages.Compute,
  184. target == CrossCompileTarget.GLSL || target == CrossCompileTarget.ESSL,
  185. 0,
  186. null);
  187. csSpirvBytes = vsCompileResult.SpirvBytes;
  188. }
  189. }
  190. CrossCompileInfo info;
  191. info.Target = target;
  192. info.FixClipSpaceZ = options.FixClipSpaceZ;
  193. info.InvertY = options.InvertVertexOutputY;
  194. info.NormalizeResourceNames = options.NormalizeResourceNames;
  195. fixed (byte* csBytesPtr = csSpirvBytes)
  196. fixed (SpecializationConstant* specConstants = options.Specializations)
  197. {
  198. info.ComputeShader = new InteropArray((uint)csSpirvBytes.Length / 4, csBytesPtr);
  199. info.Specializations = new InteropArray((uint)options.Specializations.Length, specConstants);
  200. CompilationResult* result = null;
  201. try
  202. {
  203. result = VeldridSpirvNative.Default.CrossCompile(&info);
  204. if (!result->Succeeded)
  205. {
  206. throw new SpirvCompilationException(
  207. "Compilation failed: " + Util.GetString((byte*)result->GetData(0), result->GetLength(0)));
  208. }
  209. string csCode = Util.GetString((byte*)result->GetData(0), result->GetLength(0));
  210. ReflectionInfo* reflInfo = &result->ReflectionInfo;
  211. ResourceLayoutDescription[] layouts = new ResourceLayoutDescription[reflInfo->ResourceLayouts.Count];
  212. for (uint i = 0; i < reflInfo->ResourceLayouts.Count; i++)
  213. {
  214. ref NativeResourceLayoutDescription nativeDesc =
  215. ref reflInfo->ResourceLayouts.Ref<NativeResourceLayoutDescription>(i);
  216. layouts[i].Elements = new ResourceLayoutElementDescription[nativeDesc.ResourceElements.Count];
  217. for (uint j = 0; j < nativeDesc.ResourceElements.Count; j++)
  218. {
  219. ref NativeResourceElementDescription elemDesc =
  220. ref nativeDesc.ResourceElements.Ref<NativeResourceElementDescription>(j);
  221. layouts[i].Elements[j] = new ResourceLayoutElementDescription(
  222. Util.GetString((byte*)elemDesc.Name.Data, elemDesc.Name.Count),
  223. elemDesc.Kind,
  224. elemDesc.Stages,
  225. elemDesc.Options);
  226. }
  227. }
  228. SpirvReflection reflection = new SpirvReflection(
  229. Array.Empty<VertexElementDescription>(),
  230. layouts);
  231. return new ComputeCompilationResult(csCode, reflection);
  232. }
  233. finally
  234. {
  235. if (result != null)
  236. {
  237. VeldridSpirvNative.Default.FreeResult(result);
  238. }
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Compiles the given GLSL source code into SPIR-V.
  244. /// </summary>
  245. /// <param name="sourceText">The shader source code.</param>
  246. /// <param name="fileName">A descriptive name for the shader. May be null.</param>
  247. /// <param name="stage">The <see cref="ShaderStages"/> which the shader is used in.</param>
  248. /// <param name="options">Parameters for the GLSL compiler.</param>
  249. /// <returns>A <see cref="SpirvCompilationResult"/> containing the compiled SPIR-V bytecode.</returns>
  250. public static unsafe SpirvCompilationResult CompileGlslToSpirv(
  251. string sourceText,
  252. string fileName,
  253. ShaderStages stage,
  254. GlslCompileOptions options)
  255. {
  256. int sourceAsciiCount = Encoding.ASCII.GetByteCount(sourceText);
  257. byte* sourceAsciiPtr = stackalloc byte[sourceAsciiCount];
  258. fixed (char* sourceTextPtr = sourceText)
  259. {
  260. Encoding.ASCII.GetBytes(sourceTextPtr, sourceText.Length, sourceAsciiPtr, sourceAsciiCount);
  261. }
  262. int macroCount = options.Macros.Length;
  263. NativeMacroDefinition* macros = stackalloc NativeMacroDefinition[(int)macroCount];
  264. for (int i = 0; i < macroCount; i++)
  265. {
  266. macros[i] = new NativeMacroDefinition(options.Macros[i]);
  267. }
  268. return CompileGlslToSpirv(
  269. (uint)sourceAsciiCount,
  270. sourceAsciiPtr,
  271. fileName,
  272. stage,
  273. options.Debug,
  274. (uint)macroCount,
  275. macros);
  276. }
  277. internal static unsafe SpirvCompilationResult CompileGlslToSpirv(
  278. uint sourceLength,
  279. byte* sourceTextPtr,
  280. string fileName,
  281. ShaderStages stage,
  282. bool debug,
  283. uint macroCount,
  284. NativeMacroDefinition* macros)
  285. {
  286. GlslCompileInfo info;
  287. info.Kind = GetShadercKind(stage);
  288. info.SourceText = new InteropArray(sourceLength, sourceTextPtr);
  289. info.Debug = debug;
  290. info.Macros = new InteropArray(macroCount, macros);
  291. if (string.IsNullOrEmpty(fileName)) { fileName = "<veldrid-spirv-input>"; }
  292. int fileNameAsciiCount = Encoding.ASCII.GetByteCount(fileName);
  293. byte* fileNameAsciiPtr = stackalloc byte[fileNameAsciiCount];
  294. if (fileNameAsciiCount > 0)
  295. {
  296. fixed (char* fileNameTextPtr = fileName)
  297. {
  298. Encoding.ASCII.GetBytes(fileNameTextPtr, fileName.Length, fileNameAsciiPtr, fileNameAsciiCount);
  299. }
  300. }
  301. info.FileName = new InteropArray((uint)fileNameAsciiCount, fileNameAsciiPtr);
  302. CompilationResult* result = null;
  303. try
  304. {
  305. result = VeldridSpirvNative.Default.CompileGlslToSpirv(&info);
  306. if (!result->Succeeded)
  307. {
  308. throw new SpirvCompilationException(
  309. "Compilation failed: " + Util.GetString((byte*)result->GetData(0), result->GetLength(0)));
  310. }
  311. uint length = result->GetLength(0);
  312. byte[] spirvBytes = new byte[(int)length];
  313. fixed (byte* spirvBytesPtr = &spirvBytes[0])
  314. {
  315. Buffer.MemoryCopy(result->GetData(0), spirvBytesPtr, length, length);
  316. }
  317. return new SpirvCompilationResult(spirvBytes);
  318. }
  319. finally
  320. {
  321. if (result != null)
  322. {
  323. VeldridSpirvNative.Default.FreeResult(result);
  324. }
  325. }
  326. }
  327. private static ShadercShaderKind GetShadercKind(ShaderStages stage)
  328. {
  329. switch (stage)
  330. {
  331. case ShaderStages.Vertex: return ShadercShaderKind.Vertex;
  332. case ShaderStages.Geometry: return ShadercShaderKind.Geometry;
  333. case ShaderStages.TessellationControl: return ShadercShaderKind.TessellationControl;
  334. case ShaderStages.TessellationEvaluation: return ShadercShaderKind.TessellationEvaluation;
  335. case ShaderStages.Fragment: return ShadercShaderKind.Fragment;
  336. case ShaderStages.Compute: return ShadercShaderKind.Compute;
  337. default: throw new SpirvCompilationException($"Invalid shader stage: {stage}");
  338. }
  339. }
  340. }
  341. }