Skip to content

@web-engine-dev/shader-compiler

Dual-target shader compilation pipeline generating both WGSL (WebGPU) and hand-written GLSL (WebGL 2) from a unified shader source format. Handles includes, defines, variant generation, and dead-code elimination.

Layer 5 · Resources

Features

  • Dual Pipeline: Compiles to both WGSL (WebGPU) and GLSL ES 3.0 (WebGL 2)
  • Unified Shader Format: Write once, compile to both targets
  • Include System: #include directives with dependency resolution and cycle detection
  • Preprocessor: #define, #ifdef, #ifndef, #if, #elif, #else, #endif
  • Variant Generation: Compile-time feature flags for shader permutations
  • Dead-Code Elimination: Remove unused functions, uniforms, and varyings
  • Reflection: Extract uniform blocks, samplers, vertex inputs, and storage buffers
  • Source Maps: Map compiled output back to original source lines for debugging
  • Caching: Content-hash based caching of compiled shaders
  • Validation: Syntax and semantic validation with line-accurate error messages

Installation

bash
npm install @web-engine-dev/shader-compiler
# or
pnpm add @web-engine-dev/shader-compiler

Quick Start

typescript
import { ShaderCompiler, ShaderTarget } from '@web-engine-dev/shader-compiler';

const compiler = new ShaderCompiler();

// Compile a unified shader to both targets
const wgslOutput = compiler.compile(shaderSource, {
  target: ShaderTarget.WGSL,
  defines: { USE_NORMAL_MAP: true, MAX_LIGHTS: 8 },
  includes: shaderLibrary,
});

const glslOutput = compiler.compile(shaderSource, {
  target: ShaderTarget.GLSL_ES300,
  defines: { USE_NORMAL_MAP: true, MAX_LIGHTS: 8 },
  includes: shaderLibrary,
});

// Extract reflection data
const reflection = wgslOutput.reflection;
console.log(reflection.uniformBlocks); // Binding layout
console.log(reflection.samplers); // Texture bindings
console.log(reflection.vertexInputs); // Vertex attribute layout

Compilation Pipeline

  1. Preprocessing — Resolve #include directives, expand #define macros
  2. Variant Expansion — Generate permutations from feature flags
  3. Parsing — Build AST from unified shader source
  4. Target Translation — Emit WGSL or GLSL ES 3.0 from AST
  5. Dead-Code Elimination — Remove unused declarations
  6. Reflection — Extract binding metadata for pipeline layout creation
  7. Validation — Check types, bindings, and limits
  8. Caching — Store compiled output keyed by content hash

Shader Variants

Variants allow a single shader source to generate many GPU programs:

Base shader × { LIT, UNLIT } × { SKINNED, STATIC } × { NORMAL_MAP, NO_NORMAL_MAP }
= 1 source file → 8 compiled variants

Only variant combinations actually used in materials are compiled — the rest are pruned.

Dependencies

  • @web-engine-dev/render-graph — Pipeline integration
  • @web-engine-dev/assets — Shader asset type registration

Proprietary software. All rights reserved.