将GLSL、HLSL转换为SPIR-V
SPIR-V是Vulkan的着色器字节码(注:OpenGL4.6及以上也可以使用SPIR-V作为Shader语言),作为中间语言,可方便且完整地转译其它平台的shader。
以下是SPIR-V的语言转换生态图:
在开发Vulkan程序时,用GLSL或HLSL来编写着色器逻辑,然后通过编译器将它们转换为SPIR-V。常见的开源编译器有glslang、glslc和dxc。
GLSL示例
Test.vert.glsl
#version 450 layout(location = 0) in vec2 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = vec4(inPosition, 0.0, 1.0); fragColor = inColor; }
Test.frag.glsl
#version 450 layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(fragColor, 1.0); }
HLSL示例
Test.vert.hlsl
struct VertexIn { float4 color : COLOR; }; struct VertexOut { float4 color : COLOR; }; VertexOut VS(VertexIn vIn) { VertexOut vOut; vOut.color = vIn.color; return vOut; }
Test.frag.hlsl
struct VertexOut { float4 posH : SV_POSITION; float4 color : COLOR; }; float4 PS(VertexOut pIn) : SV_Target { return pIn.color; }
glslang
Vulkan官方KhronosGroup推出的Shader编译器,可将GLSL或HLSL转换为SPIR-V。
注1:glslang原先只支持GLSL,Vulkan1.2开始加入对HLSL的支持
注2:glslang的HLSL前端是非官方维护的,而且并不能很好地兼容所有HLSL
Windows VulkanSDK中可执行程序为glslangValidator.exe。
glslang对shader的后缀有严格地要求:
后缀 | 说明 |
.conf | 提供一个配置文件来替换缺省配置。通过-c参数可生成一个模板配置文件。 |
.vert | vertex shader |
.tesc | tessellation control shader |
.tese | tessellation evaluation shader |
.geom | geometry shader |
.frag | fragment shader |
.comp | compute shader |
.mesh | mesh shader |
.task | task shader |
.rgen | ray generation shader |
.rint | ray intersection shader |
.rahit | ray any hit shader |
.rchit | ray closest hit shader |
.rmiss | ray miss shader |
.rcall | ray callable shader |
.glsl | .vert.glsl, .tesc.glsl, ..., .comp.glsl两级后缀 |
.hlsl | .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl两级后缀 |
GLSL
$(VULKAN_SDK)\Bin\glslangValidator.exe -V -S vert Test.vert.glsl -o Test.1.vert.spv // 将vs转换为SPIR-V $(VULKAN_SDK)\Bin\glslangValidator.exe -V -S frag Test.frag.glsl -o Test.1.frag.spv // 将ps转换为SPIR-V
注:将-V换成-G可创建OpenGL4.6及以上使用的spir-v,更多详见How to Load SPIR-V Shaders in OpenGL
HLSL
$(VULKAN_SDK)\Bin\glslangValidator.exe -D -V -S vert -e VS Test.vert.hlsl -o Test.1.vert.spv // 将vs转换为SPIR-V $(VULKAN_SDK)\Bin\glslangValidator.exe -D -V -S frag -e PS Test.frag.hlsl -o Test.1.frag.spv // 将ps转换为SPIR-V
更多命令行参数:
E:\VulkanSDK\shader\glsl>E:\VulkanSDK\1.3.243.0\Bin\glslangValidator.exe --help Usage: glslangValidator [option]... [file]... 'file' can end in .<stage> for auto-stage classification, where <stage> is: .conf to provide a config file that replaces the default configuration (see -c option below for generating a template) .vert for a vertex shader .tesc for a tessellation control shader .tese for a tessellation evaluation shader .geom for a geometry shader .frag for a fragment shader .comp for a compute shader .mesh for a mesh shader .task for a task shader .rgen for a ray generation shader .rint for a ray intersection shader .rahit for a ray any hit shader .rchit for a ray closest hit shader .rmiss for a ray miss shader .rcall for a ray callable shader .glsl for .vert.glsl, .tesc.glsl, ..., .comp.glsl compound suffixes .hlsl for .vert.hlsl, .tesc.hlsl, ..., .comp.hlsl compound suffixes Options: -C cascading errors; risk crash from accumulation of error recoveries -D input is HLSL (this is the default when any suffix is .hlsl) -D<name[=def]> | --define-macro <name[=def]> | --D <name[=def]> define a pre-processor macro -E print pre-processed GLSL; cannot be used with -l; errors will appear on stderr -G[ver] create SPIR-V binary, under OpenGL semantics; turns on -l; default file name is <stage>.spv (-o overrides this); 'ver', when present, is the version of the input semantics, which will appear in #define GL_SPIRV ver; '--client opengl100' is the same as -G100; a '--target-env' for OpenGL will also imply '-G'; currently only supports GLSL -H print human readable form of SPIR-V; turns on -V -I<dir> add dir to the include search path; includer's directory is searched first, followed by left-to-right order of -I -Od disables optimization; may cause illegal SPIR-V for HLSL -Os optimizes SPIR-V to minimize size -R use relaxed verification rules for generating Vulkan SPIR-V, allowing the use of default uniforms, atomic_uints, and gl_VertexID and gl_InstanceID keywords. -S <stage> uses specified stage rather than parsing the file extension choices for <stage> are vert, tesc, tese, geom, frag, or comp -U<name> | --undef-macro <name> | --U <name> undefine a pre-processor macro -V[ver] create SPIR-V binary, under Vulkan semantics; turns on -l; default file name is <stage>.spv (-o overrides this) 'ver', when present, is the version of the input semantics, which will appear in #define VULKAN ver '--client vulkan100' is the same as -V100 a '--target-env' for Vulkan will also imply '-V' -c configuration dump; creates the default configuration file (redirect to a .conf file) -d default to desktop (#version 110) when there is no shader #version (default is ES version 100) -e <name> | --entry-point <name> specify <name> as the entry-point function name -f{hlsl_functionality1} 'hlsl_functionality1' enables use of the SPV_GOOGLE_hlsl_functionality1 extension -g generate debug information -g0 strip debug information -gV generate nonsemantic shader debug information -gVS generate nonsemantic shader debug information with source -h print this usage message -i intermediate tree (glslang AST) is printed out -l link all input files together to form a single module -m memory leak mode -o <file> save binary to <file>, requires a binary option (e.g., -V) -q dump reflection query database; requires -l for linking -r | --relaxed-errors relaxed GLSL semantic error-checking mode -s silence syntax and semantic error reporting -t multi-threaded mode -v | --version print version strings -w | --suppress-warnings suppress GLSL warnings, except as required by "#extension : warn" -x save binary output as text-based 32-bit hexadecimal numbers -u<name>:<loc> specify a uniform location override for --aml --uniform-base <base> set a base to use for generated uniform locations --auto-map-bindings | --amb automatically bind uniform variables without explicit bindings --auto-map-locations | --aml automatically locate input/output lacking 'location' (fragile, not cross stage) --auto-sampled-textures Removes sampler variables and converts existing textures to sampled textures --client {vulkan<ver>|opengl<ver>} see -V and -G --depfile <file> writes depfile for build systems --dump-builtin-symbols prints builtin symbol table prior each compile -dumpfullversion | -dumpversion print bare major.minor.patchlevel --flatten-uniform-arrays | --fua flatten uniform texture/sampler arrays to scalars --glsl-version {100 | 110 | 120 | 130 | 140 | 150 | 300es | 310es | 320es | 330 400 | 410 | 420 | 430 | 440 | 450 | 460} set GLSL version, overrides #version in shader sourcen --hlsl-offsets allow block offsets to follow HLSL rules works independently of source language --hlsl-iomap perform IO mapping in HLSL register space --hlsl-enable-16bit-types allow 16-bit types in SPIR-V for HLSL --hlsl-dx9-compatible interprets sampler declarations as a texture/sampler combo like DirectX9 would, and recognizes DirectX9-specific semantics --hlsl-dx-position-w W component of SV_Position in HLSL fragment shaders compatible with DirectX --invert-y | --iy invert position.Y output in vertex shader --enhanced-msgs print more readable error messages (GLSL only) --keep-uncalled | --ku don't eliminate uncalled functions --nan-clamp favor non-NaN operand in min, max, and clamp --no-storage-format | --nsf use Unknown image format --quiet do not print anything to stdout, unless requested by another option --reflect-strict-array-suffix use strict array suffix rules when reflecting --reflect-basic-array-suffix arrays of basic types will have trailing [0] --reflect-intermediate-io reflection includes inputs/outputs of linked shaders rather than just vertex/fragment --reflect-separate-buffers reflect buffer variables and blocks separately to uniforms --reflect-all-block-variables reflect all variables in blocks, whether inactive or active --reflect-unwrap-io-blocks unwrap input/output blocks the same as uniform blocks --resource-set-binding [stage] name set binding set descriptor set and binding for individual resources --resource-set-binding [stage] set set descriptor set for all resources --rsb synonym for --resource-set-binding --set-block-backing name {uniform|buffer|push_constant} changes the backing type of a uniform, buffer, or push_constant block declared in in the program, when using -R option. This can be used to change the backing for existing blocks as well as implicit ones such as 'gl_DefaultUniformBlock'. --sbs synonym for set-block-storage --set-atomic-counter-block name set set name, and descriptor set for atomic counter blocks, with -R opt --sacb synonym for set-atomic-counter-block --set-default-uniform-block name set binding set name, descriptor set, and binding for global default-uniform-block, with -R opt --sdub synonym for set-default-uniform-block --shift-image-binding [stage] num base binding number for images (uav) --shift-image-binding [stage] [num set]... per-descriptor-set shift values --sib synonym for --shift-image-binding --shift-sampler-binding [stage] num base binding number for samplers --shift-sampler-binding [stage] [num set]... per-descriptor-set shift values --ssb synonym for --shift-sampler-binding --shift-ssbo-binding [stage] num base binding number for SSBOs --shift-ssbo-binding [stage] [num set]... per-descriptor-set shift values --sbb synonym for --shift-ssbo-binding --shift-texture-binding [stage] num base binding number for textures --shift-texture-binding [stage] [num set]... per-descriptor-set shift values --stb synonym for --shift-texture-binding --shift-uav-binding [stage] num base binding number for UAVs --shift-uav-binding [stage] [num set]... per-descriptor-set shift values --suavb synonym for --shift-uav-binding --shift-UBO-binding [stage] num base binding number for UBOs --shift-UBO-binding [stage] [num set]... per-descriptor-set shift values --sub synonym for --shift-UBO-binding --shift-cbuffer-binding | --scb synonyms for --shift-UBO-binding --spirv-dis output standard-form disassembly; works only when a SPIR-V generation option is also used --spirv-val execute the SPIRV-Tools validator --source-entrypoint <name> the given shader source function is renamed to be the <name> given in -e --sep synonym for --source-entrypoint --stdin read from stdin instead of from a file; requires providing the shader stage using -S --target-env {vulkan1.0 | vulkan1.1 | vulkan1.2 | vulkan1.3 | opengl | spirv1.0 | spirv1.1 | spirv1.2 | spirv1.3 | spirv1.4 | spirv1.5 | spirv1.6} Set the execution environment that the generated code will be executed in. Defaults to: * vulkan1.0 under --client vulkan<ver> * opengl under --client opengl<ver> * spirv1.0 under --target-env vulkan1.0 * spirv1.3 under --target-env vulkan1.1 * spirv1.5 under --target-env vulkan1.2 * spirv1.6 under --target-env vulkan1.3 Multiple --target-env can be specified. --variable-name <name> --vn <name> creates a C header file that contains a uint32_t array named <name> initialized with the shader binary code
glslc
Google推出的shader编译器,封装了glslang和SPIRV-Tools,可将GLSL或HLSL转换为SPIR-V。
GLSL
$(VULKAN_SDK)\Bin\glslc.exe -fshader-stage=vert Test.vert.glsl -o Test.2.vert.spv // 将vs转换为SPIR-V $(VULKAN_SDK)\Bin\glslc.exe -fshader-stage=frag Test.frag.glsl -o Test.2.frag.spv // 将ps转换为SPIR-V
HLSL
$(VULKAN_SDK)\Bin\glslc.exe -fshader-stage=vert -fentry-point=VS Test.vert.hlsl -o Test.2.vert.spv // 将vs转换为SPIR-V $(VULKAN_SDK)\Bin\glslc.exe -fshader-stage=frag -fentry-point=PS Test.frag.hlsl -o Test.2.frag.spv // 将ps转换为SPIR-V
更多命令行参数:
E:\VulkanSDK\shader\glsl>E:\VulkanSDK\1.3.243.0\Bin\glslc.exe --help glslc - Compile shaders into SPIR-V Usage: glslc [options] file... An input file of - represents standard input. Options: -c Only run preprocess, compile, and assemble steps. -Dmacro[=defn] Add an implicit macro definition. -E Outputs only the results of the preprocessing step. Output defaults to standard output. -fauto-bind-uniforms Automatically assign bindings to uniform variables that don't have an explicit 'binding' layout in the shader source. -fauto-map-locations Automatically assign locations to uniform variables that don't have an explicit 'location' layout in the shader source. -fauto-combined-image-sampler Removes sampler variables and converts existing textures to combined image-samplers. -fentry-point=<name> Specify the entry point name for HLSL compilation, for all subsequent source files. Default is "main". -fhlsl-16bit-types Enable 16-bit type support for HLSL. -fhlsl_functionality1, -fhlsl-functionality1 Enable extension SPV_GOOGLE_hlsl_functionality1 for HLSL compilation. -fhlsl-iomap Use HLSL IO mappings for bindings. -fhlsl-offsets Use HLSL offset rules for packing members of blocks. Affects only GLSL. HLSL rules are always used for HLSL. -finvert-y Invert position.Y output in vertex shader. -flimit=<settings> Specify resource limits. Each limit is specified by a limit name followed by an integer value. Tokens should be separated by whitespace. If the same limit is specified several times, only the last setting takes effect. -flimit-file <file> Set limits as specified in the given file. -fnan-clamp Generate code for max and min builtins so that, when given a NaN operand, the other operand is returned. Similarly, the clamp builtin will favour the non-NaN operands, as if clamp were implemented as a composition of max and min. -fpreserve-bindings Preserve all binding declarations, even if those bindings are not used. -fresource-set-binding [stage] <reg0> <set0> <binding0> [<reg1> <set1> <binding1>...] Explicitly sets the descriptor set and binding for HLSL resources, by register name. Optionally restrict it to a single stage. -fcbuffer-binding-base [stage] <value> Same as -fubo-binding-base. -fimage-binding-base [stage] <value> Sets the lowest automatically assigned binding number for images. Optionally only set it for a single shader stage. For HLSL, the resource register number is added to this base. -fsampler-binding-base [stage] <value> Sets the lowest automatically assigned binding number for samplers Optionally only set it for a single shader stage. For HLSL, the resource register number is added to this base. -fssbo-binding-base [stage] <value> Sets the lowest automatically assigned binding number for shader storage buffer objects (SSBO). Optionally only set it for a single shader stage. Only affects GLSL. -ftexture-binding-base [stage] <value> Sets the lowest automatically assigned binding number for textures. Optionally only set it for a single shader stage. For HLSL, the resource register number is added to this base. -fuav-binding-base [stage] <value> For automatically assigned bindings for unordered access views (UAV), the register number is added to this base to determine the binding number. Optionally only set it for a single shader stage. Only affects HLSL. -fubo-binding-base [stage] <value> Sets the lowest automatically assigned binding number for uniform buffer objects (UBO). Optionally only set it for a single shader stage. For HLSL, the resource register number is added to this base. -fshader-stage=<stage> Treat subsequent input files as having stage <stage>. Valid stages are vertex, vert, fragment, frag, tesscontrol, tesc, tesseval, tese, geometry, geom, compute, and comp. -g Generate source-level debug information. -h Display available options. --help Display available options. -I <value> Add directory to include search path. -mfmt=<format> Output SPIR-V binary code using the selected format. This option may be specified only when the compilation output is in SPIR-V binary code form. Available options are: bin - SPIR-V binary words. This is the default. c - Binary words as C initializer list of 32-bit ints num - List of comma-separated 32-bit hex integers -M Generate make dependencies. Implies -E and -w. -MM An alias for -M. -MD Generate make dependencies and compile. -MF <file> Write dependency output to the given file. -MT <target> Specify the target of the rule emitted by dependency generation. -O Optimize the generated SPIR-V code for better performance. -Os Optimize the generated SPIR-V code for smaller size. -O0 Disable optimization. -o <file> Write output to <file>. A file name of '-' represents standard output. -std=<value> Version and profile for GLSL input files. Possible values are concatenations of version and profile, e.g. 310es, 450core, etc. Ignored for HLSL files. -S Emit SPIR-V assembly instead of binary. --show-limits Display available limit names and their default values. --target-env=<environment> Set the target client environment, and the semantics of warnings and errors. An optional suffix can specify the client version. Values are: vulkan1.0 # The default vulkan1.1 vulkan1.2 vulkan1.3 vulkan # Same as vulkan1.0 opengl4.5 opengl # Same as opengl4.5 --target-spv=<spirv-version> Set the SPIR-V version to be used for the generated SPIR-V module. The default is the highest version of SPIR-V required to be supported for the target environment. For example, default for vulkan1.0 is spv1.0, and the default for vulkan1.1 is spv1.3, the default for vulkan1.2 is spv1.5. the default for vulkan1.3 is spv1.6. Values are: spv1.0, spv1.1, spv1.2, spv1.3, spv1.4, spv1.5, spv1.6 --version Display compiler version information. -w Suppresses all warning messages. -Werror Treat all warnings as errors. -x <language> Treat subsequent input files as having type <language>. Valid languages are: glsl, hlsl. For files ending in .hlsl the default is hlsl. Otherwise the default is glsl.
dxc
微软推出的shader编译器,能将DX12的HLSL转换为DXIL字节码。也可以将DX12的HLSL转换为SPIR-V。
转换为DXIL字节码
$(VULKAN_SDK)\Bin\dxc.exe -T vs_6_0 -E VS Test.vert.hlsl -Fo Test.3.vert.dxil // 将vs转换为DXIL $(VULKAN_SDK)\Bin\dxc.exe -T ps_6_0 -E PS Test.frag.hlsl -Fo Test.3.frag.dxil // 将ps转换为DXIL
注:如果报warning: DXIL signing library (dxil.dll,libdxil.so) not found. Resulting DXIL will not be signed for use in release environments.,请升级dxc版本
使用windows SDK中的dxc.exe工具,就不会报上面的warning
"E:\Windows Kits\10\bin\10.0.18362.0\x64\dxc.exe" -T vs_6_0 -E VS Test.vert.hlsl -Fo Test.3.vert.dxil // 将vs转换为DXIL "E:\Windows Kits\10\bin\10.0.18362.0\x64\dxc.exe" -T ps_6_0 -E PS Test.frag.hlsl -Fo Test.3.frag.dxil // 将ps转换为DXIL
转换为DXIL字节码(同时输出lld调试文件)
"E:\Windows Kits\10\bin\10.0.18362.0\x64\dxc.exe" -T vs_6_0 -E VS Test.vert.hlsl -Fo Test.3.vert.dxil /Zi /Fd F:\Temp\pdb\ // 将vs转换为DXIL,同时输出lld调试文件 "E:\Windows Kits\10\bin\10.0.18362.0\x64\dxc.exe" -T ps_6_0 -E PS Test.frag.hlsl -Fo Test.3.frag.dxil /Zi /Fd F:\Temp\pdb\ // 将ps转换为DXIL,同时输出lld调试文件
注:/Fd后面的目录路径要以\结尾,否则会报错
转换为SPIR-V
更多可参考:SPIR‐V-CodeGen、HLSL to SPIR-V Feature Mapping Manual
$(VULKAN_SDK)\Bin\dxc.exe -spirv -T vs_6_0 -E VS Test.vert.hlsl -Fo Test.3.vert.spv // 将vs转换为SPIR-V $(VULKAN_SDK)\Bin\dxc.exe -spirv -T ps_6_0 -E PS Test.frag.hlsl -Fo Test.3.frag.spv // 将ps转换为SPIR-V
更多命令行参数:
E:\VulkanSDK\shader\hlsl>E:\VulkanSDK\1.3.243.0\Bin\dxc.exe --help OVERVIEW: HLSL Compiler for Windows Version: dxcompiler.dll: 1.7 - 1.7.0.3860 (d04c296ad) USAGE: dxc.exe [options] <inputs> Common Options: -help Display available options -Qunused-arguments Don't emit warning for unused driver arguments --version Display compiler version information Compilation Options: -all-resources-bound Enables agressive flattening -auto-binding-space <value> Set auto binding space - enables auto resource binding in libraries -Cc Output color coded assembly listings -default-linkage <value> Set default linkage for non-shader functions when compiling or linking to a library target (internal, external) -denorm <value> select denormal value options (any, preserve, ftz). any is the default. -disable-payload-qualifiers Disables support for payload access qualifiers for raytracing payloads in SM 6.7. -D <value> Define macro -enable-16bit-types Enable 16bit types and disable min precision types. Available in HLSL 2018 and shader model 6.2 -enable-lifetime-markers Enable generation of lifetime markers -enable-payload-qualifiers Enables support for payload access qualifiers for raytracing payloads in SM 6.6. -encoding <value> Set default encoding for source inputs and text outputs (utf8|utf16(win)|utf32(*nix)|wide) default=utf8 -export-shaders-only Only export shaders when compiling a library -exports <value> Specify exports when compiling a library: export1[[,export1_clone,...]=internal_name][;...] -E <value> Entry point name -Fc <file> Output assembly code listing file -fdiagnostics-show-option Print option name with mappable diagnostics -fdisable-loc-tracking Disable source location tracking in IR. This will break diagnostic generation for late validation. (Ignored if /Zi is passed) -Fd <file> Write debug information to the given file, or automatically named file in directory when ending in '\' -Fe <file> Output warnings and errors to the given file -Fh <file> Output header file containing object code -Fi <file> Set preprocess output file name (with /P) -flegacy-macro-expansion Expand the operands before performing token-pasting operation (fxc behavior) -flegacy-resource-reservation Reserve unused explicit register assignments for compatibility with shader model 5.0 and below -fnew-inlining-behavior Experimental option to use heuristics-driven late inlining and disable alwaysinline annotation for library shaders -fno-diagnostics-show-option Do not print option name with mappable diagnostics -force-rootsig-ver <profile> force root signature version (rootsig_1_1 if omitted) -Fo <file> Output object file -Fre <file> Output reflection to the given file -Frs <file> Output root signature to the given file -Fsh <file> Output shader hash to the given file -ftime-report Print time report -ftime-trace=<value> Print hierchial time tracing to file -ftime-trace Print hierchial time tracing to stdout -Gec Enable backward compatibility mode -Ges Enable strict mode -Gfa Avoid flow control constructs -Gfp Prefer flow control constructs -Gis Force IEEE strictness -HV <value> HLSL version (2016, 2017, 2018, 2021). Default is 2018 -H Show header includes and nesting depth -ignore-line-directives Ignore line directives -I <value> Add directory to include search path -Lx Output hexadecimal literals -Ni Output instruction numbers in assembly listings -no-legacy-cbuf-layout Do not use legacy cbuffer load -no-warnings Suppress warnings -No Output instruction byte offsets in assembly listings -Odump Print the optimizer commands. -Od Disable optimizations -pack-optimized Optimize signature packing assuming identical signature provided for each connecting stage -pack-prefix-stable (default) Pack signatures preserving prefix-stable property - appended elements will not disturb placement of prior elements -recompile recompile from DXIL container with Debug Info or Debug Info bitcode file -res-may-alias Assume that UAVs/SRVs may alias -rootsig-define <value> Read root signature from a #define -T <profile> Set target profile. <profile>: ps_6_0, ps_6_1, ps_6_2, ps_6_3, ps_6_4, ps_6_5, ps_6_6, ps_6_7, vs_6_0, vs_6_1, vs_6_2, vs_6_3, vs_6_4, vs_6_5, vs_6_6, vs_6_7, gs_6_0, gs_6_1, gs_6_2, gs_6_3, gs_6_4, gs_6_5, gs_6_6, gs_6_7, hs_6_0, hs_6_1, hs_6_2, hs_6_3, hs_6_4, hs_6_5, hs_6_6, hs_6_7, ds_6_0, ds_6_1, ds_6_2, ds_6_3, ds_6_4, ds_6_5, ds_6_6, ds_6_7, cs_6_0, cs_6_1, cs_6_2, cs_6_3, cs_6_4, cs_6_5, cs_6_6, cs_6_7, lib_6_1, lib_6_2, lib_6_3, lib_6_4, lib_6_5, lib_6_6, lib_6_7, ms_6_5, ms_6_6, ms_6_7, as_6_5, as_6_6, as_6_7, -Vd Disable validation -verify<value> Verify diagnostic output using comment directives -Vi Display details about the include process. -Vn <name> Use <name> as variable name in header file -WX Treat warnings as errors -Zi Enable debug information. Cannot be used together with -Zs -Zpc Pack matrices in column-major order -Zpr Pack matrices in row-major order -Zsb Compute Shader Hash considering only output binary -Zss Compute Shader Hash considering source information -Zs Generate small PDB with just sources and compile options. Cannot be used together with -Zi OPTIONS: -MD Write a file with .d extension that will contain the list of the compilation target dependencies. -MF <file> Write the specfied file that will contain the list of the compilation target dependencies. -M Dumps the list of the compilation target dependencies. Optimization Options: -ffinite-math-only Allow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs. -fno-finite-math-only Disallow optimizations for floating-point arithmetic that assume that arguments and results are not NaNs or +-Infs. -O0 Optimization Level 0 -O1 Optimization Level 1 -O2 Optimization Level 2 -O3 Optimization Level 3 (Default) Rewriter Options: -decl-global-cb Collect all global constants outside cbuffer declarations into cbuffer GlobalCB { ... }. Still experimental, not all dependency scenarios handled. -extract-entry-uniforms Move uniform parameters from entry point to global scope -global-extern-by-default Set extern on non-static globals -keep-user-macro Write out user defines after rewritten HLSL -line-directive Add line directive -remove-unused-functions Remove unused functions and types -remove-unused-globals Remove unused static globals and functions -skip-fn-body Translate function definitions to declarations -skip-static Remove static functions and globals when used with -skip-fn-body -unchanged Rewrite HLSL, without changes. SPIR-V CodeGen Options: -fspv-debug=<value> Specify whitelist of debug info category (file -> source -> line, tool, vulkan-with-source) -fspv-entrypoint-name=<value> Specify the SPIR-V entry point name. Defaults to the HLSL entry point name. -fspv-extension=<value> Specify SPIR-V extension permitted to use -fspv-flatten-resource-arrays Flatten arrays of resources so each array element takes one binding number -fspv-print-all Print the SPIR-V module before each pass and after the last one. Useful for debugging SPIR-V legalization and optimization passes. -fspv-reduce-load-size Replaces loads of composite objects to reduce memory pressure for the loads -fspv-reflect Emit additional SPIR-V instructions to aid reflection -fspv-target-env=<value> Specify the target environment: vulkan1.0 (default), vulkan1.1, vulkan1.1spirv1.4, vulkan1.2, vulkan1.3, or universal1.5 -fspv-use-legacy-buffer-matrix-order Assume the legacy matrix order (row major) when accessing raw buffers (e.g., ByteAdddressBuffer) -fvk-auto-shift-bindings Apply fvk-*-shift to resources without an explicit register assignment. -fvk-b-shift <shift> <space> Specify Vulkan binding number shift for b-type register -fvk-bind-globals <binding> <set> Specify Vulkan binding number and set number for the $Globals cbuffer -fvk-bind-register <type-number> <space> <binding> <set> Specify Vulkan descriptor set and binding for a specific register -fvk-invert-y Negate SV_Position.y before writing to stage output in VS/DS/GS to accommodate Vulkan's coordinate system -fvk-s-shift <shift> <space> Specify Vulkan binding number shift for s-type register -fvk-support-nonzero-base-instance Follow Vulkan spec to use gl_BaseInstance as the first vertex instance, which makes SV_InstanceID = gl_InstanceIndex - gl_BaseInstance (without this option, SV_InstanceID = gl_InstanceIndex) -fvk-t-shift <shift> <space> Specify Vulkan binding number shift for t-type register -fvk-u-shift <shift> <space> Specify Vulkan binding number shift for u-type register -fvk-use-dx-layout Use DirectX memory layout for Vulkan resources -fvk-use-dx-position-w Reciprocate SV_Position.w after reading from stage input in PS to accommodate the difference between Vulkan and DirectX -fvk-use-gl-layout Use strict OpenGL std140/std430 memory layout for Vulkan resources -fvk-use-scalar-layout Use scalar memory layout for Vulkan resources -Oconfig=<value> Specify a comma-separated list of SPIRV-Tools passes to customize optimization configuration (see http://khr.io/hlsl2spirv#optimization) -spirv Generate SPIR-V code Utility Options: -dumpbin Load a binary file rather than compiling -extractrootsignature Extract root signature from shader bytecode (must be used with /Fo <file>) -getprivate <file> Save private data from shader blob -link Link list of libraries provided in <inputs> argument separated by ';' -P Preprocess to file -Qembed_debug Embed PDB in shader container (must be used with /Zi) -Qstrip_debug Strip debug information from 4_0+ shader bytecode (must be used with /Fo <file>) -Qstrip_priv Strip private data from shader bytecode (must be used with /Fo <file>) -Qstrip_reflect Strip reflection data from shader bytecode (must be used with /Fo <file>) -Qstrip_rootsignature Strip root signature data from shader bytecode (must be used with /Fo <file>) -setprivate <file> Private data to add to compiled shader blob -setrootsignature <file> Attach root signature to shader bytecode -verifyrootsignature <file> Verify shader bytecode with root signature Warning Options: -W[no-]<warning> Enable/Disable the specified warning
fxc
微软推出的shader编译器,使用d3dcompiler库将DX11及以下的HLSL转换为DXBC字节码。但该工具不能将HLSL转换为SPIR-V。
转换为DXBC字节码
"E:\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" Test.vert.hlsl /E VS /T vs_5_0 /Fc Test.3.vert.d3dasm // 将vs转换为DXBC "E:\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" Test.frag.hlsl /E PS /T ps_5_0 /Fc Test.3.frag.d3dasm // 将ps转换为DXBC
Test.3.vert.d3dasm
// // Generated by Microsoft (R) HLSL Shader Compiler 10.1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // COLOR 0 xyzw 0 NONE float xyzw // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // COLOR 0 xyzw 0 NONE float xyzw // vs_5_0 dcl_globalFlags refactoringAllowed dcl_input v0.xyzw dcl_output o0.xyzw mov o0.xyzw, v0.xyzw ret // Approximately 2 instruction slots used
Test.3.frag.d3dasm
// // Generated by Microsoft (R) HLSL Shader Compiler 10.1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_POSITION 0 xyzw 0 POS float // COLOR 0 xyzw 1 NONE float xyzw // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // SV_Target 0 xyzw 0 TARGET float xyzw // ps_5_0 dcl_globalFlags refactoringAllowed dcl_input_ps linear v1.xyzw dcl_output o0.xyzw mov o0.xyzw, v1.xyzw ret // Approximately 2 instruction slots used
更多命令行参考:
E:\VulkanSDK\shader\hlsl>"E:\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" /? Microsoft (R) Direct3D Shader Compiler 10.1 (using E:\Windows Kits\10\bin\10.0.18362.0\x64\D3DCOMPILER_47.dll) Copyright (C) 2013 Microsoft. All rights reserved. Usage: fxc <options> <files> /?, /help print this message /T <profile> target profile /E <name> entrypoint name /I <include> additional include path /Vi display details about the include process /Od disable optimizations /Op disable preshaders /O{0,1,2,3} optimization level 0..3. 1 is default /WX treat warnings as errors /Vd disable validation /Zi enable debugging information /Zss debug name with source information /Zsb debug name with only binary information /Zpr pack matrices in row-major order /Zpc pack matrices in column-major order /Gpp force partial precision /Gfa avoid flow control constructs /Gfp prefer flow control constructs /Gdp disable effect performance mode /Ges enable strict mode /Gec enable backwards compatibility mode /Gis force IEEE strictness /Gch compile as a child effect for FX 4.x targets /Fo <file> output object file /Fl <file> output a library /Fc <file> output assembly code listing file /Fx <file> output assembly code and hex listing file /Fh <file> output header file containing object code /Fe <file> output warnings and errors to a specific file /Fd <file> extract shader PDB and write to given file /Vn <name> use <name> as variable name in header file /Cc output color coded assembly listings /Ni output instruction numbers in assembly listings /No output instruction byte offset in assembly listings /Lx output hexadecimal literals /P <file> preprocess to file (must be used alone) @<file> options response file /dumpbin load a binary file rather than compiling /Qstrip_reflect strip reflection data from 4_0+ shader bytecode /Qstrip_debug strip debug information from 4_0+ shader bytecode /Qstrip_priv strip private data from 4_0+ shader bytecode /Qstrip_rootsignature strip root signature from shader bytecode /setrootsignature <file> attach root signature to shader bytecode /extractrootsignature <file> extract root signature from shader bytecode /verifyrootsignature <file> verify shader bytecode against root signature /compress compress DX10 shader bytecode from files /decompress decompress bytecode from first file, output files should be listed in the order they were in during compression /shtemplate <file> template shader file for merging/matching resources /mergeUAVs merge UAV slots of template shader and current shader /matchUAVs match template shader UAV slots in current shader /res_may_alias assume that UAVs/SRVs may alias for cs_5_0+ /enable_unbounded_descriptor_tables enables unbounded descriptor tables /all_resources_bound enable aggressive flattening in SM5.1+ /setprivate <file> private data to add to compiled shader blob /getprivate <file> save private data from shader blob /force_rootsig_ver <profile> force root signature version (rootsig_1_1 if omitted) /D <id>=<text> define macro /nologo suppress copyright message <profile>: cs_4_0 cs_4_1 cs_5_0 cs_5_1 ds_5_0 ds_5_1 gs_4_0 gs_4_1 gs_5_0 gs_5_1 hs_5_0 hs_5_1 lib_4_0 lib_4_1 lib_4_0_level_9_1 lib_4_0_level_9_1_vs_only lib_4_0_level_9_1_ps_only lib_4_0_level_9_3 lib_4_0_level_9_3_vs_only lib_4_0_level_9_3_ps_only lib_5_0 ps_2_0 ps_2_a ps_2_b ps_2_sw ps_3_0 ps_3_sw ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_4_0_level_9_0 ps_4_1 ps_5_0 ps_5_1 rootsig_1_0 rootsig_1_1 tx_1_0 vs_1_1 vs_2_0 vs_2_a vs_2_sw vs_3_0 vs_3_sw vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_4_0_level_9_0 vs_4_1 vs_5_0 vs_5_1
转换为DXBC字节码(同时输出pdb调试文件)
"E:\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" Test.vert.hlsl /E VS /T vs_5_0 /Zi /Zss /Fc Test.3.vert.d3dasm /Fd F:\Temp\pdb\ // 将vs转换为DXBC,同时输出pdb调试文件 "E:\Windows Kits\10\bin\10.0.18362.0\x64\fxc.exe" Test.frag.hlsl /E PS /T ps_5_0 /Zi /Zss /Fc Test.3.frag.d3dasm /Fd F:\Temp\pdb\ // 将ps转换为DXBC,同时输出pdb调试文件
注:/Fd后面的目录路径要以\结尾,否则会报错