Control flow
On this page

Rendered from AUTHORING.md at commit af54ddad5. The package is imported here by its 0.2.0 name, typeshade.

Control flow

After this page you can branch, loop and dispatch inside a shader body, and you can tell a statement that picks what to do from an expression that picks a value. Each form is TypeScript’s own, and each emits the WGSL and GLSL statement of the same shape.

if, else if and else

if takes a bool. There is no truthiness: if (n) on a number is refused, so write the comparison, if (n != 0).

if (idx == 1) {
pos = vec2(3., -1.);
} else if (idx == 2) {
pos = vec2(-1., 3.);
} else {
pos = vec2(-1., -1.);
}

! is logical negation, so a guard on the false case reads if (!hit).

for and while

A for means what it means in TypeScript. The compiler records it as a counted loop when it has an integer counter, a constant step, and an exit that compares the counter to a bound the body does not write. The bound may be a value the program learns at run time, a uniform, a parameter or a storage array’s .length. Any other for is an open loop, as a while is.

let acc = 0.;
for (let i: u32 = 0; i < 64; i++) {
acc += f32(i);
}

The counter needs no annotation when its start is a non-negative literal and the bound is a u32; otherwise it is an i32. When the start, the bound and the step are constants, a step that moves the counter away from its bound is refused with TS8007, because the loop would not exit. while (cond) is the open loop, for a loop with no counter.

let n: u32 = start;
let steps: u32 = 0;
while (n != 1) {
n = select(n / 2, 3 * n + 1, (n & 1) == 1);
steps++;
}

docs/use-typeshade-surface.md §17 has every loop header the compiler takes, and why it refuses the rest.

Break, continue and discard

Three statements end a piece of work early. break exits the nearest enclosing loop, or the current switch case. continue skips to the next iteration of the nearest enclosing loop. discard kills the current fragment invocation with no colour or depth write, and belongs in a fragment stage.

"use typeshade";
declare const dists: storage<array<f32>>;
@fragment
export function fs(alpha: location<0, f32>, count: location<1, u32, { interpolate: "flat" }>): vec4 {
let nearest = 1e10;
for (let i: u32 = 0; i < count; i++) {
const d = dists[i];
if (d < 0.) {
continue; // no distance recorded, next iteration
}
if (d < 0.001) {
break; // close enough, leave the loop
}
nearest = min(nearest, d);
}
if (alpha < 0.01) {
discard;
}
return vec4(nearest, 0., 0., alpha);
}

discard is allowed in a fragment entry, and in a helper as long as no vertex or compute entry can reach it: the check closes over the call graph, and a refusal names the helper and the entry.

Switch

switch dispatches on a single integer value, the scrutinee, which is an i32 or a u32. Each case label is a constant, and default is the optional fall-through arm. It lowers to a real switch on both targets.

let radiusPx = rawRadius;
switch (sizeMode) {
case 1:
radiusPx = rawRadius / viewport.z;
break;
case 2:
radiusPx = rawRadius * dpr;
break;
default:
break;
}

A case ends in break or return. WGSL has no fall-through, so a case that runs into the next one is refused with the remedy.

Choosing a value

The ternary c ? a : b picks a value by a condition. It is WGSL’s select, so both arms are evaluated and one is chosen, which suits a pair of cheap values:

const dir = segLen < 1e-6 ? vec2(1., 0.) : segVec / segLen;

When an arm is expensive, or a chain of conditions picks among several values, declare the variable and assign it in an if chain, so the GPU runs only the arm it takes:

let clip: vec4;
if (projParams.x < 0.5) {
clip = mvp * vec4(rel2d, 0., 1.);
} else if (projParams.x < 6.5) {
clip = mvp * vec4(relG, 0., 1.);
} else {
clip = mvp * vec4(ecefRtc, 1.);
}

Folding a loop with reduce

An accumulator is a value carried from one iteration of a loop to the next. An array’s reduce carries one for you: xs.reduce(f, init) runs acc = f(acc, value, index) from init, left to right, as TypeScript runs it.

"use typeshade";
export function nearestOf(p: vec2, pts: array<vec2, 8>): f32 {
return pts.reduce((acc, q) => min(acc, length(p - q)), 1e10);
}

The call emits the loop and the variable it updates, the same code as writing let plus for plus the assignment yourself. map, forEach, some and every are there too, and all but map work on a runtime-sized storage array (docs/use-typeshade-surface.md §63).

Dispatch on an enum

A numeric enum declares a set of named integer constants, and each member is a module constant, so a member can stand in a case label:

"use typeshade";
enum Kind {
Line,
Fill,
Stroke,
}
export function colorOf(kind: i32, line: vec4, fill: vec4, stroke: vec4): vec4 {
switch (kind) {
case Kind.Line:
return line;
case Kind.Fill:
return fill;
default:
return stroke;
}
}

Kind.Fill reads the constant, 1, and the enum’s name as a type is i32. A member the enum does not declare is an error where it is read. A string member is refused, because no GPU type holds one.

Early returns

A return inside a branch or a loop leaves the function, as it does in TypeScript:

"use typeshade";
export function sign01(winding: i32, minDist: f32): f32 {
if (winding != 0) {
return 1. - minDist;
}
return 1. + minDist;
}

A function that returns a value must return one on every path. A path that falls off the end of a value-returning function is an error at compile.

Edit this page Report a problem