andersch.dev

<2025-03-07 Fri>

Shader Cross-Compilation

Shaders written in certain shading languages may be cross-compiled to target platform-specific shader languages (e.g. GLSL, HLSL, Metal). This can be achieved in various ways.

sokolshdc

A shader-cross-compiler and code-generator command line tool.

  • Translates GLSL (vulkan-style, ver450 w/ separate texture/sampler uniforms) to
    • GLSL v300es - for GLES3 and WebGL2
    • GLSL v410 - for desktop GL without storage buffer support
    • GLSL v430 - for desktop GL with storage buffer support
    • HLSL4/HLSL5 - for D3D11, optionally as bytecode
    • Metal - for macOS and iOS, optionally as bytecode
    • WGSL - for WebGPU
  • Generates header files that can be #included
  • Uses @annotations in the shader source code to…
    • pack vertex- and fragment-shaders into same source file
    • wrap and include reusable code blocks
    • provide additional information for C code-generation
  • C header contains
    • reflection info in a comment block
    • a C struct for each shader uniform block
    • name_prog_shader_desc(sg_backend backend) function returns sg_shader_desc
    • shader descriptions can be used directly with sg_make_shader()
    • constants for vertex attr. locations, uniform-block- and image-bind-slots
    • optionally C functions for runtime inspection

SDLshadercross

Library for translating shaders to different formats, intended for use with SDL's GPU API. It takes SPIRV or HLSL as the source and outputs DXBC, DXIL, SPIRV, MSL, or HLSL. See Introducing: SDLshadercross.

  • Uses SPIRV-Cross to disassemble SPIR-V into high-level source languages.
  • Uses DirectXShaderCompiler to compile HLSL into either SPIR-V or DXIL.