커밋 af54ddad5의 AUTHORING.md를 그대로 옮긴 것으로, 이 절의 본문은 아직 영어입니다. 패키지는 0.2.0에서 쓸 typeshade라는 이름으로 가져옵니다.
조건부 프로그램
After this page you can decide which of several programs to build from one codebase, tell when a variant is one constant instead of a different program, hand the choice to a host that owns the defines, and name the result so a cache cannot serve one variant for another.
A shader that has to differ by feature, elevation present or absent, 3D or flat, is where a
GLSL codebase reaches for #define and a ladder of #ifdef. This package has no
preprocessor. A program is a file and what it imports, so the thing that varies is which
file you compile, and the code the variants share is a file they both import. The emitted
program carries the winning variant’s code with no dispatch chain around it.
Three questions hide under “the program changes”, and each one has its own answer: the shape of the program differs, a single value differs, or the choice belongs to the host. A capability the device may or may not have is a fourth question, and Capabilities & extensions answers it.
One file per variant
To specialize is to build one program for one set of choices. Write each variant as an entry file, and put what they share in a file each one imports:
"use typeshade";
export function shadeHeight(h: f32): vec4 { return vec4(h, h * 0.5, 0., 1.);}
// terrain-flat.shade.ts"use typeshade";
import { shadeHeight } from "./terrain.shade.ts";
@fragmentexport function fs(uv: location<0, vec2>): vec4 { return shadeHeight(0.);}
// terrain-dem.shade.ts"use typeshade";
import { shadeHeight } from "./terrain.shade.ts";
declare const dem: texture_2d<f32>;declare const demSampler: sampler;
@fragmentexport function fs(uv: location<0, vec2>): vec4 { return shadeHeight(textureSample(dem, demSampler, uv).x);}The host picks the file:
import { compile } from 'typeshade'
// read: the readDocument of "A shader module that imports another"const buildTerrain = (hasElevation: boolean) => { const fileName = hasElevation ? 'terrain-dem.shade.ts' : 'terrain-flat.shade.ts' return compile(read(fileName)!, { fileName, readDocument: read })}The bindings move with the shape here, and that is the reason to prefer this over a
preprocessor. In the flat variant the elevation texture is never declared, so it is absent
from reflect(), absent from the bind group layout, and the host creates no resource for
it. A const flag and a plain if would not do that: the branch is emitted as written and
the declared texture stays in the module, which is how a disabled feature still costs a
binding slot.
Some choices cannot be made until draw time. Those stay as a runtime branch on a uniform, which the GPU evaluates. Specializing is for a choice you already know when you build.
A value that differs with override
If every variant would emit the same program with one constant changed, specializing
multiplies pipelines for nothing. Declare a specialization constant instead, with
override<T>. A specialization constant is a module-scope value whose read stays symbolic
through every pass and is pinned by the host when it creates the pipeline.
"use typeshade";
const quality: override<f32> = 1.;
export function shade(base: f32): f32 { let acc = base; if (quality > 1.) { acc = acc * 2. + 0.5; } return acc;}
@fragmentexport function fs(v: location<0, f32>): vec4 { return vec4(shade(v), 0., 0., 1.);}WGSL emits override quality: f32 = 1.0; and the host pins it through the pipeline’s
constants. GLSL ES 3.00 has no driver-side equivalent, so the backend emits a #define
with the default. The program runtime pins it from render({ constants }) or
compute(entry, { constants }); an imported compute entry accepts the same record in its
third argument. A host that emits GLSL itself supplies
emitGlslModule(m, 'fragment', { overrideValues: { quality: 2 } }). These paths read
the declared constants from reflect().overrides. On the WebGL2 tier, the compute pass program keeps the default workgroup
shape and array lengths when override values change. Selecting them by override is not supported yet on the WebGL2 tier (Rule 11.8).
Because the read stays opaque to the optimizer, the branch above survives every pass and the driver removes it per pipeline variant, which is the classic ubershader mechanism. The rule of thumb: if two variants would compile to the same instruction sequence with one literal changed, that is an override; if they compile to different code, that is a separate file.
Axes the host decides
An axis is one thing the program varies on, together with the list of values it can take.
One point in the axis space is a variant. When the host picks the point at runtime, from
state you do not own, the matrix itself becomes the authored thing: variantFamily takes
the axes, a function that builds the module for one point, and a key derivation, and builds
every point.
import { compile, variantFamily } from 'typeshade'
const family = variantFamily({ axes: { elevation: ['flat', 'dem'] }, build: ({ elevation }) => { const fileName = `terrain-${elevation}.shade.ts` return compile(read(fileName)!, { fileName, readDocument: read }).module }, key: ({ elevation }) => `terrain:${elevation}`,})
family.keys // ['terrain:flat', 'terrain:dem']family.emit('wgsl') // Map { 'terrain:flat' => '…', 'terrain:dem' => '…' }family.get('terrain:dem')?.reflection // that variant's own reflectionEvery variant carries its module, its own reflection and its key, and emit returns one
preprocessor-free source per key for either target. For a GLSL host that already owns the
define, emitGuarded lowers the same matrix into a single source with a generated #if
ladder, one arm per key, each arm the same code emit produces with the preamble every arm
shares hoisted above the ladder. variantFamily’s reference page covers that shape and
what it asks of the variants.
The identity of a specialized program
A specialized program is a different program, so every axis you specialize on has to appear in every key that names it. That means the id of a cached pipeline, and the id of a baked artifact that serves bytes without compiling again. The key takes the same facts the choice of file takes.
const keyFor = (hasElevation: boolean, method: number) => `${hasElevation ? 'dem' : 'flat'}:${method}`The failure a short key causes carries no error. A key that names less than the build
reads hands one variant’s compiled shader to another variant’s draw: it compiles, it links,
it renders, and the pixels are wrong. If you add an axis to a build, add it to the key in
the same commit. variantFamily asks for the key as a function of the axes, and throws
when two points produce the same key, which turns the same mistake into a build-time
error.