WGSL's library covers GLSL's under mostly the same names: trigonometry, clamp, mix, smoothstep, geometry (dot, cross, normalize, reflect), transpose, determinant, bit operations and packing:
// out: 6 x f32
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
out[0] = clamp(4.6 / 5, 0, 1); // a rating as a 0-1 fraction
out[1] = mix(14.99, 39.50, 0.25); // linear interpolation
out[2] = smoothstep(0.0, 1.0, 0.25); // eased interpolation
out[3] = fract(18.75);
out[4] = atan2(1.0, 1.0) * 4; // pi
out[5] = length(vec2f(3, 4));
}out: 0.9200000166893005, 21.11750030517578, 0.15625, 0.75, 3.1415927410125732, 5
Texture functions (textureSample, textureLoad, textureStore, Textures and Samplers) take texture and sampler separately. Derivatives (dpdx, dpdy, fwidth) compare neighboring pixels, so they exist only in fragment shaders ("built-in cannot be used by compute pipeline stage"). Sampling uses derivatives too, so both must run in uniform control flow, which the compiler must prove:
// out: 0 x u32
@group(0) @binding(0) var cover: texture_2d<f32>;
@group(0) @binding(1) var linear: sampler;
@fragment fn fs(@location(0) uv: vec2f) -> @location(0) vec4f {
if (uv.x > 0.5) {
return textureSample(cover, linear, uv);
}
return vec4f(0.08, 0.40, 0.75, 1);
}6:12 error: 'textureSample' must only be called from uniform control flow 5:3 info: control flow depends on possibly non-uniform value 5:7 info: user-defined input 'uv' of 'fs' may be non-uniform
Sample first and choose afterwards with select(), or use textureSampleLevel(), which needs no derivatives; both versions compiled cleanly.
<!doctype html>
<style>
body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
.stage { position: relative; width: 100%; max-width: 600px; }
.stage canvas { display: block; width: 100%; }
.stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
<canvas id="view" width="600" height="384"></canvas>
<canvas id="labels" width="600" height="384"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');
function showMessage(text) { // 2D fallback when WebGPU is missing
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}
function label(text, x, y, size = 12, color = '#2b2b2b', font = 'ui-monospace, monospace') {
ink.font = `${size}px ${font}`; ink.fillStyle = color; ink.fillText(text, x, y);
}
// Six plots in a 3 x 2 grid. Each curve's distance is divided by fwidth(), a derivative:
// how much the value changes to the neighbouring pixel, so every line is about 2 px wide.
const plots = /* wgsl */ `
@vertex fn vs(@builtin(vertex_index) v: u32) -> @builtin(position) vec4f {
let p = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3))[v];
return vec4f(p, 0, 1);
}
fn curve(which: u32, x: f32) -> f32 {
switch which {
case 0u: { return clamp(x * 1.6 - 0.3, 0, 1); }
case 1u: { return mix(0.2, 0.9, x); }
case 2u: { return smoothstep(0.0, 1.0, x); }
case 3u: { return fract(x * 3); }
case 4u: { return 0.5 + 0.45 * sin(x * 12.566); }
default: { return length(vec2f(x - 0.5, 0.3)) * 1.5; }
}
}
@fragment fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f {
let cell = vec2u(pos.xy / vec2f(200, 160));
let uv = fract(pos.xy / vec2f(200, 160));
let x = (uv.x - 0.08) / 0.84;
let y = 1 - (uv.y - 0.2) / 0.72; // plot area inside each cell
let which = cell.x + cell.y * 3;
let d = y - curve(which, x);
let line = 1 - clamp(abs(d) / fwidth(d) - 0.5, 0, 1); // derivative-based anti-aliasing
let inside = x >= 0 && x <= 1 && y >= 0 && y <= 1;
var color = vec3f(0.97, 0.96, 0.93);
if (inside) {
let grid = step(0.98, fract(x * 4)) + step(0.98, fract(y * 4));
color = mix(vec3f(1), vec3f(0.88), clamp(grid, 0, 1));
color = mix(color, vec3f(0.08, 0.40, 0.75), line);
}
return vec4f(color, 1);
}`;
const lab = /* wgsl */ `
@group(0) @binding(0) var<storage, read_write> out: array<f32>;
@compute @workgroup_size(1) fn main() {
out[0] = clamp(4.6 / 5, 0, 1); // a rating as a 0-1 fraction
out[1] = mix(14.99, 39.50, 0.25); // linear interpolation
out[2] = smoothstep(0.0, 1.0, 0.25); // eased interpolation
out[3] = fract(18.75);
out[4] = atan2(1.0, 1.0) * 4; // pi
out[5] = length(vec2f(3, 4));
}`;
const branchy = /* wgsl */ `
@group(0) @binding(0) var cover: texture_2d<f32>;
@group(0) @binding(1) var linear: sampler;
@fragment fn fs(@location(0) uv: vec2f) -> @location(0) vec4f {
if (uv.x > 0.5) { return textureSample(cover, linear, uv); }
return vec4f(0.08, 0.40, 0.75, 1);
}`;
async function main() {
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) return showMessage('WebGPU is not available in this browser');
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format });
device.pushErrorScope('validation'); // textureSample in non-uniform flow: expected error
const uniformity = (await device.createShaderModule({ code: branchy }).getCompilationInfo()).messages.find((m) => m.type === 'error');
await device.popErrorScope();
const module = device.createShaderModule({ code: plots });
const render = device.createRenderPipeline({ layout: 'auto', vertex: { module }, fragment: { module, targets: [{ format }] } });
const B = GPUBufferUsage;
const out = device.createBuffer({ size: 24, usage: B.STORAGE | B.COPY_SRC });
const read = device.createBuffer({ size: 24, usage: B.COPY_DST | B.MAP_READ });
const compute = device.createComputePipeline({ layout: 'auto', compute: { module: device.createShaderModule({ code: lab }) } });
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
pass.setPipeline(render);
pass.setViewport(0, 0, 600, 320, 0, 1);
pass.draw(3);
pass.end();
const cp = encoder.beginComputePass();
cp.setPipeline(compute);
cp.setBindGroup(0, device.createBindGroup({ layout: compute.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: out } }] }));
cp.dispatchWorkgroups(1);
cp.end();
encoder.copyBufferToBuffer(out, 0, read, 0, 24);
device.queue.submit([encoder.finish()]);
await read.mapAsync(GPUMapMode.READ);
const v = [...new Float32Array(read.getMappedRange())].map((x) => +x.toFixed(4));
read.unmap();
['clamp(1.6x - 0.3, 0, 1)', 'mix(0.2, 0.9, x)', 'smoothstep(0, 1, x)', 'fract(3x)', '0.5 + 0.45 sin(4 pi x)', 'length(vec2f(x - .5, .3))']
.forEach((t, i) => label(t, 18 + (i % 3) * 200, 22 + Math.floor(i / 3) * 160, 11.5, '#222'));
label(`compute: clamp ${v[0]}, mix ${v[1]}, smoothstep ${v[2]}, fract ${v[3]}, atan2*4 ${v[4]}, length ${v[5]}`, 8, 340, 11, '#1f4f8a');
label('textureSample() inside if (uv.x > 0.5), a branch on a varying:', 8, 358, 11, '#8a2b2b');
label(uniformity ? uniformity.message : 'compiled', 8, 374, 11, '#8a2b2b');
}
main();
</script>