feat(core): widget.gpu, the WebGPU subset for live widgets, with host checks and conformance fixtures

The prelude records WebGPU's API (devices, contexts by canvas key, resources, pipelines, bind
groups, command encoders and passes) into batches of ops and bytes with prelude-assigned handles
and every default filled in; batches ride frame requests, or go before other waits and at the
end. device.lost, unavailable GPUs and encoder misuse (error ops) are handled.
The TypeScript host (LiveWidget) passes { available, format } in the live input and checks
batches without a GPU: op shapes, handles and limits, with exact messages; an error stops the
canvases its batch renders into, else all. GPU batches never overtake waiting renders or draws.
widgets-gpu.md gains the normalised op shapes, the host checks and the conformance driver;
test/fixtures/gpu holds 34 fixtures, among them four example widget templates (a lit cube, a
textured quad, post-processing, a first-person maze).
This commit is contained in:
OpenCode Agent 2026-11-22 23:51:45 +00:00
parent cb1e19652c
commit 0786c7331c
52 changed files with 23967 additions and 32 deletions

View file

@ -33,7 +33,7 @@ or `invalid`); keep the previous state and view and show the message inline.
## Live mode
A widget template with `mode: "live"` defines `async function main(data)` and runs as one long program per open widget:
`<program>\nreturn await __widget_live(__input(), true)` with `__input()` = `{ data }` and the host functions `__host.post`,
`<program>\nreturn await __widget_live(__input(), true)` with `__input()` = `{ data, gpu }` and the host functions `__host.post`,
`__host.receive`, `__host.sleep`, `__host.now` and `__host.fetch` (see `specs/v2/widgets-live.md` for the messages,
pausing and budgets). The prelude builds the program-facing `widget` object on them; model guidance with examples is
in `docs/live-guidance.md`.

View file

@ -0,0 +1,102 @@
// Writes test/fixtures/gpu/*.json (specs/v2/widgets-gpu.md, Conformance): for each program in
// test/fixtures/gpu-cases.ts, the batches it posts, run on the TypeScript host under the fixtures' driver, and the
// program errors (phase `gpu`) the host's checks give. Run `bun run script/gpu-conformance.ts` only to regenerate them
// from a prelude and host known to be right.
import path from "node:path"
import { type LiveInput, LiveWidget, ManualClock, program } from "../src/index.js"
import { type GpuCase, gpuCases, rawCases } from "../test/fixtures/gpu-cases.js"
const dir = path.resolve(import.meta.dir, "../test/fixtures/gpu")
/** The GPU the fixtures' host has. */
export const GPU = { available: true, format: "rgba8unorm" } as const
/** The frames the driver delivers: frame `i` at `t = i / 60`, on a canvas 300 x 200 at scale 2. */
const frame = (i: number) => ({ t: i / 60, dt: 1 / 60, width: 300, height: 200, scale: 2, pointer: null, dark: false })
/** The most frames a fixture runs. */
const FRAMES = 10
export interface Recorded {
readonly batches: ReadonlyArray<{ readonly frame: boolean; readonly ops: unknown; readonly bytes: string }>
readonly errors: ReadonlyArray<{ readonly message: string; readonly canvases: ReadonlyArray<string> | "all" }>
readonly end: string
}
/**
* Runs a case the way the fixtures' driver does: the canvas sizes before anything else, then while the program asks for
* frames, each fixture input for frame `i` and frame `i`; it stops when the program ends, or settles without asking
* for a frame, or after `FRAMES` frames. Timers run on a clock that moves 1/60 s at a time while the program waits.
*/
export async function run(item: GpuCase): Promise<Recorded> {
const clock = new ManualClock()
const batches: Array<{ frame: boolean; ops: unknown; bytes: string }> = []
const widget = LiveWidget.start(program(item.source), item.data ?? null, {
clock,
// GPU programs, not budgets: no 50 ms slice.
busyMs: 600_000,
gpu: { format: GPU.format },
onMessage: (message) => {
const batch = message.type === "frame" ? message.gpu : message.type === "gpu" ? message : undefined
if (batch)
batches.push({
frame: message.type === "frame",
ops: batch.ops,
bytes: Buffer.from(batch.bytes).toString("base64"),
})
},
})
item.canvases.forEach((canvas) => widget.canvas(canvas.key, canvas.width, canvas.height))
// Until the program asks for a frame or ends: it may be computing (real time) or sleeping (the clock).
const settle = async () => {
for (let step = 0; step < 10 && !widget.ended && !widget.frameRequested; step++) {
await Promise.race([widget.when((c) => c.frameRequested).catch(() => undefined), Bun.sleep(50)])
if (!widget.frameRequested) await clock.advance(1000 / 60)
}
}
for (let i = 0; i < FRAMES; i++) {
await settle()
if (widget.ended || !widget.frameRequested) break
for (const { input } of (item.inputs ?? []).filter((entry) => entry.frame === i)) {
const given = input as LiveInput
if (given.type === "event") widget.event(given.event)
if (given.type === "canvas") widget.canvas(given.key, given.width, given.height)
}
widget.frame(frame(i))
}
await settle()
const end = widget.ended ?? (await widget.stop())
return {
batches,
errors: widget.gpuErrors.map((error) => ({ message: error.message, canvases: error.canvases })),
end: end.type === "error" ? `error: ${end.error.message}` : end.type,
}
}
// JSON, two spaces deep, with one op per line.
function format(file: Record<string, unknown>) {
const { batches, ...rest } = file as { batches?: Recorded["batches"] }
const head = JSON.stringify(rest, null, 2).slice(0, -2)
if (!batches) return head + "\n}\n"
const body = batches.map(
(batch) =>
` {\n "frame": ${batch.frame},\n "bytes": ${JSON.stringify(batch.bytes)},\n "ops": [\n` +
(batch.ops as ReadonlyArray<unknown>).map((op) => ` ${JSON.stringify(op)}`).join(",\n") +
`\n ]\n }`,
)
return `${head},\n "batches": [\n${body.join(",\n")}\n ]\n}\n`
}
export const fixtures = (): ReadonlyArray<GpuCase & { readonly raw: boolean }> => [
...gpuCases.map((item) => ({ ...item, raw: false })),
...rawCases.map((item) => ({ ...item, raw: true })),
]
if (import.meta.main) {
for (const item of fixtures()) {
const recorded = await run(item)
// A raw case's batch is in its source.
const { batches, ...rest } = recorded
const file = { ...item, raw: undefined, gpu: GPU, ...(item.raw ? {} : { batches }), ...rest }
await Bun.write(path.join(dir, `${item.name}.json`), format(file))
}
console.log(`wrote ${fixtures().length} fixtures to ${dir}`)
}

611
packages/widget/src/gpu.ts Normal file
View file

@ -0,0 +1,611 @@
// GPU batch checks a host makes without a GPU (specs/v2/widgets-gpu.md, Host checks): every op's shape, the handles
// it names, and the limits. A host with a GPU replays what passes; the TypeScript host only checks.
/** A batch as the prelude posts it: ops, and the bytes they read. */
export interface GpuBatch {
readonly ops: ReadonlyArray<unknown>
readonly bytes: ArrayBuffer
}
/** A program error from a batch (phase `gpu`): the canvases it stops, by key, or every canvas of the device. */
export interface GpuError {
readonly message: string
readonly canvases: ReadonlyArray<string> | "all"
}
export const GPU_LIMITS = {
ops: 20_000,
bytes: 4 * 1024 * 1024,
passes: 16,
draws: 10_000,
handles: 4096,
resources: 256 * 1024 * 1024,
shader: 256 * 1024,
buffer: 64 * 1024 * 1024,
dimension: 4096,
layers: 256,
}
const TEXTURE_FORMATS: Record<string, number> = {
rgba8unorm: 4,
"rgba8unorm-srgb": 4,
bgra8unorm: 4,
r8unorm: 1,
rgba16float: 8,
depth24plus: 4,
depth32float: 4,
}
const COLOR_FORMATS = ["rgba8unorm", "rgba8unorm-srgb", "bgra8unorm", "r8unorm", "rgba16float"]
const DEPTH_FORMATS = ["depth24plus", "depth32float"]
const VERTEX_FORMATS = [
"uint8x2",
"uint8x4",
"sint8x2",
"sint8x4",
"unorm8x2",
"unorm8x4",
"snorm8x2",
"snorm8x4",
"uint16x2",
"uint16x4",
"sint16x2",
"sint16x4",
"unorm16x2",
"unorm16x4",
"snorm16x2",
"snorm16x4",
"float16x2",
"float16x4",
"float32",
"float32x2",
"float32x3",
"float32x4",
"uint32",
"uint32x2",
"uint32x3",
"uint32x4",
"sint32",
"sint32x2",
"sint32x3",
"sint32x4",
]
const COMPARE = ["never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always"]
const FACTORS = [
"zero",
"one",
"src",
"one-minus-src",
"src-alpha",
"one-minus-src-alpha",
"dst",
"one-minus-dst",
"dst-alpha",
"one-minus-dst-alpha",
"src-alpha-saturated",
"constant",
"one-minus-constant",
]
const BUFFER_USAGE = { COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128 }
const TEXTURE_USAGE = { COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 }
const STAGES = { VERTEX: 1, FRAGMENT: 2 }
class Invalid extends Error {}
const fail = (message: string): never => {
throw new Invalid(message)
}
type Kind =
| "context"
| "buffer"
| "texture"
| "view"
| "sampler"
| "shader"
| "bindGroupLayout"
| "pipelineLayout"
| "renderPipeline"
| "bindGroup"
interface Handle {
readonly kind: Kind
/** A buffer's or texture's bytes as allocated; a view's texture; a context's key. */
readonly bytes?: number
readonly texture?: number
readonly key?: string
destroyed?: boolean
}
// Checks one value at `path` ("<op>" argument <i>, then .field and [index]).
const whole = (value: unknown, path: string) =>
typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fail(`${path} must be a whole number`)
const wholeOrAll = (value: unknown, path: string) =>
value === -1
? -1
: typeof value === "number" && Number.isInteger(value) && value >= 0
? value
: fail(`${path} must be a whole number or -1`)
const integer = (value: unknown, path: string) =>
typeof value === "number" && Number.isInteger(value) ? value : fail(`${path} must be an integer`)
const finite = (value: unknown, path: string) =>
typeof value === "number" && Number.isFinite(value) ? value : fail(`${path} must be a finite number`)
const bool = (value: unknown, path: string) =>
typeof value === "boolean" ? value : fail(`${path} must be true or false`)
const text = (value: unknown, path: string) => (typeof value === "string" ? value : fail(`${path} must be a string`))
const oneOf = <A>(value: unknown, options: ReadonlyArray<A>, path: string) =>
options.includes(value as A) ? (value as A) : fail(`${path} must be one of ${options.join(", ")}`)
const list = (value: unknown, path: string, length?: number) =>
Array.isArray(value) && (length === undefined || value.length === length)
? value
: fail(length === undefined ? `${path} must be a list` : `${path} must be a list of ${length}`)
const record = (value: unknown, path: string) =>
value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: fail(`${path} must be an object`)
const nullable = <A>(value: unknown, check: (value: unknown) => A) => (value === null ? null : check(value))
const flags = (value: unknown, names: Record<string, number>, path: string) => {
const all = Object.values(names).reduce((sum, bit) => sum | bit, 0)
return typeof value === "number" && Number.isInteger(value) && value >= 0 && (value & ~all) === 0
? value
: fail(`${path} must combine ${Object.keys(names).join(", ")}`)
}
const limit = (value: number, max: number, what: string) =>
value > max ? fail(`${what} is over the limit of ${max}`) : value
// The ops: their number of arguments after the name.
const ARITY: Record<string, number> = {
context: 4,
buffer: 3,
texture: 8,
view: 3,
sampler: 2,
shader: 2,
bindGroupLayout: 2,
pipelineLayout: 2,
renderPipeline: 2,
autoLayout: 3,
bindGroup: 2,
destroy: 1,
writeBuffer: 4,
writeTexture: 8,
copyBufferToBuffer: 5,
copyBufferToTexture: 8,
copyTextureToTexture: 7,
pass: 1,
setPipeline: 1,
setBindGroup: 3,
setVertexBuffer: 4,
setIndexBuffer: 4,
setViewport: 6,
setScissorRect: 4,
draw: 4,
drawIndexed: 5,
end: 0,
submit: 0,
error: 1,
}
const IN_PASS = new Set([
"setPipeline",
"setBindGroup",
"setVertexBuffer",
"setIndexBuffer",
"setViewport",
"setScissorRect",
"draw",
"drawIndexed",
"end",
])
/**
* The checks of a widget's batches, in order. `canvases` gives the keys of the GPU canvases in the last rendered view.
* A batch gives its first error, or none, and the rest of it goes unchecked. The error stops the canvases the batch
* renders into (a pass's color attachment is a view of their texture), or every GPU canvas of the widget when it renders
* into none; then later batches go unchecked. An error stopping only canvases already stopped isn't given again.
*/
export function gpuChecks(canvases: () => ReadonlySet<string>) {
const handles = new Map<number, Handle>()
const state = { last: 0, live: 0, resources: 0, passes: 0, draws: 0, all: false }
const stopped = new Set<string>()
const find = (value: unknown, path: string, ...kinds: ReadonlyArray<Kind>) => {
const h = whole(value, path)
const found = handles.get(h) ?? fail(`no handle ${h}`)
if (!kinds.includes(found.kind)) fail(`handle ${h} is a ${found.kind}, not a ${kinds.join(" or ")}`)
if (found.destroyed) fail(`handle ${h} was destroyed`)
return found
}
const create = (value: unknown, path: string, made: Handle) => {
const h = whole(value, path)
if (h <= state.last) fail(`handle ${h} was already used`)
state.last = h
handles.set(h, made)
limit(++state.live, GPU_LIMITS.handles, "the number of live handles")
if (made.bytes) limit((state.resources += made.bytes), GPU_LIMITS.resources, "the size of buffers and textures")
}
const free = (h: number, found: Handle) => {
found.destroyed = true
state.live--
state.resources -= found.bytes ?? 0
for (const [, other] of handles)
if (other.kind === "view" && other.texture === h && !other.destroyed) {
other.destroyed = true
state.live--
}
}
const range = (offset: number, length: number, bytes: ArrayBuffer) =>
offset + length > bytes.byteLength
? fail(`bytes [${offset}, ${offset + length}) are outside the batch's ${bytes.byteLength} bytes`)
: undefined
const triple = (value: unknown, path: string) =>
list(value, path, 3).forEach((item, i) => whole(item, `${path}[${i}]`))
const op = (o: ReadonlyArray<unknown>, name: string, bytes: ArrayBuffer) => {
const a = (i: number) => `"${name}" argument ${i}`
switch (name) {
case "context": {
const key = text(o[2], a(2))
oneOf(o[3], ["bgra8unorm", "rgba8unorm"], a(3))
oneOf(o[4], ["opaque", "premultiplied"], a(4))
if (!canvases().has(key)) fail(`no GPU canvas with key "${key}"`)
const existing = handles.get(whole(o[1], a(1)))
if (existing?.kind === "context" && existing.key === key) return
return create(o[1], a(1), { kind: "context", key })
}
case "buffer": {
const size = limit(whole(o[2], a(2)), GPU_LIMITS.buffer, a(2))
flags(o[3], BUFFER_USAGE, a(3))
return create(o[1], a(1), { kind: "buffer", bytes: size })
}
case "texture": {
const width = limit(whole(o[2], a(2)), GPU_LIMITS.dimension, a(2))
const height = limit(whole(o[3], a(3)), GPU_LIMITS.dimension, a(3))
const layers = limit(whole(o[4], a(4)), GPU_LIMITS.layers, a(4))
const format = oneOf(o[5], Object.keys(TEXTURE_FORMATS), a(5))
flags(o[6], TEXTURE_USAGE, a(6))
const mips = whole(o[7], a(7))
const samples = oneOf(o[8], [1, 4], a(8))
let bytes = 0
for (let mip = 0; mip < mips; mip++)
bytes += Math.max(1, width >> mip) * Math.max(1, height >> mip) * layers * TEXTURE_FORMATS[format]! * samples
return create(o[1], a(1), { kind: "texture", bytes })
}
case "view": {
const texture = whole(o[2], a(2))
find(texture, a(2), "texture", "context")
const d = record(o[3], a(3))
oneOf(d.dimension, ["2d", "2d-array", "cube"], `${a(3)}.dimension`)
for (const field of ["baseMipLevel", "mipLevelCount", "baseArrayLayer", "arrayLayerCount"])
whole(d[field], `${a(3)}.${field}`)
return create(o[1], a(1), { kind: "view", texture })
}
case "sampler": {
const d = record(o[2], a(2))
for (const field of ["addressModeU", "addressModeV", "addressModeW"])
oneOf(d[field], ["clamp-to-edge", "repeat", "mirror-repeat"], `${a(2)}.${field}`)
for (const field of ["magFilter", "minFilter", "mipmapFilter"])
oneOf(d[field], ["nearest", "linear"], `${a(2)}.${field}`)
finite(d.lodMinClamp, `${a(2)}.lodMinClamp`)
finite(d.lodMaxClamp, `${a(2)}.lodMaxClamp`)
nullable(d.compare, (value) => oneOf(value, COMPARE, `${a(2)}.compare`))
whole(d.maxAnisotropy, `${a(2)}.maxAnisotropy`)
return create(o[1], a(1), { kind: "sampler" })
}
case "shader": {
limit(new TextEncoder().encode(text(o[2], a(2))).length, GPU_LIMITS.shader, a(2))
return create(o[1], a(1), { kind: "shader" })
}
case "bindGroupLayout": {
const d = record(o[2], a(2))
list(d.entries, `${a(2)}.entries`).forEach((item, i) => {
const at = `${a(2)}.entries[${i}]`
const e = record(item, at)
whole(e.binding, `${at}.binding`)
flags(e.visibility, STAGES, `${at}.visibility`)
if ([e.buffer, e.sampler, e.texture].filter((value) => value !== null).length !== 1)
fail(`${at} needs exactly one of buffer, sampler and texture`)
nullable(e.buffer, (value) => {
const b = record(value, `${at}.buffer`)
oneOf(b.type, ["uniform", "storage", "read-only-storage"], `${at}.buffer.type`)
bool(b.hasDynamicOffset, `${at}.buffer.hasDynamicOffset`)
whole(b.minBindingSize, `${at}.buffer.minBindingSize`)
})
nullable(e.sampler, (value) =>
oneOf(
record(value, `${at}.sampler`).type,
["filtering", "non-filtering", "comparison"],
`${at}.sampler.type`,
),
)
nullable(e.texture, (value) => {
const t = record(value, `${at}.texture`)
oneOf(t.sampleType, ["float", "unfilterable-float", "depth", "sint", "uint"], `${at}.texture.sampleType`)
oneOf(t.viewDimension, ["2d", "2d-array", "cube"], `${at}.texture.viewDimension`)
bool(t.multisampled, `${at}.texture.multisampled`)
})
})
return create(o[1], a(1), { kind: "bindGroupLayout" })
}
case "pipelineLayout": {
list(o[2], a(2)).forEach((item, i) => find(item, `${a(2)}[${i}]`, "bindGroupLayout"))
return create(o[1], a(1), { kind: "pipelineLayout" })
}
case "renderPipeline": {
pipeline(record(o[2], a(2)), a(2))
return create(o[1], a(1), { kind: "renderPipeline" })
}
case "autoLayout": {
find(o[2], a(2), "renderPipeline")
whole(o[3], a(3))
return create(o[1], a(1), { kind: "bindGroupLayout" })
}
case "bindGroup": {
const d = record(o[2], a(2))
find(d.layout, `${a(2)}.layout`, "bindGroupLayout")
list(d.entries, `${a(2)}.entries`).forEach((item, i) => {
const at = `${a(2)}.entries[${i}]`
const e = record(item, at)
whole(e.binding, `${at}.binding`)
const r = record(e.resource, `${at}.resource`)
if ("buffer" in r) {
find(r.buffer, `${at}.resource.buffer`, "buffer")
whole(r.offset, `${at}.resource.offset`)
wholeOrAll(r.size, `${at}.resource.size`)
} else if ("sampler" in r) find(r.sampler, `${at}.resource.sampler`, "sampler")
else if ("view" in r) find(r.view, `${at}.resource.view`, "view")
else fail(`${at}.resource must be a buffer binding, a sampler or a view`)
})
return create(o[1], a(1), { kind: "bindGroup" })
}
case "destroy": {
const h = whole(o[1], a(1))
return free(h, find(h, a(1), "buffer", "texture"))
}
case "writeBuffer":
find(o[1], a(1), "buffer")
whole(o[2], a(2))
return range(whole(o[3], a(3)), whole(o[4], a(4)), bytes)
case "writeTexture":
find(o[1], a(1), "texture")
whole(o[2], a(2))
triple(o[3], a(3))
range(whole(o[4], a(4)), whole(o[5], a(5)), bytes)
whole(o[6], a(6))
nullable(o[7], (value) => whole(value, a(7)))
return triple(o[8], a(8))
case "copyBufferToBuffer":
find(o[1], a(1), "buffer")
whole(o[2], a(2))
find(o[3], a(3), "buffer")
whole(o[4], a(4))
return void whole(o[5], a(5))
case "copyBufferToTexture":
find(o[1], a(1), "buffer")
whole(o[2], a(2))
whole(o[3], a(3))
nullable(o[4], (value) => whole(value, a(4)))
find(o[5], a(5), "texture")
whole(o[6], a(6))
triple(o[7], a(7))
return triple(o[8], a(8))
case "copyTextureToTexture":
find(o[1], a(1), "texture")
whole(o[2], a(2))
triple(o[3], a(3))
find(o[4], a(4), "texture")
whole(o[5], a(5))
triple(o[6], a(6))
return triple(o[7], a(7))
case "setPipeline":
return void find(o[1], a(1), "renderPipeline")
case "setBindGroup":
whole(o[1], a(1))
find(o[2], a(2), "bindGroup")
return list(o[3], a(3)).forEach((item, i) => whole(item, `${a(3)}[${i}]`))
case "setVertexBuffer":
whole(o[1], a(1))
find(o[2], a(2), "buffer")
whole(o[3], a(3))
return void wholeOrAll(o[4], a(4))
case "setIndexBuffer":
find(o[1], a(1), "buffer")
oneOf(o[2], ["uint16", "uint32"], a(2))
whole(o[3], a(3))
return void wholeOrAll(o[4], a(4))
case "setViewport":
return [1, 2, 3, 4, 5, 6].forEach((i) => finite(o[i], a(i)))
case "setScissorRect":
return [1, 2, 3, 4].forEach((i) => whole(o[i], a(i)))
case "draw":
case "drawIndexed":
o.slice(1).forEach((value, i) => (name === "drawIndexed" && i === 3 ? integer : whole)(value, a(i + 1)))
return void limit(++state.draws, GPU_LIMITS.draws, "the number of draws in a frame")
}
}
const pipeline = (d: Record<string, unknown>, at: string) => {
if (d.layout !== "auto") find(d.layout, `${at}.layout`, "pipelineLayout")
const vertex = record(d.vertex, `${at}.vertex`)
find(vertex.module, `${at}.vertex.module`, "shader")
nullable(vertex.entryPoint, (value) => text(value, `${at}.vertex.entryPoint`))
list(vertex.buffers, `${at}.vertex.buffers`).forEach((item, i) =>
nullable(item, (value) => {
const path = `${at}.vertex.buffers[${i}]`
const b = record(value, path)
whole(b.arrayStride, `${path}.arrayStride`)
oneOf(b.stepMode, ["vertex", "instance"], `${path}.stepMode`)
list(b.attributes, `${path}.attributes`).forEach((attribute, j) => {
const where = `${path}.attributes[${j}]`
const t = record(attribute, where)
oneOf(t.format, VERTEX_FORMATS, `${where}.format`)
whole(t.offset, `${where}.offset`)
whole(t.shaderLocation, `${where}.shaderLocation`)
})
}),
)
nullable(d.fragment, (value) => {
const fragment = record(value, `${at}.fragment`)
find(fragment.module, `${at}.fragment.module`, "shader")
nullable(fragment.entryPoint, (entry) => text(entry, `${at}.fragment.entryPoint`))
list(fragment.targets, `${at}.fragment.targets`).forEach((item, i) =>
nullable(item, (target) => {
const path = `${at}.fragment.targets[${i}]`
const t = record(target, path)
oneOf(t.format, COLOR_FORMATS, `${path}.format`)
nullable(t.blend, (blend) => {
const b = record(blend, `${path}.blend`)
for (const part of ["color", "alpha"]) {
const c = record(b[part], `${path}.blend.${part}`)
oneOf(
c.operation,
["add", "subtract", "reverse-subtract", "min", "max"],
`${path}.blend.${part}.operation`,
)
oneOf(c.srcFactor, FACTORS, `${path}.blend.${part}.srcFactor`)
oneOf(c.dstFactor, FACTORS, `${path}.blend.${part}.dstFactor`)
}
})
limit(whole(t.writeMask, `${path}.writeMask`), 15, `${path}.writeMask`)
}),
)
})
const primitive = record(d.primitive, `${at}.primitive`)
oneOf(
primitive.topology,
["point-list", "line-list", "line-strip", "triangle-list", "triangle-strip"],
`${at}.primitive.topology`,
)
nullable(primitive.stripIndexFormat, (value) =>
oneOf(value, ["uint16", "uint32"], `${at}.primitive.stripIndexFormat`),
)
oneOf(primitive.frontFace, ["ccw", "cw"], `${at}.primitive.frontFace`)
oneOf(primitive.cullMode, ["none", "front", "back"], `${at}.primitive.cullMode`)
nullable(d.depthStencil, (value) => {
const depth = record(value, `${at}.depthStencil`)
oneOf(depth.format, DEPTH_FORMATS, `${at}.depthStencil.format`)
bool(depth.depthWriteEnabled, `${at}.depthStencil.depthWriteEnabled`)
oneOf(depth.depthCompare, COMPARE, `${at}.depthStencil.depthCompare`)
})
const multisample = record(d.multisample, `${at}.multisample`)
oneOf(multisample.count, [1, 4], `${at}.multisample.count`)
whole(multisample.mask, `${at}.multisample.mask`)
bool(multisample.alphaToCoverageEnabled, `${at}.multisample.alphaToCoverageEnabled`)
}
// The keys of the canvases a batch renders into, in order, from what it and earlier batches made.
const rendered = (ops: ReadonlyArray<unknown>) => {
const textures = new Map<number, number>()
const contexts = new Map<number, string>()
const keys = new Set<string>()
const context = (h: number | undefined) => {
const found = h === undefined ? undefined : handles.get(h)
return h === undefined ? undefined : (contexts.get(h) ?? (found?.kind === "context" ? found.key : undefined))
}
for (const o of ops) {
if (!Array.isArray(o) || typeof o[1] !== "number") continue
if (o[0] === "context" && typeof o[2] === "string") contexts.set(o[1], o[2])
if (o[0] === "view" && typeof o[2] === "number") textures.set(o[1], o[2])
}
for (const o of ops) {
if (!Array.isArray(o) || o[0] !== "pass" || !o[1] || !Array.isArray(o[1].colorAttachments)) continue
for (const attachment of o[1].colorAttachments) {
const view = attachment?.view
if (typeof view !== "number") continue
const key = context(textures.get(view) ?? handles.get(view)?.texture)
if (key !== undefined) keys.add(key)
}
}
return [...keys]
}
// A pass's descriptor, checked.
const pass = (value: unknown) => {
const at = `"pass" argument 1`
const d = record(value, at)
list(d.colorAttachments, `${at}.colorAttachments`).forEach((item, i) =>
nullable(item, (attachment) => {
const path = `${at}.colorAttachments[${i}]`
const c = record(attachment, path)
find(c.view, `${path}.view`, "view")
nullable(c.resolveTarget, (resolve) => find(resolve, `${path}.resolveTarget`, "view"))
list(c.clearValue, `${path}.clearValue`, 4).forEach((part, j) => finite(part, `${path}.clearValue[${j}]`))
oneOf(c.loadOp, ["load", "clear"], `${path}.loadOp`)
oneOf(c.storeOp, ["store", "discard"], `${path}.storeOp`)
}),
)
nullable(d.depthStencilAttachment, (attachment) => {
const path = `${at}.depthStencilAttachment`
const depth = record(attachment, path)
find(depth.view, `${path}.view`, "view")
nullable(depth.depthClearValue, (clear) => finite(clear, `${path}.depthClearValue`))
nullable(depth.depthLoadOp, (load) => oneOf(load, ["load", "clear"], `${path}.depthLoadOp`))
nullable(depth.depthStoreOp, (store) => oneOf(store, ["store", "discard"], `${path}.depthStoreOp`))
bool(depth.depthReadOnly, `${path}.depthReadOnly`)
})
limit(++state.passes, GPU_LIMITS.passes, "the number of render passes in a frame")
}
return {
/** Checks a batch; `frame`: it came with a frame request, which ends the frame its limits count. */
batch: (value: unknown, frame: boolean): GpuError | undefined => {
if (state.all) return undefined
const scoped = { keys: [] as string[], pass: false }
const error = (message: string): GpuError | undefined => {
if (scoped.keys.length > 0) {
const fresh = scoped.keys.filter((key) => !stopped.has(key))
scoped.keys.forEach((key) => stopped.add(key))
return fresh.length > 0 ? { message, canvases: fresh } : undefined
}
state.all = true
const fresh = [...canvases()].filter((key) => !stopped.has(key))
return fresh.length > 0 || stopped.size === 0 ? { message, canvases: "all" } : undefined
}
try {
const batch = record(value, "a batch")
const ops = list(batch.ops, "a batch's ops")
scoped.keys = rendered(ops)
if (!(batch.bytes instanceof ArrayBuffer)) fail("a batch's bytes must be an ArrayBuffer")
const bytes = batch.bytes as ArrayBuffer
limit(ops.length, GPU_LIMITS.ops, "the number of ops in a batch")
limit(bytes.byteLength, GPU_LIMITS.bytes, "the size of a batch's bytes")
for (let index = 0; index < ops.length; index++) {
try {
const o = ops[index]
if (!Array.isArray(o) || typeof o[0] !== "string") fail("an op is a list that starts with its name")
const list = o as ReadonlyArray<unknown>
const name = list[0] as string
const arity = Object.hasOwn(ARITY, name) ? ARITY[name]! : fail(`unknown op "${name}"`)
if (list.length !== arity + 1) fail(`"${name}" takes ${arity} arguments`)
if (name === "error") fail(text(list[1], `"error" argument 1`))
if (name === "pass") {
if (scoped.pass) fail(`"pass" inside a render pass`)
pass(list[1])
scoped.pass = true
continue
}
if (IN_PASS.has(name) && !scoped.pass) fail(`"${name}" outside a render pass`)
if (!IN_PASS.has(name) && scoped.pass) fail(`"${name}" inside a render pass`)
if (name === "end") scoped.pass = false
else op(list, name, bytes)
} catch (caught) {
if (!(caught instanceof Invalid)) throw caught
return error(`gpu op ${index}: ${caught.message}`)
}
}
if (scoped.pass) fail("a render pass is still open at the end of the batch")
return undefined
} catch (caught) {
if (!(caught instanceof Invalid)) throw caught
return error(caught.message)
} finally {
if (frame) {
state.passes = 0
state.draws = 0
}
}
},
/** The device is lost: every handle is gone. */
lost: () => {
handles.clear()
state.live = 0
state.resources = 0
},
}
}

View file

@ -18,6 +18,7 @@ import type { Capabilities } from "./widget-template.js"
import { type Tree, tree, unmark, ViewError } from "./tree.js"
import { compiled } from "./compiled.js"
import { located, MAX_VALUE_DEPTH, NEWER, OLDER, protocol, PROTOCOL } from "./host.js"
import { type GpuBatch, type GpuError, gpuChecks } from "./gpu.js"
/** A display frame in live mode: like a canvas frame, without the canvas id. */
export type LiveFrame = Omit<Frame, "id">
@ -26,7 +27,10 @@ export type LiveFrame = Omit<Frame, "id">
export type LiveMessage =
| { readonly type: "render"; readonly node: Node }
| { readonly type: "draw"; readonly id: string; readonly commands: ReadonlyArray<Command> }
| { readonly type: "frame" }
/** A frame request; it may carry the GPU batch recorded since the last one (widgets-gpu.md). */
| { readonly type: "frame"; readonly gpu?: GpuBatch }
/** A GPU batch on its own, posted before the program waits on something else than a frame. */
| ({ readonly type: "gpu" } & GpuBatch)
| { readonly type: "submit"; readonly value: unknown }
| { readonly type: "dismiss" }
| { readonly type: "send"; readonly value: unknown; readonly wake: boolean }
@ -38,6 +42,10 @@ export type LiveInput =
| { readonly type: "event"; readonly event: WidgetEvent }
| { readonly type: "frame"; readonly frame: LiveFrame }
| { readonly type: "resumed"; readonly pausedMs: number }
/** A GPU canvas's size in physical pixels, before the frame after it changed (widgets-gpu.md). */
| { readonly type: "canvas"; readonly key: string; readonly width: number; readonly height: number }
/** The GPU device is lost: every handle is gone. */
| { readonly type: "gpu"; readonly lost: string }
/** How a live program ended. `return`: `main` returned without an answer; its last view stays. */
export type LiveEnd =
@ -113,6 +121,11 @@ export interface LiveOptions {
readonly capabilities?: Capabilities
/** Performs `fetch` requests that passed the contract's checks; the platform `fetch` by default. */
readonly transport?: Transport
/**
* The GPU the program sees (widgets-gpu.md): by default one with `rgba8unorm` canvases, whose batches this host checks
* without replaying them (it draws no canvas); `false`: none, so the program records nothing.
*/
readonly gpu?: false | { readonly format?: "bgra8unorm" | "rgba8unorm" }
}
/**
@ -128,11 +141,17 @@ export interface LiveWidget {
readonly frameRequested: boolean
readonly paused: boolean
readonly warnings: ReadonlyArray<string>
/** The program errors (phase `gpu`) the GPU batches had, each with the canvases it stopped. */
readonly gpuErrors: ReadonlyArray<GpuError>
readonly ended: LiveEnd | undefined
readonly done: Promise<LiveEnd>
readonly event: (event: WidgetEvent) => void
/** Delivers a frame if the program asked for one and isn't paused; returns whether it did. */
readonly frame: (frame: LiveFrame) => boolean
/** Tells the program a GPU canvas's size, in physical pixels. */
readonly canvas: (key: string, width: number, height: number) => void
/** Loses the GPU device: every handle is gone, and the program's `device.lost` resolves. */
readonly loseDevice: (reason: string) => void
/**
* Holds everything for the program: events, timer firings and fetch results wait, and `now()` stops, until `resume`,
* which first delivers `{ type: "resumed", pausedMs }`.
@ -146,7 +165,7 @@ export interface LiveWidget {
export const LiveWidget = {
/**
* Starts `<program>\nreturn await __widget_live(__input(), true)` with `__input()` = `{ data }`. A program built for an
* Starts `<program>\nreturn await __widget_live(__input(), true)` with `__input()` = `{ data, gpu }`. A program built for an
* older contract ends at once with an error; one for a newer contract throws (a client error).
*/
start: (program: string, data: unknown, options?: LiveOptions): LiveWidget => {
@ -166,6 +185,15 @@ export const LiveWidget = {
}> = []
const drawings = new Map<string, ReadonlyArray<Command>>()
const warnings: string[] = []
const gpuErrors: GpuError[] = []
const gpu = gpuChecks(
() => new Set([...(current.tree?.canvases ?? new Map())].flatMap(([key, canvas]) => (canvas.gpu ? [key] : []))),
)
// A GPU batch, checked; `frame`: it came with a frame request.
const replay = (batch: GpuBatch, frame: boolean) => {
const error = gpu.batch(batch, frame)
if (error) gpuErrors.push(error)
}
const ending = Promise.withResolvers<LiveEnd>()
const current = {
view: undefined as Node | undefined,
@ -178,7 +206,11 @@ export const LiveWidget = {
// The post rate's token bucket, and the `render` and `draw` posts waiting for a token, oldest first; a canvas's
// draws coalesce by its key.
bucket: { tokens: BURST, at: started },
waiting: [] as Array<{ readonly key: string | undefined; readonly message: LiveMessage }>,
waiting: [] as Array<{
readonly key: string | undefined
readonly message: LiveMessage
readonly counted: boolean
}>,
slot: undefined as (() => void) | undefined,
fetches: { inFlight: 0, starts: [] as number[] },
// The last rendered view's tree, for `draw` keys.
@ -378,6 +410,7 @@ export const LiveWidget = {
const canvas = current.tree?.canvases.get(key)
if (canvas === undefined) throw new Error('No canvas with key "' + key + '" in the rendered view')
if (canvas.wgsl) throw new Error('Canvas "' + key + '" is drawn by its wgsl; it takes no draw commands')
if (canvas.gpu) throw new Error('Canvas "' + key + '" is drawn by the GPU; it takes no draw commands')
return { message: unmark({ type: "draw", id: canvas.id, commands: message.commands }, POSTED), key }
}
@ -397,15 +430,23 @@ export const LiveWidget = {
const accepted = accept(message)
if (!accepted) return
if (accepted.type === "render" || accepted.type === "draw") return counted(accepted, key)
if (accepted.type === "frame" && current.requested) return
// A GPU batch takes no token, but never overtakes a waiting render or draw: its canvas may be in one.
if ((accepted.type === "gpu" || (accepted.type === "frame" && accepted.gpu)) && current.waiting.length > 0)
return void current.waiting.push({ key: undefined, message: accepted, counted: false })
if (accepted.type === "submit" || accepted.type === "dismiss") release()
apply(accepted)
send(accepted)
}
// A frame request while one is pending changes nothing, but its GPU batch is applied.
const send = (accepted: LiveMessage) => {
if (accepted.type !== "frame" || !current.requested) return apply(accepted)
if (accepted.gpu) apply({ type: "gpu", ops: accepted.gpu.ops, bytes: accepted.gpu.bytes })
}
// The post rate (specs/v2/widgets-live.md): a token bucket of `BURST` tokens, refilled at `postsPerSecond`. A
// `render` or `draw` post takes a token and goes out at once when nothing waits; otherwise it waits, in place of a
// waiting post of its kind (the render, or the draw for its canvas key), and waiting posts go out in order, one per
// token, as tokens come.
// token, as tokens come; a GPU batch waiting among them takes none.
const refill = () => {
const at = clock.now()
current.bucket.tokens = Math.min(
@ -425,8 +466,8 @@ export const LiveWidget = {
? entry.message.type === "render"
: entry.message.type === "draw" && entry.key === key,
)
if (index === -1) current.waiting.push({ key, message })
else current.waiting[index] = { key, message }
if (index === -1) current.waiting.push({ key, message, counted: true })
else current.waiting[index] = { key, message, counted: true }
schedule()
}
const schedule = () => {
@ -436,9 +477,12 @@ export const LiveWidget = {
current.slot = clock.schedule(wait, () => {
current.slot = undefined
refill()
while (current.waiting.length > 0 && current.bucket.tokens >= 1 - EPSILON && !current.ended) {
current.bucket.tokens -= 1
apply(current.waiting.shift()!.message)
while (current.waiting.length > 0 && !current.ended) {
const next = current.waiting[0]!
if (next.counted && current.bucket.tokens < 1 - EPSILON) break
if (next.counted) current.bucket.tokens -= 1
current.waiting.shift()
send(next.message)
}
schedule()
})
@ -447,13 +491,15 @@ export const LiveWidget = {
const release = () => {
current.slot?.()
current.slot = undefined
current.waiting.splice(0).forEach((entry) => apply(entry.message))
current.waiting.splice(0).forEach((entry) => send(entry.message))
}
const apply = (accepted: LiveMessage) => {
if (accepted.type === "render") current.view = accepted.node
if (accepted.type === "draw") drawings.set(accepted.id, accepted.commands)
if (accepted.type === "frame") current.requested = true
if (accepted.type === "frame" && accepted.gpu) replay(accepted.gpu, true)
if (accepted.type === "gpu") replay(accepted, false)
options?.onMessage?.(accepted)
if (accepted.type === "submit") return end({ type: "submit", value: accepted.value })
if (accepted.type === "dismiss") return end({ type: "dismiss" })
@ -480,7 +526,10 @@ export const LiveWidget = {
if ("error" in checked) return void fail("invalid", checked.error)
return { type: "draw", id: message.id as string, commands: checked.commands }
}
if (message.type === "frame") return { type: "frame" }
if (message.type === "frame")
return isRecord(message.gpu) ? { type: "frame", gpu: message.gpu as unknown as GpuBatch } : { type: "frame" }
if (message.type === "gpu")
return { type: "gpu", ops: message.ops as GpuBatch["ops"], bytes: message.bytes as ArrayBuffer }
if (message.type === "submit") return { type: "submit", value: message.value ?? null }
if (message.type === "dismiss") return { type: "dismiss" }
if (message.type === "send") return { type: "send", value: message.value ?? null, wake: message.wake !== false }
@ -508,6 +557,7 @@ export const LiveWidget = {
return current.pausedAt !== undefined
},
warnings,
gpuErrors,
get ended() {
return current.ended
},
@ -519,6 +569,11 @@ export const LiveWidget = {
deliver({ type: "frame", frame })
return true
},
canvas: (key, width, height) => deliver({ type: "canvas", key, width, height }),
loseDevice: (reason) => {
gpu.lost()
deliver({ type: "gpu", lost: reason })
},
pause: () => {
if (current.pausedAt !== undefined || current.ended) return
current.pausedAt = clock.now()
@ -554,7 +609,11 @@ export const LiveWidget = {
Runtime.make({
limits: { maxValueDepth: MAX_VALUE_DEPTH },
globals: () => ({
__input: Host.fn(() => ({ data })),
__input: Host.fn(() =>
options?.gpu === false
? { data }
: { data, gpu: { available: true, format: options?.gpu?.format ?? "rgba8unorm" } },
),
__host: {
post: located((args) => post(args)),
receive: located((args, call) => (checked("receive", args), receive(call.signal)), {

View file

@ -112,6 +112,8 @@ export interface Canvas {
readonly wgsl?: string
/** With `wgsl`: up to 16 floats, available as `widget.values` (4 vec4f, row-major, zero padded). */
readonly values?: ReadonlyArray<number>
/** A live program draws it with `widget.gpu` (widgets-gpu.md); it needs a `key`. */
readonly gpu?: true
/** An image src shown where the canvas can't be drawn (a terminal, a shader that fails to compile). */
readonly poster?: string
/** Set by the prelude when the canvas has an `onPointer` handler: only then does it take pointer input. */
@ -451,11 +453,16 @@ export const Node: Schema.Codec<Node> = Schema.Union([
values: optional(Schema.Array(Schema.Finite).check(Schema.isMaxLength(16))),
poster: optional(Schema.String),
pointer: optional(Schema.Literal(true)),
gpu: optional(Schema.Literal(true)),
}).check(
Schema.makeFilter(
(canvas: { readonly wgsl?: string; readonly values?: ReadonlyArray<number> }) =>
(canvas: { readonly wgsl?: string; readonly values?: ReadonlyArray<number>; readonly gpu?: true }) =>
canvas.values === undefined || canvas.wgsl !== undefined || "`values` need `wgsl`",
),
Schema.makeFilter(
(canvas: { readonly wgsl?: string; readonly gpu?: true }) =>
canvas.gpu === undefined || canvas.wgsl === undefined || "`gpu` and `wgsl` exclude each other",
),
),
])

View file

@ -357,6 +357,609 @@ function __widget_dispatch(state, event, data) {
return event.type === "press" ? entry.handler(state) : entry.handler(state, value)
}
// WebGPU's flags, for the subset widgets have (specs/v2/widgets-gpu.md).
const GPUBufferUsage = Object.freeze({ COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128 })
const GPUTextureUsage = Object.freeze({ COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, RENDER_ATTACHMENT: 16 })
const GPUShaderStage = Object.freeze({ VERTEX: 1, FRAGMENT: 2 })
const GPUColorWrite = Object.freeze({ RED: 1, GREEN: 2, BLUE: 4, ALPHA: 8, ALL: 15 })
// `widget.gpu` (specs/v2/widgets-gpu.md): WebGPU's shapes, recorded as ops and bytes into the batch the host replays.
// `start` takes the live input's `gpu`; `take` gives the pending batch (or null); `accept` takes the host's `canvas`
// and `gpu` messages; `watched` tells whether the program waits on the device's loss, which `watch` is told of.
function __widget_gpu(watch) {
const LIMITS = Object.freeze({
maxTextureDimension2D: 4096,
maxTextureArrayLayers: 256,
maxBindGroups: 4,
maxBindingsPerBindGroup: 1000,
maxDynamicUniformBuffersPerPipelineLayout: 8,
maxDynamicStorageBuffersPerPipelineLayout: 4,
maxSampledTexturesPerShaderStage: 16,
maxSamplersPerShaderStage: 16,
maxStorageBuffersPerShaderStage: 8,
maxUniformBuffersPerShaderStage: 12,
maxUniformBufferBindingSize: 65536,
maxStorageBufferBindingSize: 67108864,
minUniformBufferOffsetAlignment: 256,
minStorageBufferOffsetAlignment: 256,
maxVertexBuffers: 8,
maxBufferSize: 67108864,
maxVertexAttributes: 16,
maxVertexBufferArrayStride: 2048,
maxInterStageShaderVariables: 16,
maxColorAttachments: 8,
maxColorAttachmentBytesPerSample: 32,
})
// `device`: the live device or null, and `lost` its resolver; `ops` and `bytes` (`length` of them used): the pending
// batch. `sizes`: the GPU canvases' sizes by key, from the host; `contexts` by key.
const gpu = {
watched: false,
available: false,
format: "rgba8unorm",
next: 1,
device: null,
lost: null,
ops: [],
bytes: null,
length: 0,
}
const sizes = {}
const contexts = {}
const handle = () => gpu.next++
// Records an op for `device`; a lost device's calls, and every call without a GPU, record nothing.
const record = (device, op) => {
if (gpu.available && device === gpu.device) gpu.ops.push(op)
}
const kind = (value, expected, what) => {
if (!value || value.__kind !== expected) throw new TypeError(what + " must be a GPU " + expected)
return value.__handle
}
const object = (value, what) => {
if (!value || typeof value !== "object") throw new TypeError(what + " must be an object")
return value
}
// Appends `data`'s bytes (an ArrayBuffer, or a typed array whose offset and size count elements) to the batch and
// returns `[byteOffset, byteLength]`. They are copied now, as WebGPU's writes copy them.
const append = (data, offset, size) => {
const view = ArrayBuffer.isView(data)
if (!view && !(data instanceof ArrayBuffer)) throw new TypeError("data must be an ArrayBuffer or a typed array")
const unit = view ? data.BYTES_PER_ELEMENT : 1
const skip = (offset ?? 0) * unit
const length = size === undefined ? data.byteLength - skip : size * unit
const bytes = new Uint8Array(view ? data.buffer : data, (view ? data.byteOffset : 0) + skip, length)
if (!gpu.bytes || gpu.length + length > gpu.bytes.length) {
const grown = new Uint8Array(Math.max(1024, (gpu.length + length) * 2))
if (gpu.bytes) grown.set(new Uint8Array(gpu.bytes.buffer, 0, gpu.length))
gpu.bytes = grown
}
gpu.bytes.set(bytes, gpu.length)
gpu.length += length
return [gpu.length - length, length]
}
// An origin or extent as WebGPU takes one (an array, or an object), as `[x, y, z]`.
const triple = (value, fill) =>
Array.isArray(value)
? [value[0] ?? fill[0], value[1] ?? fill[1], value[2] ?? fill[2]]
: value && typeof value === "object"
? [
value.x ?? value.width ?? fill[0],
value.y ?? value.height ?? fill[1],
value.z ?? value.depthOrArrayLayers ?? fill[2],
]
: fill
const extent = (value) => triple(value, [undefined, 1, 1])
const origin = (value) => triple(value, [0, 0, 0])
const component = (value) => ({
operation: value?.operation ?? "add",
srcFactor: value?.srcFactor ?? "one",
dstFactor: value?.dstFactor ?? "zero",
})
const texture = (device, h, props) => {
// Views are immutable, so equal ones are one handle: a frame's view of the canvas too.
const views = {}
return {
__kind: "texture",
__handle: h,
__device: device,
...props,
createView: (descriptor) => {
const d = descriptor ?? {}
const layers = props.depthOrArrayLayers
const dimension = d.dimension ?? (layers > 1 ? "2d-array" : "2d")
const base = d.baseArrayLayer ?? 0
const mip = d.baseMipLevel ?? 0
const normal = {
dimension,
baseMipLevel: mip,
mipLevelCount: d.mipLevelCount ?? props.mipLevelCount - mip,
baseArrayLayer: base,
arrayLayerCount: d.arrayLayerCount ?? (dimension === "2d" ? 1 : dimension === "cube" ? 6 : layers - base),
}
const key = JSON.stringify(normal)
if (views[key]) return views[key]
const view = { __kind: "view", __handle: handle(), __device: device }
record(device, ["view", view.__handle, h, normal])
views[key] = view
return view
},
destroy: () => record(device, ["destroy", h]),
}
}
const pass = (encoder, descriptor) => {
const d = object(descriptor, "beginRenderPass's descriptor")
const depth = d.depthStencilAttachment
const clear = (value) =>
Array.isArray(value) ? [...value] : value ? [value.r, value.g, value.b, value.a] : [0, 0, 0, 0]
encoder.add(
[
"pass",
{
colorAttachments: (d.colorAttachments ?? []).map((a) =>
a
? {
view: kind(a.view, "view", "a color attachment's view"),
resolveTarget: a.resolveTarget ? kind(a.resolveTarget, "view", "a resolveTarget") : null,
clearValue: clear(a.clearValue),
loadOp: a.loadOp,
storeOp: a.storeOp,
}
: null,
),
depthStencilAttachment: depth
? {
view: kind(depth.view, "view", "the depth attachment's view"),
depthClearValue: depth.depthClearValue ?? null,
depthLoadOp: depth.depthLoadOp ?? null,
depthStoreOp: depth.depthStoreOp ?? null,
depthReadOnly: depth.depthReadOnly ?? false,
}
: null,
},
],
true,
)
const open = { ended: false }
const add = (op) => (open.ended ? encoder.fail("the render pass has ended") : encoder.add(op, true))
return {
setPipeline: (pipeline) => add(["setPipeline", kind(pipeline, "renderPipeline", "setPipeline's pipeline")]),
setBindGroup: (index, group, offsets) =>
add([
"setBindGroup",
index,
kind(group, "bindGroup", "setBindGroup's group"),
offsets ? Array.from(offsets) : [],
]),
setVertexBuffer: (slot, buffer, offset, size) =>
add(["setVertexBuffer", slot, kind(buffer, "buffer", "setVertexBuffer's buffer"), offset ?? 0, size ?? -1]),
setIndexBuffer: (buffer, format, offset, size) =>
add(["setIndexBuffer", kind(buffer, "buffer", "setIndexBuffer's buffer"), format, offset ?? 0, size ?? -1]),
setViewport: (x, y, width, height, minDepth, maxDepth) =>
add(["setViewport", x, y, width, height, minDepth, maxDepth]),
setScissorRect: (x, y, width, height) => add(["setScissorRect", x, y, width, height]),
draw: (count, instances, first, firstInstance) =>
add(["draw", count, instances ?? 1, first ?? 0, firstInstance ?? 0]),
drawIndexed: (count, instances, first, base, firstInstance) =>
add(["drawIndexed", count, instances ?? 1, first ?? 0, base ?? 0, firstInstance ?? 0]),
end: () => {
if (open.ended) return encoder.fail("the render pass has ended")
open.ended = true
encoder.add(["end"], true)
encoder.close()
},
}
}
// A command encoder keeps its commands until `queue.submit` takes its command buffer. Misuse that WebGPU reports as
// a validation error goes into the batch as an `error` op, once per encoder, and the encoder records nothing more.
const encoder = (device) => {
const state = { ops: gpu.available ? [] : null, pass: false, finished: false, failed: false }
const self = {
add: (op, inPass) => {
if (state.failed) return
if (state.finished) return self.fail("the command encoder is finished")
if (state.pass && !inPass) return self.fail("a render pass is open on this command encoder")
state.ops?.push(op)
},
close: () => (state.pass = false),
fail: (message) => {
if (state.failed) return
state.failed = true
record(device, ["error", message])
},
}
const dead = { add: () => {}, fail: () => {}, close: () => {} }
return {
__kind: "encoder",
beginRenderPass: (descriptor) => {
if (state.finished) self.fail("the command encoder is finished")
else if (state.pass) self.fail("a render pass is open on this command encoder")
if (state.failed) return pass(dead, descriptor)
state.pass = true
return pass(self, descriptor)
},
copyBufferToBuffer: (source, sourceOffset, destination, destinationOffset, size) =>
self.add([
"copyBufferToBuffer",
kind(source, "buffer", "the source"),
sourceOffset,
kind(destination, "buffer", "the destination"),
destinationOffset,
size,
]),
copyBufferToTexture: (source, destination, size) =>
self.add([
"copyBufferToTexture",
kind(source?.buffer, "buffer", "the source's buffer"),
source.offset ?? 0,
source.bytesPerRow,
source.rowsPerImage ?? null,
kind(destination?.texture, "texture", "the destination's texture"),
destination.mipLevel ?? 0,
origin(destination.origin),
extent(size),
]),
copyTextureToTexture: (source, destination, size) =>
self.add([
"copyTextureToTexture",
kind(source?.texture, "texture", "the source's texture"),
source.mipLevel ?? 0,
origin(source.origin),
kind(destination?.texture, "texture", "the destination's texture"),
destination.mipLevel ?? 0,
origin(destination.origin),
extent(size),
]),
finish: () => {
if (state.pass) self.fail("a render pass is open on this command encoder")
else if (state.finished) self.fail("the command encoder is finished")
state.finished = true
return { __kind: "commandBuffer", ops: state.failed ? null : state.ops, submitted: false }
},
}
}
const createDevice = () => {
const lost = new Promise((resolve) => (gpu.lost = resolve))
const device = {
__kind: "device",
limits: LIMITS,
features: new Set(),
// Reading it waits for the loss: the host's messages keep coming until then.
get lost() {
gpu.watched = true
watch()
return lost
},
createBuffer: (descriptor) => {
const d = object(descriptor, "createBuffer's descriptor")
const h = handle()
record(device, ["buffer", h, d.size, d.usage])
return {
__kind: "buffer",
__handle: h,
__device: device,
size: d.size,
usage: d.usage,
destroy: () => record(device, ["destroy", h]),
}
},
createTexture: (descriptor) => {
const d = object(descriptor, "createTexture's descriptor")
const [width, height, depthOrArrayLayers] = extent(d.size)
const props = {
width,
height,
depthOrArrayLayers,
format: d.format,
usage: d.usage,
mipLevelCount: d.mipLevelCount ?? 1,
sampleCount: d.sampleCount ?? 1,
dimension: "2d",
}
const h = handle()
if (d.dimension !== undefined && d.dimension !== "2d")
record(device, ["error", 'a texture\'s dimension must be "2d"'])
record(device, [
"texture",
h,
width,
height,
depthOrArrayLayers,
d.format,
d.usage,
props.mipLevelCount,
props.sampleCount,
])
return texture(device, h, props)
},
createSampler: (descriptor) => {
const d = descriptor ?? {}
const h = handle()
record(device, [
"sampler",
h,
{
addressModeU: d.addressModeU ?? "clamp-to-edge",
addressModeV: d.addressModeV ?? "clamp-to-edge",
addressModeW: d.addressModeW ?? "clamp-to-edge",
magFilter: d.magFilter ?? "nearest",
minFilter: d.minFilter ?? "nearest",
mipmapFilter: d.mipmapFilter ?? "nearest",
lodMinClamp: d.lodMinClamp ?? 0,
lodMaxClamp: d.lodMaxClamp ?? 32,
compare: d.compare ?? null,
maxAnisotropy: d.maxAnisotropy ?? 1,
},
])
return { __kind: "sampler", __handle: h, __device: device }
},
createShaderModule: (descriptor) => {
const h = handle()
record(device, ["shader", h, object(descriptor, "createShaderModule's descriptor").code])
return { __kind: "shader", __handle: h, __device: device }
},
createBindGroupLayout: (descriptor) => {
const h = handle()
const entries = (object(descriptor, "createBindGroupLayout's descriptor").entries ?? []).map((e) => ({
binding: e.binding,
visibility: e.visibility,
buffer: e.buffer
? {
type: e.buffer.type ?? "uniform",
hasDynamicOffset: e.buffer.hasDynamicOffset ?? false,
minBindingSize: e.buffer.minBindingSize ?? 0,
}
: null,
sampler: e.sampler ? { type: e.sampler.type ?? "filtering" } : null,
texture: e.texture
? {
sampleType: e.texture.sampleType ?? "float",
viewDimension: e.texture.viewDimension ?? "2d",
multisampled: e.texture.multisampled ?? false,
}
: null,
}))
record(device, ["bindGroupLayout", h, { entries }])
return { __kind: "bindGroupLayout", __handle: h, __device: device }
},
createPipelineLayout: (descriptor) => {
const h = handle()
const layouts = (object(descriptor, "createPipelineLayout's descriptor").bindGroupLayouts ?? []).map((l) =>
kind(l, "bindGroupLayout", "a bind group layout"),
)
record(device, ["pipelineLayout", h, layouts])
return { __kind: "pipelineLayout", __handle: h, __device: device }
},
createBindGroup: (descriptor) => {
const d = object(descriptor, "createBindGroup's descriptor")
const h = handle()
// A buffer, a buffer binding, a sampler or a texture view.
const resource = (r) =>
r?.__kind === "sampler"
? { sampler: r.__handle }
: r?.__kind === "view"
? { view: r.__handle }
: r?.__kind === "buffer"
? { buffer: r.__handle, offset: 0, size: -1 }
: {
buffer: kind(r?.buffer, "buffer", "a bind group entry's resource"),
offset: r.offset ?? 0,
size: r.size ?? -1,
}
record(device, [
"bindGroup",
h,
{
layout: kind(d.layout, "bindGroupLayout", "createBindGroup's layout"),
entries: (d.entries ?? []).map((e) => ({ binding: e.binding, resource: resource(e.resource) })),
},
])
return { __kind: "bindGroup", __handle: h, __device: device }
},
createRenderPipeline: (descriptor) => {
const d = object(descriptor, "createRenderPipeline's descriptor")
const h = handle()
const vertex = object(d.vertex, "the vertex stage")
const fragment = d.fragment
const depth = d.depthStencil
record(device, [
"renderPipeline",
h,
{
layout: d.layout === "auto" ? "auto" : kind(d.layout, "pipelineLayout", "the layout"),
vertex: {
module: kind(vertex.module, "shader", "the vertex module"),
entryPoint: vertex.entryPoint ?? null,
buffers: (vertex.buffers ?? []).map((b) =>
b
? {
arrayStride: b.arrayStride,
stepMode: b.stepMode ?? "vertex",
attributes: (b.attributes ?? []).map((a) => ({
format: a.format,
offset: a.offset,
shaderLocation: a.shaderLocation,
})),
}
: null,
),
},
fragment: fragment
? {
module: kind(fragment.module, "shader", "the fragment module"),
entryPoint: fragment.entryPoint ?? null,
targets: (fragment.targets ?? []).map((t) =>
t
? {
format: t.format,
blend: t.blend ? { color: component(t.blend.color), alpha: component(t.blend.alpha) } : null,
writeMask: t.writeMask ?? 15,
}
: null,
),
}
: null,
primitive: {
topology: d.primitive?.topology ?? "triangle-list",
stripIndexFormat: d.primitive?.stripIndexFormat ?? null,
frontFace: d.primitive?.frontFace ?? "ccw",
cullMode: d.primitive?.cullMode ?? "none",
},
depthStencil: depth
? {
format: depth.format,
depthWriteEnabled: depth.depthWriteEnabled ?? false,
depthCompare: depth.depthCompare ?? "always",
}
: null,
multisample: {
count: d.multisample?.count ?? 1,
mask: d.multisample?.mask ?? 4294967295,
alphaToCoverageEnabled: d.multisample?.alphaToCoverageEnabled ?? false,
},
},
])
// `layout: "auto"`'s layouts: one handle per index.
const layouts = {}
return {
__kind: "renderPipeline",
__handle: h,
__device: device,
getBindGroupLayout: (index) => {
if (layouts[index]) return layouts[index]
const layout = { __kind: "bindGroupLayout", __handle: handle(), __device: device }
record(device, ["autoLayout", layout.__handle, h, index])
layouts[index] = layout
return layout
},
}
},
createCommandEncoder: () => encoder(device),
queue: {
writeBuffer: (buffer, offset, data, dataOffset, size) => {
const h = kind(buffer, "buffer", "writeBuffer's buffer")
if (gpu.available && device === gpu.device)
gpu.ops.push(["writeBuffer", h, offset, ...append(data, dataOffset, size)])
},
writeTexture: (destination, data, layout, size) => {
const h = kind(destination?.texture, "texture", "writeTexture's texture")
if (!gpu.available || device !== gpu.device) return
const skip = layout?.offset ?? 0
const [byteOffset, byteLength] = append(data)
gpu.ops.push([
"writeTexture",
h,
destination.mipLevel ?? 0,
origin(destination.origin),
byteOffset + skip,
byteLength - skip,
layout?.bytesPerRow,
layout?.rowsPerImage ?? null,
extent(size),
])
},
submit: (buffers) => {
for (const buffer of buffers) {
kind(buffer, "commandBuffer", "submit's command buffer")
if (buffer.submitted) {
record(device, ["error", "a command buffer can be submitted once"])
continue
}
buffer.submitted = true
if (buffer.ops && gpu.available && device === gpu.device) for (const op of buffer.ops) gpu.ops.push(op)
}
record(device, ["submit"])
},
},
}
return device
}
const api = {
get available() {
return gpu.available
},
getPreferredCanvasFormat: () => gpu.format,
// One device per widget, until it is lost.
requestDevice: async () => {
if (!gpu.device) gpu.device = createDevice()
return gpu.device
},
getContext: (key) => {
const name = String(key)
if (contexts[name]) return contexts[name]
const state = { device: null, handle: 0, texture: null }
const context = {
get width() {
return sizes[name]?.width ?? 0
},
get height() {
return sizes[name]?.height ?? 0
},
configure: (configuration) => {
const c = object(configuration, "configure's configuration")
kind(c.device, "device", "configure's device")
// A new device's context is a new handle; configuring again keeps it.
if (c.device !== state.device) state.handle = handle()
state.device = c.device
record(c.device, ["context", state.handle, name, c.format, c.alphaMode ?? "opaque"])
const props = {
format: c.format,
usage: 16,
mipLevelCount: 1,
sampleCount: 1,
depthOrArrayLayers: 1,
dimension: "2d",
}
state.texture = texture(c.device, state.handle, props)
// The canvas's texture is the client's: destroying it does nothing.
state.texture.destroy = () => {}
Object.defineProperty(state.texture, "width", { get: () => context.width })
Object.defineProperty(state.texture, "height", { get: () => context.height })
},
getCurrentTexture: () => {
if (!state.texture) throw new Error("configure the context before getCurrentTexture")
return state.texture
},
}
contexts[name] = context
return context
},
}
return {
api,
start: (input) => {
gpu.available = input?.available === true
if (input?.format === "bgra8unorm" || input?.format === "rgba8unorm") gpu.format = input.format
},
take: () => {
if (gpu.ops.length === 0) return null
const batch = { ops: gpu.ops, bytes: gpu.bytes ? gpu.bytes.buffer.slice(0, gpu.length) : new ArrayBuffer(0) }
gpu.ops = []
gpu.length = 0
return batch
},
watched: () => gpu.watched && gpu.available && gpu.device !== null,
accept: (message) => {
if (message.type === "canvas") {
sizes[String(message.key)] = { width: message.width, height: message.height }
return
}
if (message.type !== "gpu" || message.lost === undefined || !gpu.device) return
// Every handle is gone: the lost device's calls record nothing, and `requestDevice` makes a new one.
const resolve = gpu.lost
gpu.device = null
gpu.watched = false
gpu.ops = []
gpu.length = 0
resolve({ reason: message.lost, message: typeof message.message === "string" ? message.message : "" })
},
}
}
// Live mode (specs/v2/widgets-live.md): `main(data)` runs once, on the host's `__host.post`, `__host.receive`,
// `__host.sleep`, `__host.now` and `__host.fetch`. While the view has handlers, hooks are registered or a frame is
// awaited, a pump receives client messages and calls handlers and hooks between the program's awaits.
@ -375,9 +978,21 @@ const widget = (() => {
reject: null,
}
const api = {}
// `widget.gpu`, made for a live run only: steps never pay for it.
const made = { gpu: null }
const gpu = () => (made.gpu ??= __widget_gpu(() => pump()))
const post = (message) => (live.done ? undefined : __host.post(message))
// The pending GPU batch goes out on its own before any wait on the host but a frame request, which carries it.
const flush = () => {
const batch = gpu().take()
if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })
}
const wanted = () =>
!live.done && (live.waiting.length > 0 || live.interactive || Object.values(hooks).some((list) => list.length > 0))
!live.done &&
(live.waiting.length > 0 ||
live.interactive ||
gpu().watched() ||
Object.values(hooks).some((list) => list.length > 0))
const fail = (error) => live.reject?.(error)
// Runs a handler or hook; an async one that rejects fails the program like a throw.
const call = (handler, ...args) => {
@ -409,6 +1024,7 @@ const widget = (() => {
}
const accept = (message) => {
if (message.type === "event") return dispatch(message.event ?? {})
if (message.type === "canvas" || message.type === "gpu") return gpu().accept(message)
if (message.type === "resumed") return emit("resumed", message.pausedMs)
if (message.type !== "frame") return
live.requested = false
@ -424,7 +1040,10 @@ const widget = (() => {
if (live.pumping) return
live.pumping = true
try {
while (wanted()) accept(await __host.receive())
while (wanted()) {
flush()
accept(await __host.receive())
}
} catch (error) {
fail(error)
} finally {
@ -433,9 +1052,13 @@ const widget = (() => {
}
}
const request = () => {
if (live.requested || live.frame) return
const batch = gpu().take()
if (live.requested || live.frame) {
if (batch) post({ type: "gpu", ops: batch.ops, bytes: batch.bytes })
return
}
live.requested = true
post({ type: "frame" })
post(batch ? { type: "frame", gpu: batch } : { type: "frame" })
}
const take = () => {
const frame = live.frame
@ -490,7 +1113,10 @@ const widget = (() => {
if (index !== -1) hooks[kind].splice(index, 1)
}
},
sleep: (ms) => __host.sleep(ms),
sleep: (ms) => {
flush()
return __host.sleep(ms)
},
now: () => __host.now(),
submit: (value) => {
post({ type: "submit", value: value ?? null })
@ -501,6 +1127,7 @@ const widget = (() => {
live.done = true
},
fetch: async (url, init) => {
flush()
const request = { url: String(url), method: init?.method ?? "GET", headers: init?.headers ?? {} }
if (init?.body !== undefined) request.body = String(init.body)
try {
@ -513,11 +1140,15 @@ const widget = (() => {
capturePointer: () => post({ type: "capture", value: true }),
releasePointer: () => post({ type: "capture", value: false }),
})
Object.defineProperty(api, "gpu", { get: () => gpu().api, enumerable: true })
// Runs `main`, then keeps the widget interactive while its view has handlers or hooks are registered.
api.__run = async (data) => {
// `gpu`: the live input's `{ available, format }` (specs/v2/widgets-gpu.md), none without a GPU.
api.__run = async (data, gpuInput) => {
gpu().start(gpuInput)
const failed = new Promise((_, reject) => (live.reject = reject))
failed.catch(() => {})
await Promise.race([main(data), failed])
flush()
if (!wanted()) return
await Promise.race([new Promise((resolve) => (live.idle = resolve)), failed])
}
@ -526,6 +1157,6 @@ const widget = (() => {
// Hosts run `return await __widget_live(__input(), true)` (specs/v2/widgets.md, Native hosts).
async function __widget_live(input) {
await widget.__run(input.data)
await widget.__run(input.data, input.gpu)
return null
}

File diff suppressed because one or more lines are too long

View file

@ -31,7 +31,7 @@ export const marker: unknown = Host.functionMarker
export interface Tree {
readonly view: unknown
readonly handlers: ReadonlySet<string>
readonly canvases: ReadonlyMap<string, { readonly id: string; readonly wgsl: boolean }>
readonly canvases: ReadonlyMap<string, { readonly id: string; readonly wgsl: boolean; readonly gpu: boolean }>
}
type Item = Record<string, unknown>
@ -106,7 +106,7 @@ function clean(value: unknown, strict: string | undefined, json = false): unknow
* but a node's handler props.
*/
export function tree(root: unknown, label: string): Tree {
const canvases = new Map<string, { id: string; wgsl: boolean }>()
const canvases = new Map<string, { id: string; wgsl: boolean; gpu: boolean }>()
const handlers = new Set<string>()
const node = (value: Item, path: string, level: number): Item => {
@ -127,7 +127,7 @@ export function tree(root: unknown, label: string): Tree {
if (handled) handlers.add(path)
if (value.type === "canvas" && handled) out.pointer = true
if (canvas && !canvases.has(String(value.key)))
canvases.set(String(value.key), { id: path, wgsl: typeof value.wgsl === "string" })
canvases.set(String(value.key), { id: path, wgsl: typeof value.wgsl === "string", gpu: value.gpu === true })
}
}
if (value.children === undefined) return out

View file

@ -0,0 +1,310 @@
import { readFileSync } from "node:fs"
import path from "node:path"
// The GPU conformance fixtures' programs (`gpu/*.json`): the example widget templates, run for a few frames, and
// programs that break the subset's structure, handles or limits. `canvases`: sizes the host sends before the first
// frame; `inputs`: what the client sends before frame `frame` (an `event`, or a `canvas` size).
export interface GpuCase {
readonly name: string
readonly source: string
readonly data?: unknown
readonly canvases: ReadonlyArray<{ readonly key: string; readonly width: number; readonly height: number }>
readonly inputs?: ReadonlyArray<{ readonly frame: number; readonly input: unknown }>
}
const template = (name: string) => readFileSync(path.resolve(import.meta.dir, `gpu/templates/${name}.js`), "utf8")
// A live program that renders GPU canvases `keys`, gets a device and configures each, then runs `body` with
// `device`, `contexts` (by key) and `view(key)` (the canvas's current view).
const program = (body: string, keys: ReadonlyArray<string> = ["scene"]) => `async function main() {
widget.render(ui.column([${keys.map((key) => `ui.canvas({ key: ${JSON.stringify(key)}, gpu: true, height: 100 })`).join(", ")}]))
const device = await widget.gpu.requestDevice()
const format = widget.gpu.getPreferredCanvasFormat()
const contexts = {}
for (const key of ${JSON.stringify(keys)}) {
contexts[key] = widget.gpu.getContext(key)
contexts[key].configure({ device, format })
}
const view = (key) => contexts[key].getCurrentTexture().createView()
const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: "clear", storeOp: "store" }] })
${body}
}`
const scene = [{ key: "scene", width: 200, height: 200 }]
export const gpuCases: ReadonlyArray<GpuCase> = [
{ name: "cube", source: template("cube"), data: { frames: 3 }, canvases: [{ key: "cube", width: 600, height: 480 }] },
{
name: "textured-quad",
source: template("textured-quad"),
data: { frames: 2 },
canvases: [{ key: "quad", width: 400, height: 400 }],
},
{
name: "post-process",
source: template("post-process"),
data: { frames: 3 },
// The size changes before the second frame: the offscreen texture follows it.
canvases: [{ key: "post", width: 320, height: 220 }],
inputs: [{ frame: 1, input: { type: "canvas", key: "post", width: 640, height: 440 } }],
},
{
name: "maze",
source: template("maze"),
data: { frames: 4 },
canvases: [{ key: "maze", width: 640, height: 360 }],
inputs: [
{
frame: 1,
input: {
type: "event",
event: {
id: "",
type: "key",
value: {
kind: "down",
key: "w",
code: "KeyW",
repeat: false,
shift: false,
alt: false,
ctrl: false,
meta: false,
},
},
},
},
{ frame: 2, input: { type: "event", event: { id: "", type: "capture", value: true } } },
{
frame: 2,
input: {
type: "event",
event: { id: "0/:maze", type: "pointer", value: { kind: "move", dx: 40, dy: -10, button: 0 } },
},
},
],
},
{
// Device loss isn't a fixture input; two devices' worth of handles are: a second requestDevice keeps the first.
name: "handles-and-defaults",
source: program(`
const again = await widget.gpu.requestDevice()
if (again !== device) throw new Error("one device per widget")
const texture = device.createTexture({ size: { width: 8, height: 8, depthOrArrayLayers: 6 }, format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, mipLevelCount: 2 })
const cube = texture.createView({ dimension: "cube" })
const layers = texture.createView()
if (texture.createView({ dimension: "cube" }) !== cube) throw new Error("equal views are one handle")
device.createSampler()
const layout = device.createBindGroupLayout({ entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { viewDimension: "cube" } },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
{ binding: 2, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: "read-only-storage", hasDynamicOffset: true } },
] })
const storage = device.createBuffer({ size: 512, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC })
const copy = device.createBuffer({ size: 512, usage: GPUBufferUsage.COPY_DST })
device.createBindGroup({ layout, entries: [
{ binding: 0, resource: cube },
{ binding: 1, resource: device.createSampler({ magFilter: "linear", compare: undefined }) },
{ binding: 2, resource: { buffer: storage, offset: 256, size: 64 } },
] })
device.createPipelineLayout({ bindGroupLayouts: [layout] })
device.queue.writeBuffer(storage, 4, new Uint32Array([1, 2, 3, 4, 5]), 1, 3)
device.queue.writeBuffer(storage, 0, new Uint8Array([9, 8, 7, 6]).buffer)
device.queue.writeTexture({ texture, mipLevel: 1, origin: [0, 0, 2] }, new Uint8Array(4 * 4 * 4).fill(200), { bytesPerRow: 16 }, { width: 4, height: 4 })
const encoder = device.createCommandEncoder()
encoder.copyBufferToBuffer(storage, 0, copy, 0, 256)
device.queue.submit([encoder.finish()])
texture.destroy()
await widget.frame()`),
canvases: scene,
},
{
// The encoder errors the prelude finds itself go into the batch as \`error\` ops.
name: "error-encoder-finished",
source: program(`
const encoder = device.createCommandEncoder()
const buffer = encoder.finish()
encoder.beginRenderPass(clear("scene")).end()
device.queue.submit([buffer])
await widget.frame()`),
canvases: scene,
},
{
name: "error-open-pass",
source: program(`
const encoder = device.createCommandEncoder()
encoder.beginRenderPass(clear("scene"))
device.queue.submit([encoder.finish()])
await widget.frame()`),
canvases: scene,
},
{
name: "error-submitted-twice",
source: program(`
const encoder = device.createCommandEncoder()
encoder.beginRenderPass(clear("scene")).end()
const buffer = encoder.finish()
device.queue.submit([buffer])
device.queue.submit([buffer])
await widget.frame()`),
canvases: scene,
},
{
name: "error-unknown-canvas",
source: `async function main() {
widget.render(ui.canvas({ key: "scene", gpu: true, height: 100 }))
const device = await widget.gpu.requestDevice()
widget.gpu.getContext("elsewhere").configure({ device, format: widget.gpu.getPreferredCanvasFormat() })
await widget.frame()
}`,
canvases: scene,
},
{
name: "error-buffer-too-big",
source: program(`
device.createBuffer({ size: 64 * 1024 * 1024 + 4, usage: GPUBufferUsage.VERTEX })
await widget.frame()`),
canvases: scene,
},
{
name: "error-texture-too-wide",
source: program(`
device.createTexture({ size: [4097, 4], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING })
await widget.frame()`),
canvases: scene,
},
{
name: "error-unknown-format",
source: program(`
device.createTexture({ size: [4, 4], format: "rg11b10ufloat", usage: GPUTextureUsage.TEXTURE_BINDING })
await widget.frame()`),
canvases: scene,
},
{
name: "error-usage-outside-the-subset",
source: program(`
device.createBuffer({ size: 16, usage: 1 })
await widget.frame()`),
canvases: scene,
},
{
name: "error-resources-over-256-mb",
source: program(`
for (let i = 0; i < 5; i++) device.createBuffer({ size: 64 * 1024 * 1024, usage: GPUBufferUsage.STORAGE })
await widget.frame()`),
canvases: scene,
},
{
name: "error-destroyed-buffer",
source: program(`
const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.COPY_DST })
buffer.destroy()
device.queue.writeBuffer(buffer, 0, new Float32Array(4))
await widget.frame()`),
canvases: scene,
},
{
name: "error-too-many-passes",
source: program(`
await widget.frame()
const encoder = device.createCommandEncoder()
for (let i = 0; i < 17; i++) encoder.beginRenderPass(clear("scene")).end()
device.queue.submit([encoder.finish()])
await widget.frame()`),
canvases: scene,
},
{
// 10,000 draws a frame are allowed; one more is over, in any of the frame's batches.
name: "error-too-many-draws",
source: program(`
const module = device.createShaderModule({ code: "@vertex fn vs() -> @builtin(position) vec4f { return vec4f(0); } @fragment fn fs() -> @location(0) vec4f { return vec4f(1); }" })
const pipeline = device.createRenderPipeline({ layout: "auto", vertex: { module }, fragment: { module, targets: [{ format }] } })
const frame = async (draws) => {
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass(clear("scene"))
pass.setPipeline(pipeline)
for (let i = 0; i < draws; i++) pass.draw(3)
pass.end()
device.queue.submit([encoder.finish()])
}
await frame(10000)
await widget.frame()
await frame(6000)
await widget.sleep(1)
await frame(4001)
await widget.frame()`),
canvases: scene,
},
{
// An error stops the canvases its batch renders into: "a"'s batch fails on frame 1, "b"'s on frame 2; a batch
// that renders into neither stops both, but they are stopped already, so it gives no error.
name: "error-isolated-to-a-canvas",
source: program(
`
const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.VERTEX })
const gone = device.createBuffer({ size: 16, usage: GPUBufferUsage.VERTEX })
gone.destroy()
const draw = (key, vertices) => {
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass(clear(key))
pass.setVertexBuffer(0, vertices)
pass.end()
device.queue.submit([encoder.finish()])
}
for (let frame = 0; frame < 3; frame++) {
await widget.frame()
draw("a", frame === 1 ? gone : buffer)
await widget.sleep(1)
draw("b", frame === 2 ? gone : buffer)
}
await widget.frame()
device.queue.writeBuffer(gone, 0, new Float32Array(4))`,
["a", "b"],
),
canvases: [
{ key: "a", width: 100, height: 100 },
{ key: "b", width: 100, height: 100 },
],
},
]
// Batches a program posts itself, which the prelude never makes, one fixture each: a JavaScript expression for the
// batch's ops, posted with 8 bytes.
const raw = (ops: string) => `async function main() {
widget.render(ui.canvas({ key: "scene", gpu: true, height: 100 }))
__host.post({ type: "gpu", ops: ${ops}, bytes: new ArrayBuffer(8) })
await widget.frame()
}`
const view = `{ dimension: "2d", baseMipLevel: 0, mipLevelCount: 1, baseArrayLayer: 0, arrayLayerCount: 1 }`
const sampler = `{ addressModeU: "wrap", addressModeV: "repeat", addressModeW: "repeat", magFilter: "nearest", minFilter: "nearest", mipmapFilter: "nearest", lodMinClamp: 0, lodMaxClamp: 32, compare: null, maxAnisotropy: 1 }`
export const rawCases: ReadonlyArray<GpuCase> = (
[
["unknown-op", `[["sparkle", 1]]`],
["not-a-list", `[{ op: "buffer" }]`],
["wrong-arity", `[["buffer", 1, 16]]`],
["handle-reused", `[["buffer", 1, 16, 32], ["buffer", 1, 16, 32]]`],
["handles-out-of-order", `[["buffer", 2, 16, 32], ["buffer", 1, 16, 32]]`],
["no-such-handle", `[["destroy", 9]]`],
["wrong-kind", `[["shader", 1, ""], ["destroy", 1]]`],
["bytes-out-of-range", `[["buffer", 1, 16, 8], ["writeBuffer", 1, 0, 4, 8]]`],
["not-a-whole-number", `[["buffer", 1, 16.5, 8]]`],
["bad-enum", `[["sampler", 1, ${sampler}]]`],
["draw-outside-a-pass", `[["draw", 3, 1, 0, 0]]`],
[
"pass-left-open",
`[["context", 1, "scene", "rgba8unorm", "opaque"], ["view", 2, 1, ${view}], ["pass", { colorAttachments: [{ view: 2, resolveTarget: null, clearValue: [0, 0, 0, 1], loadOp: "clear", storeOp: "store" }], depthStencilAttachment: null }]]`,
],
[
"bind-group-layout-entry",
`[["bindGroupLayout", 1, { entries: [{ binding: 0, visibility: 2, buffer: null, sampler: null, texture: null }] }]]`,
],
["shader-over-256-kb", `[["shader", 1, "x".repeat(256 * 1024 + 1)]]`],
["ops-over-20000", `Array.from({ length: 20001 }, (_, i) => ["shader", i + 1, ""])`],
["handles-over-4096", `Array.from({ length: 4097 }, (_, i) => ["shader", i + 1, ""])`],
] as const
).map(([name, ops]) => ({
name: `raw-${name}`,
source: raw(ops),
canvases: [{ key: "scene", width: 100, height: 100 }],
}))

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,32 @@
{
"name": "error-buffer-too-big",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n device.createBuffer({ size: 64 * 1024 * 1024 + 4, usage: GPUBufferUsage.VERTEX })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: \"buffer\" argument 2 is over the limit of 67108864",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["buffer",2,67108868,32]
]
}
]
}

View file

@ -0,0 +1,34 @@
{
"name": "error-destroyed-buffer",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.COPY_DST })\n buffer.destroy()\n device.queue.writeBuffer(buffer, 0, new Float32Array(4))\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 3: handle 2 was destroyed",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "AAAAAAAAAAAAAAAAAAAAAA==",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["buffer",2,16,8],
["destroy",2],
["writeBuffer",2,0,0,16]
]
}
]
}

View file

@ -0,0 +1,34 @@
{
"name": "error-encoder-finished",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const encoder = device.createCommandEncoder()\n const buffer = encoder.finish()\n encoder.beginRenderPass(clear(\"scene\")).end()\n device.queue.submit([buffer])\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 2: the command encoder is finished",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["view",2,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["error","the command encoder is finished"],
["submit"]
]
}
]
}

View file

@ -0,0 +1,117 @@
{
"name": "error-isolated-to-a-canvas",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"a\", gpu: true, height: 100 }), ui.canvas({ key: \"b\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"a\",\"b\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.VERTEX })\n const gone = device.createBuffer({ size: 16, usage: GPUBufferUsage.VERTEX })\n gone.destroy()\n const draw = (key, vertices) => {\n const encoder = device.createCommandEncoder()\n const pass = encoder.beginRenderPass(clear(key))\n pass.setVertexBuffer(0, vertices)\n pass.end()\n device.queue.submit([encoder.finish()])\n }\n for (let frame = 0; frame < 3; frame++) {\n await widget.frame()\n draw(\"a\", frame === 1 ? gone : buffer)\n await widget.sleep(1)\n draw(\"b\", frame === 2 ? gone : buffer)\n }\n await widget.frame()\n device.queue.writeBuffer(gone, 0, new Float32Array(4))\n}",
"canvases": [
{
"key": "a",
"width": 100,
"height": 100
},
{
"key": "b",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: handle 4 was destroyed",
"canvases": [
"a"
]
},
{
"message": "gpu op 1: handle 4 was destroyed",
"canvases": [
"b"
]
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"a","rgba8unorm","opaque"],
["context",2,"b","rgba8unorm","opaque"],
["buffer",3,16,32],
["buffer",4,16,32],
["destroy",4]
]
},
{
"frame": false,
"bytes": "",
"ops": [
["view",5,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["pass",{"colorAttachments":[{"view":5,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,3,0,-1],
["end"],
["submit"]
]
},
{
"frame": true,
"bytes": "",
"ops": [
["view",6,2,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["pass",{"colorAttachments":[{"view":6,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,3,0,-1],
["end"],
["submit"]
]
},
{
"frame": false,
"bytes": "",
"ops": [
["pass",{"colorAttachments":[{"view":5,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,4,0,-1],
["end"],
["submit"]
]
},
{
"frame": true,
"bytes": "",
"ops": [
["pass",{"colorAttachments":[{"view":6,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,3,0,-1],
["end"],
["submit"]
]
},
{
"frame": false,
"bytes": "",
"ops": [
["pass",{"colorAttachments":[{"view":5,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,3,0,-1],
["end"],
["submit"]
]
},
{
"frame": true,
"bytes": "",
"ops": [
["pass",{"colorAttachments":[{"view":6,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setVertexBuffer",0,4,0,-1],
["end"],
["submit"]
]
},
{
"frame": false,
"bytes": "AAAAAAAAAAAAAAAAAAAAAA==",
"ops": [
["writeBuffer",4,0,0,16]
]
}
]
}

View file

@ -0,0 +1,34 @@
{
"name": "error-open-pass",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const encoder = device.createCommandEncoder()\n encoder.beginRenderPass(clear(\"scene\"))\n device.queue.submit([encoder.finish()])\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 2: a render pass is open on this command encoder",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["view",2,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["error","a render pass is open on this command encoder"],
["submit"]
]
}
]
}

View file

@ -0,0 +1,36 @@
{
"name": "error-resources-over-256-mb",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n for (let i = 0; i < 5; i++) device.createBuffer({ size: 64 * 1024 * 1024, usage: GPUBufferUsage.STORAGE })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 5: the size of buffers and textures is over the limit of 268435456",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["buffer",2,67108864,128],
["buffer",3,67108864,128],
["buffer",4,67108864,128],
["buffer",5,67108864,128],
["buffer",6,67108864,128]
]
}
]
}

View file

@ -0,0 +1,39 @@
{
"name": "error-submitted-twice",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const encoder = device.createCommandEncoder()\n encoder.beginRenderPass(clear(\"scene\")).end()\n const buffer = encoder.finish()\n device.queue.submit([buffer])\n device.queue.submit([buffer])\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 5: a command buffer can be submitted once",
"canvases": [
"scene"
]
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["view",2,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["submit"],
["error","a command buffer can be submitted once"],
["submit"]
]
}
]
}

View file

@ -0,0 +1,32 @@
{
"name": "error-texture-too-wide",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n device.createTexture({ size: [4097, 4], format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: \"texture\" argument 2 is over the limit of 4096",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["texture",2,4097,4,1,"rgba8unorm",4,1,1]
]
}
]
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,75 @@
{
"name": "error-too-many-passes",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n await widget.frame()\n const encoder = device.createCommandEncoder()\n for (let i = 0; i < 17; i++) encoder.beginRenderPass(clear(\"scene\")).end()\n device.queue.submit([encoder.finish()])\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 33: the number of render passes in a frame is over the limit of 16",
"canvases": [
"scene"
]
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"]
]
},
{
"frame": true,
"bytes": "",
"ops": [
["view",2,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["pass",{"colorAttachments":[{"view":2,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["end"],
["submit"]
]
}
]
}

View file

@ -0,0 +1,31 @@
{
"name": "error-unknown-canvas",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n const device = await widget.gpu.requestDevice()\n widget.gpu.getContext(\"elsewhere\").configure({ device, format: widget.gpu.getPreferredCanvasFormat() })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: no GPU canvas with key \"elsewhere\"",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"elsewhere","rgba8unorm","opaque"]
]
}
]
}

View file

@ -0,0 +1,32 @@
{
"name": "error-unknown-format",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n device.createTexture({ size: [4, 4], format: \"rg11b10ufloat\", usage: GPUTextureUsage.TEXTURE_BINDING })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: \"texture\" argument 5 must be one of rgba8unorm, rgba8unorm-srgb, bgra8unorm, r8unorm, rgba16float, depth24plus, depth32float",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["texture",2,4,4,1,"rg11b10ufloat",4,1,1]
]
}
]
}

View file

@ -0,0 +1,32 @@
{
"name": "error-usage-outside-the-subset",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n device.createBuffer({ size: 16, usage: 1 })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: \"buffer\" argument 3 must combine COPY_SRC, COPY_DST, INDEX, VERTEX, UNIFORM, STORAGE",
"canvases": "all"
}
],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["buffer",2,16,1]
]
}
]
}

View file

@ -0,0 +1,42 @@
{
"name": "handles-and-defaults",
"source": "async function main() {\n widget.render(ui.column([ui.canvas({ key: \"scene\", gpu: true, height: 100 })]))\n const device = await widget.gpu.requestDevice()\n const format = widget.gpu.getPreferredCanvasFormat()\n const contexts = {}\n for (const key of [\"scene\"]) {\n contexts[key] = widget.gpu.getContext(key)\n contexts[key].configure({ device, format })\n }\n const view = (key) => contexts[key].getCurrentTexture().createView()\n const clear = (key) => ({ colorAttachments: [{ view: view(key), loadOp: \"clear\", storeOp: \"store\" }] })\n\n const again = await widget.gpu.requestDevice()\n if (again !== device) throw new Error(\"one device per widget\")\n const texture = device.createTexture({ size: { width: 8, height: 8, depthOrArrayLayers: 6 }, format: \"rgba8unorm\", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, mipLevelCount: 2 })\n const cube = texture.createView({ dimension: \"cube\" })\n const layers = texture.createView()\n if (texture.createView({ dimension: \"cube\" }) !== cube) throw new Error(\"equal views are one handle\")\n device.createSampler()\n const layout = device.createBindGroupLayout({ entries: [\n { binding: 0, visibility: GPUShaderStage.FRAGMENT, texture: { viewDimension: \"cube\" } },\n { binding: 1, visibility: GPUShaderStage.FRAGMENT, sampler: {} },\n { binding: 2, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: \"read-only-storage\", hasDynamicOffset: true } },\n ] })\n const storage = device.createBuffer({ size: 512, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC })\n const copy = device.createBuffer({ size: 512, usage: GPUBufferUsage.COPY_DST })\n device.createBindGroup({ layout, entries: [\n { binding: 0, resource: cube },\n { binding: 1, resource: device.createSampler({ magFilter: \"linear\", compare: undefined }) },\n { binding: 2, resource: { buffer: storage, offset: 256, size: 64 } },\n ] })\n device.createPipelineLayout({ bindGroupLayouts: [layout] })\n device.queue.writeBuffer(storage, 4, new Uint32Array([1, 2, 3, 4, 5]), 1, 3)\n device.queue.writeBuffer(storage, 0, new Uint8Array([9, 8, 7, 6]).buffer)\n device.queue.writeTexture({ texture, mipLevel: 1, origin: [0, 0, 2] }, new Uint8Array(4 * 4 * 4).fill(200), { bytesPerRow: 16 }, { width: 4, height: 4 })\n const encoder = device.createCommandEncoder()\n encoder.copyBufferToBuffer(storage, 0, copy, 0, 256)\n device.queue.submit([encoder.finish()])\n texture.destroy()\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 200,
"height": 200
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "AgAAAAMAAAAEAAAACQgHBsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMg=",
"ops": [
["context",1,"scene","rgba8unorm","opaque"],
["texture",2,8,8,6,"rgba8unorm",6,2,1],
["view",3,2,{"dimension":"cube","baseMipLevel":0,"mipLevelCount":2,"baseArrayLayer":0,"arrayLayerCount":6}],
["view",4,2,{"dimension":"2d-array","baseMipLevel":0,"mipLevelCount":2,"baseArrayLayer":0,"arrayLayerCount":6}],
["sampler",5,{"addressModeU":"clamp-to-edge","addressModeV":"clamp-to-edge","addressModeW":"clamp-to-edge","magFilter":"nearest","minFilter":"nearest","mipmapFilter":"nearest","lodMinClamp":0,"lodMaxClamp":32,"compare":null,"maxAnisotropy":1}],
["bindGroupLayout",6,{"entries":[{"binding":0,"visibility":2,"buffer":null,"sampler":null,"texture":{"sampleType":"float","viewDimension":"cube","multisampled":false}},{"binding":1,"visibility":2,"buffer":null,"sampler":{"type":"filtering"},"texture":null},{"binding":2,"visibility":3,"buffer":{"type":"read-only-storage","hasDynamicOffset":true,"minBindingSize":0},"sampler":null,"texture":null}]}],
["buffer",7,512,140],
["buffer",8,512,8],
["sampler",9,{"addressModeU":"clamp-to-edge","addressModeV":"clamp-to-edge","addressModeW":"clamp-to-edge","magFilter":"linear","minFilter":"nearest","mipmapFilter":"nearest","lodMinClamp":0,"lodMaxClamp":32,"compare":null,"maxAnisotropy":1}],
["bindGroup",10,{"layout":6,"entries":[{"binding":0,"resource":{"view":3}},{"binding":1,"resource":{"sampler":9}},{"binding":2,"resource":{"buffer":7,"offset":256,"size":64}}]}],
["pipelineLayout",11,[6]],
["writeBuffer",7,4,0,12],
["writeBuffer",7,0,12,4],
["writeTexture",2,1,[0,0,2],16,64,16,null,[4,4,1]],
["copyBufferToBuffer",7,0,8,0,256],
["submit"],
["destroy",2]
]
}
]
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,111 @@
{
"name": "post-process",
"source": "// Render to a texture, then post-process it onto the canvas: a spinning triangle drawn offscreen, shown through a\n// vignette with a chromatic offset. `data.frames`: stop after that many frames (fixtures).\nconst SCENE = `\n@group(0) @binding(0) var<uniform> angle: vec4f;\n\nstruct Out { @builtin(position) position: vec4f, @location(0) color: vec3f }\n\n@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {\n let a = angle.x + f32(index) * 2.0943951;\n var out: Out;\n out.position = vec4f(cos(a) * 0.7, sin(a) * 0.7, 0.0, 1.0);\n var colors = array<vec3f, 3>(vec3f(1, 0.3, 0.2), vec3f(0.2, 1, 0.4), vec3f(0.3, 0.4, 1));\n out.color = colors[index];\n return out;\n}\n\n@fragment fn fs(in: Out) -> @location(0) vec4f {\n return vec4f(in.color, 1.0);\n}\n`\n\nconst POST = `\n@group(0) @binding(0) var linear: sampler;\n@group(0) @binding(1) var scene: texture_2d<f32>;\n\nstruct Out { @builtin(position) position: vec4f, @location(0) uv: vec2f }\n\n// One triangle that covers the screen.\n@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {\n let corner = vec2f(f32((index << 1u) & 2u), f32(index & 2u));\n var out: Out;\n out.position = vec4f(corner * 2.0 - 1.0, 0.0, 1.0);\n out.uv = vec2f(corner.x, 1.0 - corner.y);\n return out;\n}\n\n@fragment fn fs(in: Out) -> @location(0) vec4f {\n let offset = (in.uv - 0.5) * 0.01;\n let r = textureSample(scene, linear, in.uv + offset).r;\n let g = textureSample(scene, linear, in.uv).g;\n let b = textureSample(scene, linear, in.uv - offset).b;\n let vignette = 1.0 - dot(in.uv - 0.5, in.uv - 0.5) * 1.5;\n return vec4f(vec3f(r, g, b) * vignette, 1.0);\n}\n`\n\nasync function main(data) {\n widget.render(ui.canvas({ key: \"post\", gpu: true, height: 220, alt: \"A post-processed triangle\" }))\n const device = await widget.gpu.requestDevice()\n const context = widget.gpu.getContext(\"post\")\n const format = widget.gpu.getPreferredCanvasFormat()\n context.configure({ device, format })\n\n const sceneModule = device.createShaderModule({ code: SCENE })\n const scenePipeline = device.createRenderPipeline({\n layout: \"auto\",\n vertex: { module: sceneModule, entryPoint: \"vs\" },\n fragment: { module: sceneModule, entryPoint: \"fs\", targets: [{ format: \"rgba8unorm\" }] },\n })\n const angle = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST })\n const sceneGroup = device.createBindGroup({\n layout: scenePipeline.getBindGroupLayout(0),\n entries: [{ binding: 0, resource: { buffer: angle } }],\n })\n\n const postModule = device.createShaderModule({ code: POST })\n const postPipeline = device.createRenderPipeline({\n layout: \"auto\",\n vertex: { module: postModule, entryPoint: \"vs\" },\n fragment: { module: postModule, entryPoint: \"fs\", targets: [{ format }] },\n })\n const sampler = device.createSampler({ magFilter: \"linear\", minFilter: \"linear\" })\n\n // The offscreen texture and its bind group follow the canvas's size.\n const target = { texture: null, group: null, width: 0, height: 0 }\n for (let frame = 0; data?.frames === undefined || frame < data.frames; frame++) {\n const { t, width, height, scale } = await widget.frame()\n const w = context.width || Math.round(width * scale)\n const h = context.height || Math.round(height * scale)\n if (target.width !== w || target.height !== h) {\n target.texture?.destroy()\n target.texture = device.createTexture({\n size: [w, h],\n format: \"rgba8unorm\",\n usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,\n })\n target.group = device.createBindGroup({\n layout: postPipeline.getBindGroupLayout(0),\n entries: [\n { binding: 0, resource: sampler },\n { binding: 1, resource: target.texture.createView() },\n ],\n })\n Object.assign(target, { width: w, height: h })\n }\n device.queue.writeBuffer(angle, 0, new Float32Array([t, 0, 0, 0]))\n\n const encoder = device.createCommandEncoder()\n const scene = encoder.beginRenderPass({\n colorAttachments: [\n { view: target.texture.createView(), loadOp: \"clear\", storeOp: \"store\", clearValue: [0.1, 0.1, 0.12, 1] },\n ],\n })\n scene.setPipeline(scenePipeline)\n scene.setBindGroup(0, sceneGroup)\n scene.draw(3)\n scene.end()\n const post = encoder.beginRenderPass({\n colorAttachments: [{ view: context.getCurrentTexture().createView(), loadOp: \"clear\", storeOp: \"store\" }],\n })\n post.setPipeline(postPipeline)\n post.setBindGroup(0, target.group)\n post.draw(3)\n post.end()\n device.queue.submit([encoder.finish()])\n }\n}\n",
"data": {
"frames": 3
},
"canvases": [
{
"key": "post",
"width": 320,
"height": 220
}
],
"inputs": [
{
"frame": 1,
"input": {
"type": "canvas",
"key": "post",
"width": 640,
"height": 440
}
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [],
"end": "return",
"batches": [
{
"frame": true,
"bytes": "",
"ops": [
["context",1,"post","rgba8unorm","opaque"],
["shader",2,"\n@group(0) @binding(0) var<uniform> angle: vec4f;\n\nstruct Out { @builtin(position) position: vec4f, @location(0) color: vec3f }\n\n@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {\n let a = angle.x + f32(index) * 2.0943951;\n var out: Out;\n out.position = vec4f(cos(a) * 0.7, sin(a) * 0.7, 0.0, 1.0);\n var colors = array<vec3f, 3>(vec3f(1, 0.3, 0.2), vec3f(0.2, 1, 0.4), vec3f(0.3, 0.4, 1));\n out.color = colors[index];\n return out;\n}\n\n@fragment fn fs(in: Out) -> @location(0) vec4f {\n return vec4f(in.color, 1.0);\n}\n"],
["renderPipeline",3,{"layout":"auto","vertex":{"module":2,"entryPoint":"vs","buffers":[]},"fragment":{"module":2,"entryPoint":"fs","targets":[{"format":"rgba8unorm","blend":null,"writeMask":15}]},"primitive":{"topology":"triangle-list","stripIndexFormat":null,"frontFace":"ccw","cullMode":"none"},"depthStencil":null,"multisample":{"count":1,"mask":4294967295,"alphaToCoverageEnabled":false}}],
["buffer",4,16,72],
["autoLayout",5,3,0],
["bindGroup",6,{"layout":5,"entries":[{"binding":0,"resource":{"buffer":4,"offset":0,"size":-1}}]}],
["shader",7,"\n@group(0) @binding(0) var linear: sampler;\n@group(0) @binding(1) var scene: texture_2d<f32>;\n\nstruct Out { @builtin(position) position: vec4f, @location(0) uv: vec2f }\n\n// One triangle that covers the screen.\n@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {\n let corner = vec2f(f32((index << 1u) & 2u), f32(index & 2u));\n var out: Out;\n out.position = vec4f(corner * 2.0 - 1.0, 0.0, 1.0);\n out.uv = vec2f(corner.x, 1.0 - corner.y);\n return out;\n}\n\n@fragment fn fs(in: Out) -> @location(0) vec4f {\n let offset = (in.uv - 0.5) * 0.01;\n let r = textureSample(scene, linear, in.uv + offset).r;\n let g = textureSample(scene, linear, in.uv).g;\n let b = textureSample(scene, linear, in.uv - offset).b;\n let vignette = 1.0 - dot(in.uv - 0.5, in.uv - 0.5) * 1.5;\n return vec4f(vec3f(r, g, b) * vignette, 1.0);\n}\n"],
["renderPipeline",8,{"layout":"auto","vertex":{"module":7,"entryPoint":"vs","buffers":[]},"fragment":{"module":7,"entryPoint":"fs","targets":[{"format":"rgba8unorm","blend":null,"writeMask":15}]},"primitive":{"topology":"triangle-list","stripIndexFormat":null,"frontFace":"ccw","cullMode":"none"},"depthStencil":null,"multisample":{"count":1,"mask":4294967295,"alphaToCoverageEnabled":false}}],
["sampler",9,{"addressModeU":"clamp-to-edge","addressModeV":"clamp-to-edge","addressModeW":"clamp-to-edge","magFilter":"linear","minFilter":"linear","mipmapFilter":"nearest","lodMinClamp":0,"lodMaxClamp":32,"compare":null,"maxAnisotropy":1}]
]
},
{
"frame": true,
"bytes": "AAAAAAAAAAAAAAAAAAAAAA==",
"ops": [
["texture",10,320,220,1,"rgba8unorm",20,1,1],
["autoLayout",11,8,0],
["view",12,10,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["bindGroup",13,{"layout":11,"entries":[{"binding":0,"resource":{"sampler":9}},{"binding":1,"resource":{"view":12}}]}],
["writeBuffer",4,0,0,16],
["view",14,1,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["pass",{"colorAttachments":[{"view":12,"resolveTarget":null,"clearValue":[0.1,0.1,0.12,1],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",3],
["setBindGroup",0,6,[]],
["draw",3,1,0,0],
["end"],
["pass",{"colorAttachments":[{"view":14,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",8],
["setBindGroup",0,13,[]],
["draw",3,1,0,0],
["end"],
["submit"]
]
},
{
"frame": true,
"bytes": "iYiIPAAAAAAAAAAAAAAAAA==",
"ops": [
["destroy",10],
["texture",15,640,440,1,"rgba8unorm",20,1,1],
["view",16,15,{"dimension":"2d","baseMipLevel":0,"mipLevelCount":1,"baseArrayLayer":0,"arrayLayerCount":1}],
["bindGroup",17,{"layout":11,"entries":[{"binding":0,"resource":{"sampler":9}},{"binding":1,"resource":{"view":16}}]}],
["writeBuffer",4,0,0,16],
["pass",{"colorAttachments":[{"view":16,"resolveTarget":null,"clearValue":[0.1,0.1,0.12,1],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",3],
["setBindGroup",0,6,[]],
["draw",3,1,0,0],
["end"],
["pass",{"colorAttachments":[{"view":14,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",8],
["setBindGroup",0,17,[]],
["draw",3,1,0,0],
["end"],
["submit"]
]
},
{
"frame": false,
"bytes": "iYgIPQAAAAAAAAAAAAAAAA==",
"ops": [
["writeBuffer",4,0,0,16],
["pass",{"colorAttachments":[{"view":16,"resolveTarget":null,"clearValue":[0.1,0.1,0.12,1],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",3],
["setBindGroup",0,6,[]],
["draw",3,1,0,0],
["end"],
["pass",{"colorAttachments":[{"view":14,"resolveTarget":null,"clearValue":[0,0,0,0],"loadOp":"clear","storeOp":"store"}],"depthStencilAttachment":null}],
["setPipeline",8],
["setBindGroup",0,17,[]],
["draw",3,1,0,0],
["end"],
["submit"]
]
}
]
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-bad-enum",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"sampler\", 1, { addressModeU: \"wrap\", addressModeV: \"repeat\", addressModeW: \"repeat\", magFilter: \"nearest\", minFilter: \"nearest\", mipmapFilter: \"nearest\", lodMinClamp: 0, lodMaxClamp: 32, compare: null, maxAnisotropy: 1 }]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"sampler\" argument 2.addressModeU must be one of clamp-to-edge, repeat, mirror-repeat",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-bind-group-layout-entry",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"bindGroupLayout\", 1, { entries: [{ binding: 0, visibility: 2, buffer: null, sampler: null, texture: null }] }]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"bindGroupLayout\" argument 2.entries[0] needs exactly one of buffer, sampler and texture",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-bytes-out-of-range",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"buffer\", 1, 16, 8], [\"writeBuffer\", 1, 0, 4, 8]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: bytes [4, 12) are outside the batch's 8 bytes",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-draw-outside-a-pass",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"draw\", 3, 1, 0, 0]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"draw\" outside a render pass",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-handle-reused",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"buffer\", 1, 16, 32], [\"buffer\", 1, 16, 32]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: handle 1 was already used",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-handles-out-of-order",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"buffer\", 2, 16, 32], [\"buffer\", 1, 16, 32]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: handle 1 was already used",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-handles-over-4096",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: Array.from({ length: 4097 }, (_, i) => [\"shader\", i + 1, \"\"]), bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 4096: the number of live handles is over the limit of 4096",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-no-such-handle",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"destroy\", 9]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: no handle 9",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-not-a-list",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [{ op: \"buffer\" }], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: an op is a list that starts with its name",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-not-a-whole-number",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"buffer\", 1, 16.5, 8]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"buffer\" argument 2 must be a whole number",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-ops-over-20000",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: Array.from({ length: 20001 }, (_, i) => [\"shader\", i + 1, \"\"]), bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "the number of ops in a batch is over the limit of 20000",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,24 @@
{
"name": "raw-pass-left-open",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"context\", 1, \"scene\", \"rgba8unorm\", \"opaque\"], [\"view\", 2, 1, { dimension: \"2d\", baseMipLevel: 0, mipLevelCount: 1, baseArrayLayer: 0, arrayLayerCount: 1 }], [\"pass\", { colorAttachments: [{ view: 2, resolveTarget: null, clearValue: [0, 0, 0, 1], loadOp: \"clear\", storeOp: \"store\" }], depthStencilAttachment: null }]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "a render pass is still open at the end of the batch",
"canvases": [
"scene"
]
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-shader-over-256-kb",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"shader\", 1, \"x\".repeat(256 * 1024 + 1)]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"shader\" argument 2 is over the limit of 262144",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-unknown-op",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"sparkle\", 1]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: unknown op \"sparkle\"",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-wrong-arity",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"buffer\", 1, 16]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 0: \"buffer\" takes 3 arguments",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,22 @@
{
"name": "raw-wrong-kind",
"source": "async function main() {\n widget.render(ui.canvas({ key: \"scene\", gpu: true, height: 100 }))\n __host.post({ type: \"gpu\", ops: [[\"shader\", 1, \"\"], [\"destroy\", 1]], bytes: new ArrayBuffer(8) })\n await widget.frame()\n}",
"canvases": [
{
"key": "scene",
"width": 100,
"height": 100
}
],
"gpu": {
"available": true,
"format": "rgba8unorm"
},
"errors": [
{
"message": "gpu op 1: handle 1 is a shader, not a buffer or texture",
"canvases": "all"
}
],
"end": "return"
}

View file

@ -0,0 +1,161 @@
// A rotating, lit, depth-tested cube (widgets-gpu.md). `data.frames`: stop after that many frames (fixtures).
const SHADER = `
struct Uniforms { mvp: mat4x4f, model: mat4x4f }
@group(0) @binding(0) var<uniform> u: Uniforms;
struct Out { @builtin(position) position: vec4f, @location(0) normal: vec3f }
@vertex fn vs(@location(0) position: vec3f, @location(1) normal: vec3f) -> Out {
var out: Out;
out.position = u.mvp * vec4f(position, 1.0);
out.normal = (u.model * vec4f(normal, 0.0)).xyz;
return out;
}
@fragment fn fs(in: Out) -> @location(0) vec4f {
let light = normalize(vec3f(0.4, 0.8, 0.6));
let lit = 0.2 + 0.8 * max(dot(normalize(in.normal), light), 0.0);
return vec4f(vec3f(0.3, 0.6, 1.0) * lit, 1.0);
}
`
// Column-major 4x4 matrices, as WGSL reads them.
function multiply(a, b) {
const out = new Float32Array(16)
for (let column = 0; column < 4; column++)
for (let row = 0; row < 4; row++) {
let sum = 0
for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[column * 4 + k]
out[column * 4 + row] = sum
}
return out
}
// A perspective projection to WebGPU's depth range, 0 to 1.
function perspective(fovy, aspect, near, far) {
const f = 1 / Math.tan(fovy / 2)
// prettier-ignore
return new Float32Array([f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far / (near - far), -1, 0, 0, (near * far) / (near - far), 0])
}
function rotation(x, y) {
const [cx, sx, cy, sy] = [Math.cos(x), Math.sin(x), Math.cos(y), Math.sin(y)]
return new Float32Array([cy, sx * sy, -cx * sy, 0, 0, cx, sx, 0, sy, -sx * cy, cx * cy, 0, 0, 0, 0, 1])
}
const translation = (x, y, z) => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1])
// Each face: its normal and its 4 corners; 24 vertices of position and normal, 36 indices.
function cube() {
// prettier-ignore
const faces = [
[[1, 0, 0], [[1, -1, -1], [1, 1, -1], [1, 1, 1], [1, -1, 1]]],
[[-1, 0, 0], [[-1, -1, 1], [-1, 1, 1], [-1, 1, -1], [-1, -1, -1]]],
[[0, 1, 0], [[-1, 1, -1], [-1, 1, 1], [1, 1, 1], [1, 1, -1]]],
[[0, -1, 0], [[-1, -1, 1], [-1, -1, -1], [1, -1, -1], [1, -1, 1]]],
[[0, 0, 1], [[1, -1, 1], [1, 1, 1], [-1, 1, 1], [-1, -1, 1]]],
[[0, 0, -1], [[-1, -1, -1], [-1, 1, -1], [1, 1, -1], [1, -1, -1]]],
]
const vertices = []
const indices = []
faces.forEach(([normal, corners], face) => {
corners.forEach((corner) => vertices.push(...corner, ...normal))
const at = face * 4
indices.push(at, at + 1, at + 2, at, at + 2, at + 3)
})
return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices) }
}
async function main(data) {
widget.render(ui.canvas({ key: "cube", gpu: true, height: 240, alt: "A rotating cube" }))
const device = await widget.gpu.requestDevice()
const context = widget.gpu.getContext("cube")
const format = widget.gpu.getPreferredCanvasFormat()
context.configure({ device, format, alphaMode: "opaque" })
const mesh = cube()
const vertices = device.createBuffer({
size: mesh.vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
})
device.queue.writeBuffer(vertices, 0, mesh.vertices)
const indices = device.createBuffer({
size: mesh.indices.byteLength,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
})
device.queue.writeBuffer(indices, 0, mesh.indices)
const uniforms = device.createBuffer({ size: 128, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST })
const module = device.createShaderModule({ code: SHADER })
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module,
entryPoint: "vs",
buffers: [
{
arrayStride: 24,
attributes: [
{ format: "float32x3", offset: 0, shaderLocation: 0 },
{ format: "float32x3", offset: 12, shaderLocation: 1 },
],
},
],
},
fragment: { module, entryPoint: "fs", targets: [{ format }] },
primitive: { topology: "triangle-list", cullMode: "back" },
depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" },
})
const group = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: uniforms } }],
})
const depth = { texture: null, width: 0, height: 0 }
for (let frame = 0; data?.frames === undefined || frame < data.frames; frame++) {
const { t, width, height, scale } = await widget.frame()
const w = context.width || Math.round(width * scale)
const h = context.height || Math.round(height * scale)
// The depth texture follows the canvas's size.
if (depth.width !== w || depth.height !== h) {
depth.texture?.destroy()
depth.texture = device.createTexture({
size: [w, h],
format: "depth24plus",
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
Object.assign(depth, { width: w, height: h })
}
const model = rotation(t * 0.7, t)
const mvp = multiply(perspective(Math.PI / 4, w / h, 0.1, 100), multiply(translation(0, 0, -6), model))
const matrices = new Float32Array(32)
matrices.set(mvp, 0)
matrices.set(model, 16)
device.queue.writeBuffer(uniforms, 0, matrices)
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadOp: "clear",
storeOp: "store",
clearValue: [0.05, 0.05, 0.08, 1],
},
],
depthStencilAttachment: {
view: depth.texture.createView(),
depthClearValue: 1,
depthLoadOp: "clear",
depthStoreOp: "store",
},
})
pass.setPipeline(pipeline)
pass.setBindGroup(0, group)
pass.setVertexBuffer(0, vertices)
pass.setIndexBuffer(indices, "uint16")
pass.drawIndexed(36)
pass.end()
device.queue.submit([encoder.finish()])
}
}

View file

@ -0,0 +1,252 @@
// A first-person maze: walls as a few hundred instanced boxes, WASD to walk, a click captures the pointer for
// mouse-look, and a HUD in a stack over the canvas. `data.frames`: stop after that many frames (fixtures).
const SHADER = `
struct Uniforms { viewProjection: mat4x4f, eye: vec4f }
@group(0) @binding(0) var<uniform> u: Uniforms;
struct Out { @builtin(position) position: vec4f, @location(0) normal: vec3f, @location(1) world: vec3f, @location(2) tint: f32 }
@vertex fn vs(@location(0) position: vec3f, @location(1) normal: vec3f, @location(2) offset: vec3f, @location(3) size: vec3f) -> Out {
let world = position * size + offset;
var out: Out;
out.position = u.viewProjection * vec4f(world, 1.0);
out.normal = normal;
out.world = world;
out.tint = select(1.0, 0.55, size.y < 0.5);
return out;
}
@fragment fn fs(in: Out) -> @location(0) vec4f {
let light = normalize(vec3f(0.3, 1.0, 0.5));
let lit = 0.35 + 0.65 * max(dot(in.normal, light), 0.0);
let fog = clamp(distance(in.world, u.eye.xyz) / 14.0, 0.0, 1.0);
let color = vec3f(0.85, 0.75, 0.6) * in.tint * lit;
return vec4f(mix(color, vec3f(0.08, 0.09, 0.12), fog), 1.0);
}
`
const SIZE = 21
// A maze of SIZE x SIZE cells (true: wall), carved by a depth-first walk from a seeded generator.
function maze(seed) {
let state = seed
const random = () => (state = (state * 1103515245 + 12345) % 2147483648) / 2147483648
const walls = Array.from({ length: SIZE }, () => Array(SIZE).fill(true))
const stack = [[1, 1]]
walls[1][1] = false
while (stack.length > 0) {
const [x, z] = stack[stack.length - 1]
const next = [
[2, 0],
[-2, 0],
[0, 2],
[0, -2],
]
.map(([dx, dz]) => [x + dx, z + dz, dx, dz])
.filter(([nx, nz]) => nx > 0 && nz > 0 && nx < SIZE - 1 && nz < SIZE - 1 && walls[nz][nx])
if (next.length === 0) {
stack.pop()
continue
}
const [nx, nz, dx, dz] = next[Math.floor(random() * next.length)]
walls[z + dz / 2][x + dx / 2] = false
walls[nz][nx] = false
stack.push([nx, nz])
}
return walls
}
// A unit box: 24 vertices of position and normal, 36 indices.
function box() {
// prettier-ignore
const faces = [
[[1, 0, 0], [[1, -1, -1], [1, 1, -1], [1, 1, 1], [1, -1, 1]]],
[[-1, 0, 0], [[-1, -1, 1], [-1, 1, 1], [-1, 1, -1], [-1, -1, -1]]],
[[0, 1, 0], [[-1, 1, -1], [-1, 1, 1], [1, 1, 1], [1, 1, -1]]],
[[0, -1, 0], [[-1, -1, 1], [-1, -1, -1], [1, -1, -1], [1, -1, 1]]],
[[0, 0, 1], [[1, -1, 1], [1, 1, 1], [-1, 1, 1], [-1, -1, 1]]],
[[0, 0, -1], [[-1, -1, -1], [-1, 1, -1], [1, 1, -1], [1, -1, -1]]],
]
const vertices = []
const indices = []
faces.forEach(([normal, corners], face) => {
corners.forEach((corner) => vertices.push(...corner.map((c) => c / 2), ...normal))
indices.push(face * 4, face * 4 + 1, face * 4 + 2, face * 4, face * 4 + 2, face * 4 + 3)
})
return { vertices: new Float32Array(vertices), indices: new Uint16Array(indices) }
}
function perspective(fovy, aspect, near, far) {
const f = 1 / Math.tan(fovy / 2)
return [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, far / (near - far), -1, 0, 0, (near * far) / (near - far), 0]
}
// The view matrix of an eye at `eye` looking along yaw and pitch.
function view(eye, yaw, pitch) {
const forward = [Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)]
const right = [Math.cos(yaw), 0, Math.sin(yaw)]
const up = [
right[1] * forward[2] - right[2] * forward[1],
right[2] * forward[0] - right[0] * forward[2],
right[0] * forward[1] - right[1] * forward[0],
]
const dot = (a) => a[0] * eye[0] + a[1] * eye[1] + a[2] * eye[2]
// prettier-ignore
return [right[0], up[0], -forward[0], 0, right[1], up[1], -forward[1], 0, right[2], up[2], -forward[2], 0, -dot(right), -dot(up), dot(forward), 1]
}
function multiply(a, b) {
const out = new Float32Array(16)
for (let column = 0; column < 4; column++)
for (let row = 0; row < 4; row++) {
let sum = 0
for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[column * 4 + k]
out[column * 4 + row] = sum
}
return out
}
async function main(data) {
const walls = maze(7)
const player = { x: 1.5, z: 1.5, yaw: Math.PI / 2, pitch: 0, captured: false }
const hud = () =>
widget.render(
ui.stack([
ui.canvas({
key: "maze",
gpu: true,
height: 360,
place: "fill",
alt: "A first-person maze",
// Under pointer capture, moves are relative: they turn the camera.
onPointer: (p) => {
if (p.dx !== undefined) {
player.yaw += p.dx * 0.004
player.pitch = Math.max(-1.2, Math.min(1.2, player.pitch - p.dy * 0.004))
} else if (p.kind === "down" && !player.captured) widget.capturePointer()
},
}),
ui.text(player.captured ? "WASD to walk, Esc to let go" : "Click to look around", {
place: "top-left",
inset: 8,
}),
]),
)
widget.on("capture", (captured) => {
player.captured = captured
hud()
})
hud()
const device = await widget.gpu.requestDevice()
const context = widget.gpu.getContext("maze")
const format = widget.gpu.getPreferredCanvasFormat()
context.configure({ device, format })
// One instance per wall cell, and one flat one for the floor: offset and size.
const instances = []
walls.forEach((row, z) => row.forEach((wall, x) => wall && instances.push(x + 0.5, 0.5, z + 0.5, 1, 1, 1)))
instances.push(SIZE / 2, -0.05, SIZE / 2, SIZE, 0.1, SIZE)
const instanceData = new Float32Array(instances)
const mesh = box()
const make = (array, usage) => {
const buffer = device.createBuffer({ size: array.byteLength, usage: usage | GPUBufferUsage.COPY_DST })
device.queue.writeBuffer(buffer, 0, array)
return buffer
}
const vertices = make(mesh.vertices, GPUBufferUsage.VERTEX)
const indices = make(mesh.indices, GPUBufferUsage.INDEX)
const instanceBuffer = make(instanceData, GPUBufferUsage.VERTEX)
const uniforms = device.createBuffer({ size: 80, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST })
const module = device.createShaderModule({ code: SHADER })
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module,
entryPoint: "vs",
buffers: [
{
arrayStride: 24,
attributes: [
{ format: "float32x3", offset: 0, shaderLocation: 0 },
{ format: "float32x3", offset: 12, shaderLocation: 1 },
],
},
{
arrayStride: 24,
stepMode: "instance",
attributes: [
{ format: "float32x3", offset: 0, shaderLocation: 2 },
{ format: "float32x3", offset: 12, shaderLocation: 3 },
],
},
],
},
fragment: { module, entryPoint: "fs", targets: [{ format }] },
primitive: { cullMode: "back" },
depthStencil: { format: "depth24plus", depthWriteEnabled: true, depthCompare: "less" },
})
const group = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: uniforms } }],
})
const open = (x, z) => !walls[Math.floor(z)]?.[Math.floor(x)]
const depth = { texture: null, width: 0, height: 0 }
for (let frame = 0; data?.frames === undefined || frame < data.frames; frame++) {
const { dt, width, height, scale } = await widget.frame()
// Walk, sliding along walls: each axis moves only into open cells, keeping 0.2 from them.
const keys = widget.keys
const ahead = (keys.has("KeyW") ? 1 : 0) - (keys.has("KeyS") ? 1 : 0)
const side = (keys.has("KeyD") ? 1 : 0) - (keys.has("KeyA") ? 1 : 0)
const speed = 2.5 * dt
const dx = (Math.sin(player.yaw) * ahead + Math.cos(player.yaw) * side) * speed
const dz = (-Math.cos(player.yaw) * ahead + Math.sin(player.yaw) * side) * speed
if (open(player.x + dx + Math.sign(dx) * 0.2, player.z)) player.x += dx
if (open(player.x, player.z + dz + Math.sign(dz) * 0.2)) player.z += dz
const w = context.width || Math.round(width * scale)
const h = context.height || Math.round(height * scale)
if (depth.width !== w || depth.height !== h) {
depth.texture?.destroy()
depth.texture = device.createTexture({
size: [w, h],
format: "depth24plus",
usage: GPUTextureUsage.RENDER_ATTACHMENT,
})
Object.assign(depth, { width: w, height: h })
}
const eye = [player.x, 0.6, player.z]
const matrices = new Float32Array(20)
matrices.set(multiply(perspective(1.2, w / h, 0.05, 50), view(eye, player.yaw, player.pitch)), 0)
matrices.set([...eye, 1], 16)
device.queue.writeBuffer(uniforms, 0, matrices)
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadOp: "clear",
storeOp: "store",
clearValue: [0.08, 0.09, 0.12, 1],
},
],
depthStencilAttachment: {
view: depth.texture.createView(),
depthClearValue: 1,
depthLoadOp: "clear",
depthStoreOp: "store",
},
})
pass.setPipeline(pipeline)
pass.setBindGroup(0, group)
pass.setVertexBuffer(0, vertices)
pass.setVertexBuffer(1, instanceBuffer)
pass.setIndexBuffer(indices, "uint16")
pass.drawIndexed(36, instances.length / 6)
pass.end()
device.queue.submit([encoder.finish()])
}
}

View file

@ -0,0 +1,117 @@
// Render to a texture, then post-process it onto the canvas: a spinning triangle drawn offscreen, shown through a
// vignette with a chromatic offset. `data.frames`: stop after that many frames (fixtures).
const SCENE = `
@group(0) @binding(0) var<uniform> angle: vec4f;
struct Out { @builtin(position) position: vec4f, @location(0) color: vec3f }
@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {
let a = angle.x + f32(index) * 2.0943951;
var out: Out;
out.position = vec4f(cos(a) * 0.7, sin(a) * 0.7, 0.0, 1.0);
var colors = array<vec3f, 3>(vec3f(1, 0.3, 0.2), vec3f(0.2, 1, 0.4), vec3f(0.3, 0.4, 1));
out.color = colors[index];
return out;
}
@fragment fn fs(in: Out) -> @location(0) vec4f {
return vec4f(in.color, 1.0);
}
`
const POST = `
@group(0) @binding(0) var linear: sampler;
@group(0) @binding(1) var scene: texture_2d<f32>;
struct Out { @builtin(position) position: vec4f, @location(0) uv: vec2f }
// One triangle that covers the screen.
@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {
let corner = vec2f(f32((index << 1u) & 2u), f32(index & 2u));
var out: Out;
out.position = vec4f(corner * 2.0 - 1.0, 0.0, 1.0);
out.uv = vec2f(corner.x, 1.0 - corner.y);
return out;
}
@fragment fn fs(in: Out) -> @location(0) vec4f {
let offset = (in.uv - 0.5) * 0.01;
let r = textureSample(scene, linear, in.uv + offset).r;
let g = textureSample(scene, linear, in.uv).g;
let b = textureSample(scene, linear, in.uv - offset).b;
let vignette = 1.0 - dot(in.uv - 0.5, in.uv - 0.5) * 1.5;
return vec4f(vec3f(r, g, b) * vignette, 1.0);
}
`
async function main(data) {
widget.render(ui.canvas({ key: "post", gpu: true, height: 220, alt: "A post-processed triangle" }))
const device = await widget.gpu.requestDevice()
const context = widget.gpu.getContext("post")
const format = widget.gpu.getPreferredCanvasFormat()
context.configure({ device, format })
const sceneModule = device.createShaderModule({ code: SCENE })
const scenePipeline = device.createRenderPipeline({
layout: "auto",
vertex: { module: sceneModule, entryPoint: "vs" },
fragment: { module: sceneModule, entryPoint: "fs", targets: [{ format: "rgba8unorm" }] },
})
const angle = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST })
const sceneGroup = device.createBindGroup({
layout: scenePipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: angle } }],
})
const postModule = device.createShaderModule({ code: POST })
const postPipeline = device.createRenderPipeline({
layout: "auto",
vertex: { module: postModule, entryPoint: "vs" },
fragment: { module: postModule, entryPoint: "fs", targets: [{ format }] },
})
const sampler = device.createSampler({ magFilter: "linear", minFilter: "linear" })
// The offscreen texture and its bind group follow the canvas's size.
const target = { texture: null, group: null, width: 0, height: 0 }
for (let frame = 0; data?.frames === undefined || frame < data.frames; frame++) {
const { t, width, height, scale } = await widget.frame()
const w = context.width || Math.round(width * scale)
const h = context.height || Math.round(height * scale)
if (target.width !== w || target.height !== h) {
target.texture?.destroy()
target.texture = device.createTexture({
size: [w, h],
format: "rgba8unorm",
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
})
target.group = device.createBindGroup({
layout: postPipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: sampler },
{ binding: 1, resource: target.texture.createView() },
],
})
Object.assign(target, { width: w, height: h })
}
device.queue.writeBuffer(angle, 0, new Float32Array([t, 0, 0, 0]))
const encoder = device.createCommandEncoder()
const scene = encoder.beginRenderPass({
colorAttachments: [
{ view: target.texture.createView(), loadOp: "clear", storeOp: "store", clearValue: [0.1, 0.1, 0.12, 1] },
],
})
scene.setPipeline(scenePipeline)
scene.setBindGroup(0, sceneGroup)
scene.draw(3)
scene.end()
const post = encoder.beginRenderPass({
colorAttachments: [{ view: context.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store" }],
})
post.setPipeline(postPipeline)
post.setBindGroup(0, target.group)
post.draw(3)
post.end()
device.queue.submit([encoder.finish()])
}
}

View file

@ -0,0 +1,87 @@
// A quad with a texture built in script: a checkerboard with a gradient, sampled with linear filtering and repeat.
// `data.frames`: stop after that many frames (fixtures).
const SHADER = `
struct Out { @builtin(position) position: vec4f, @location(0) uv: vec2f }
@vertex fn vs(@builtin(vertex_index) index: u32) -> Out {
var corners = array<vec2f, 6>(vec2f(-1, -1), vec2f(1, -1), vec2f(1, 1), vec2f(-1, -1), vec2f(1, 1), vec2f(-1, 1));
let corner = corners[index];
var out: Out;
out.position = vec4f(corner * 0.8, 0.0, 1.0);
out.uv = (corner * vec2f(0.5, -0.5) + 0.5) * 2.0;
return out;
}
@group(0) @binding(0) var linear: sampler;
@group(0) @binding(1) var image: texture_2d<f32>;
@fragment fn fs(in: Out) -> @location(0) vec4f {
return textureSample(image, linear, in.uv);
}
`
// 64 x 64 RGBA pixels: 8-pixel squares, tinted by position.
function checkerboard(size) {
const pixels = new Uint8Array(size * size * 4)
for (let y = 0; y < size; y++)
for (let x = 0; x < size; x++) {
const on = ((x >> 3) + (y >> 3)) % 2 === 0
const at = (y * size + x) * 4
pixels[at] = on ? 255 : Math.round((x / size) * 255)
pixels[at + 1] = on ? 255 : 64
pixels[at + 2] = on ? 255 : Math.round((y / size) * 255)
pixels[at + 3] = 255
}
return pixels
}
async function main(data) {
widget.render(ui.canvas({ key: "quad", gpu: true, height: 200, alt: "A textured quad" }))
const device = await widget.gpu.requestDevice()
const context = widget.gpu.getContext("quad")
const format = widget.gpu.getPreferredCanvasFormat()
context.configure({ device, format })
const size = 64
const texture = device.createTexture({
size: [size, size],
format: "rgba8unorm",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
})
device.queue.writeTexture({ texture }, checkerboard(size), { bytesPerRow: size * 4 }, [size, size])
const sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear",
addressModeU: "repeat",
addressModeV: "repeat",
})
const module = device.createShaderModule({ code: SHADER })
const pipeline = device.createRenderPipeline({
layout: "auto",
vertex: { module, entryPoint: "vs" },
fragment: { module, entryPoint: "fs", targets: [{ format }] },
})
const group = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: sampler },
{ binding: 1, resource: texture.createView() },
],
})
for (let frame = 0; data?.frames === undefined || frame < data.frames; frame++) {
await widget.frame()
const encoder = device.createCommandEncoder()
const pass = encoder.beginRenderPass({
colorAttachments: [
{ view: context.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 1] },
],
})
pass.setPipeline(pipeline)
pass.setBindGroup(0, group)
pass.draw(6)
pass.end()
device.queue.submit([encoder.finish()])
}
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,192 @@
import { expect, test } from "bun:test"
import { Glob } from "bun"
import path from "node:path"
import { fixtures, run } from "../script/gpu-conformance.js"
import { LiveWidget, type LiveMessage, ManualClock, program, step } from "../src/index.js"
// The GPU conformance fixtures (`fixtures/gpu/*.json`, widgets-gpu.md): every host posts the same batches for each
// program, and its checks give the same program errors. This holds the TypeScript host to them.
const dir = path.resolve(import.meta.dir, "fixtures/gpu")
const files = [...new Glob("*.json").scanSync(dir)].toSorted()
test("there is a fixture for every case, the example widget templates among them", () => {
expect(files.map((file) => file.replace(/\.json$/, "")).toSorted()).toEqual(
fixtures()
.map((item) => item.name)
.toSorted(),
)
for (const name of ["cube", "textured-quad", "post-process", "maze"]) expect(files).toContain(`${name}.json`)
})
for (const file of files) {
test(`gpu fixture ${file}`, async () => {
const fixture = await Bun.file(path.join(dir, file)).json()
const item = fixtures().find((candidate) => candidate.name === fixture.name)!
expect(item.source).toBe(fixture.source)
const recorded = await run(item)
if (fixture.batches) expect(recorded.batches).toEqual(fixture.batches)
expect(recorded.errors).toEqual(fixture.errors)
expect(recorded.end).toBe(fixture.end)
}, 60_000)
}
// A live run on a manual clock; `posts` holds its GPU batches, `sent` what it sends.
const start = (source: string, options: { readonly gpu?: false } = {}) => {
const clock = new ManualClock()
const posts: LiveMessage[] = []
const sent: unknown[] = []
const widget = LiveWidget.start(program(source), null, {
clock,
...options,
onMessage: (message) => {
if (message.type === "gpu" || (message.type === "frame" && message.gpu)) posts.push(message)
if (message.type === "send") sent.push(message.value)
},
})
return { widget, clock, posts, sent }
}
const size = { t: 0, dt: 1 / 60, width: 100, height: 50, scale: 2, pointer: null, dark: false }
test("without a GPU the program runs unchanged and records nothing", async () => {
const { widget, posts, sent } = start(
`async function main() {
widget.render(ui.canvas({ key: "c", gpu: true, height: 10 }))
const device = await widget.gpu.requestDevice()
widget.gpu.getContext("c").configure({ device, format: widget.gpu.getPreferredCanvasFormat() })
const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.VERTEX })
device.queue.writeBuffer(buffer, 0, new Float32Array(4))
device.queue.submit([device.createCommandEncoder().finish()])
widget.send([widget.gpu.available, typeof device.lost.then, device.limits.maxTextureDimension2D])
}`,
{ gpu: false },
)
expect(await widget.done).toEqual({ type: "return" })
expect(posts).toEqual([])
expect(sent).toEqual([[false, "function", 4096]])
expect(widget.gpuErrors).toEqual([])
})
test("canvas sizes, a lost device, and batches before sleeps and at the end", async () => {
const sent: unknown[] = []
const clock = new ManualClock()
const posts: LiveMessage[] = []
const widget = LiveWidget.start(
program(`async function main() {
widget.render(ui.canvas({ key: "c", gpu: true, height: 10 }))
const context = widget.gpu.getContext("c")
try { context.getCurrentTexture() } catch (error) { widget.send(error.message) }
const device = await widget.gpu.requestDevice()
context.configure({ device, format: "rgba8unorm" })
await widget.frame()
widget.send([context.width, context.height, context.getCurrentTexture().width])
device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM })
await widget.sleep(10)
const lost = await device.lost
widget.send(lost)
device.createBuffer({ size: 4, usage: GPUBufferUsage.UNIFORM })
const again = await widget.gpu.requestDevice()
widget.send(again === device)
context.configure({ device: again, format: "rgba8unorm" })
again.createBuffer({ size: 8, usage: GPUBufferUsage.UNIFORM })
}`),
null,
{
clock,
onMessage: (message) => {
if (message.type === "send") sent.push(message.value)
if (message.type === "gpu" || (message.type === "frame" && message.gpu)) posts.push(message)
},
},
)
widget.canvas("c", 200, 100)
await widget.when((current) => current.frameRequested)
widget.frame(size)
await clock.advance(10)
widget.loseDevice("unknown")
expect(await widget.done).toEqual({ type: "return" })
expect(sent).toEqual([
"configure the context before getCurrentTexture",
[200, 100, 200],
{ reason: "unknown", message: "" },
false,
])
const ops = posts.map((post) => (post.type === "frame" ? post.gpu!.ops : post.type === "gpu" ? post.ops : []))
expect(posts.map((post) => post.type)).toEqual(["frame", "gpu", "gpu"])
expect(ops).toEqual([
[["context", 1, "c", "rgba8unorm", "opaque"]],
[["buffer", 2, 4, 64]],
// The lost device's buffer records nothing (its handle, 3, is spent); the new device's context is a new handle.
[
["context", 4, "c", "rgba8unorm", "opaque"],
["buffer", 5, 8, 64],
],
])
expect(widget.gpuErrors).toEqual([])
})
test("a GPU canvas takes no draw commands, and can't have wgsl too", async () => {
const { widget } = start(`async function main() {
widget.render(ui.canvas({ key: "c", gpu: true, height: 10 }))
widget.draw("c", [])
}`)
expect(await widget.done).toMatchObject({
type: "error",
error: { message: expect.stringContaining(`Canvas "c" is drawn by the GPU; it takes no draw commands`) },
})
const both = await step(program(`function view() { return ui.canvas({ height: 1, gpu: true, wgsl: "x" }) }`), {
phase: "init",
data: null,
}).catch((error: unknown) => error)
expect(both).toMatchObject({
kind: "invalid",
message: expect.stringContaining("`gpu` and `wgsl` exclude each other"),
})
})
test("writes copy their data when they are called, and typed arrays count elements", async () => {
const { widget, posts } = start(`async function main() {
widget.render(ui.canvas({ key: "c", gpu: true, height: 10 }))
const device = await widget.gpu.requestDevice()
const buffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.COPY_DST })
const data = new Uint16Array([1, 2, 3, 4])
device.queue.writeBuffer(buffer, 0, data, 1, 2)
data[1] = 9
device.queue.writeBuffer(buffer, 4, data.buffer, 2, 2)
}`)
await widget.done
const batch = posts[0]!
expect(batch.type === "gpu" && batch.ops).toEqual([
["buffer", 1, 16, 8],
["writeBuffer", 1, 0, 0, 4],
["writeBuffer", 1, 4, 4, 2],
])
expect(batch.type === "gpu" && [...new Uint8Array(batch.bytes)]).toEqual([2, 0, 3, 0, 9, 0])
})
test("a GPU batch takes no token but never overtakes a waiting render; a bare frame request doesn't wait", async () => {
const clock = new ManualClock()
const order: string[] = []
const widget = LiveWidget.start(
program(`async function main() {
for (let i = 0; i < 9; i++) widget.render(ui.column([ui.text(String(i)), ui.canvas({ key: "c" + i, gpu: true, height: 10 })]))
const device = await widget.gpu.requestDevice()
widget.gpu.getContext("c8").configure({ device, format: "rgba8unorm" })
await widget.sleep(1)
await widget.frame()
}`),
null,
{
clock,
postsPerSecond: 1,
onMessage: (message) => order.push(message.type === "render" ? "render" : message.type),
},
)
await clock.advance(0)
// 8 renders at once; the 9th waits for a token, and the batch (whose canvas only it has) waits behind it.
expect(order).toEqual(Array(8).fill("render"))
await clock.advance(1000)
// The bare frame request, posted after the batch, went at once.
expect(order).toEqual([...Array(8).fill("render"), "frame", "render", "gpu"])
expect(widget.gpuErrors).toEqual([])
await widget.stop()
})

View file

@ -84,7 +84,11 @@ const trees = async (source: string, data: unknown) => {
if (!result.ok) throw new Error(result.error.message)
const host = tree(crossed.view, "Argument 1 to __cross")
return [
JSON.stringify([host.view, [...host.handlers], Object.fromEntries(host.canvases)]),
JSON.stringify([
host.view,
[...host.handlers],
Object.fromEntries([...host.canvases].map(([key, canvas]) => [key, { id: canvas.id, wgsl: canvas.wgsl }])),
]),
result.value as string,
] as const
}

View file

@ -108,6 +108,7 @@ today.
| 17 | value | f64 (slider), str (input, one-value select), str list (multiple select) | 35 | pointer | int |
| 18 | min | f64 | 36 | place | int: top-left 0, top 1, top-right 2, left 3, center 4, right 5, bottom-left 6, bottom 7, bottom-right 8, fill 9 |
| | | | 37 | inset | f64 (all sides) or f64 list of 4 (top, right, bottom, left) |
| | | | 38 | gpu | int (a GPU canvas, `widgets-gpu.md`) |
**Rules for the encoder** (`write_node`). It writes the props the tree has, in its key order:
- `type` and `children` are never props.

View file

@ -141,9 +141,9 @@ and hands the actual transfer to the app (URLSession / OkHttp), so system TLS an
## Lifecycle and budgets
- The client starts `<program>\nreturn await __widget_live(__input(), true)` (input `{ data }`) when an open live
widget first becomes visible, on its own thread or task, never the UI thread. Render the last `render` node; before
the first one, show a loading frame.
- The client starts `<program>\nreturn await __widget_live(__input(), true)` (input `{ data, gpu? }`, `gpu` per
`widgets-gpu.md`) when an open live widget first becomes visible, on its own thread or task, never the UI thread.
Render the last `render` node; before the first one, show a loading frame.
- **Pause when not visible.** When a live widget scrolls out of view, its window or app goes to the background, or the
session is closed, the client pauses the program: no frames, events or timer firings are delivered, `sleep` timers
freeze with their remaining time, `now()` stops, and in-flight `fetch` results are held until resume. When the widget

View file

@ -352,7 +352,8 @@ type Node = (
| { type: "divider" }
| { type: "canvas"; id?: string; height: number; width?: number; fps?: number; duration?: number; alt?: string;
poster?: string; wgsl?: string; values?: number[] // values only with wgsl
pointer?: true } // set by the prelude when it has onPointer: only then does it take input
pointer?: true // set by the prelude when it has onPointer: only then does it take input
gpu?: true } // drawn by a live program's widget.gpu (widgets-gpu.md); not with wgsl
| { type: "stack"; children: Node[] }
) & {
// Any node, as a child of a stack (see Stack); ignored elsewhere.