Skip to content

Concept1 of 5

How the kit works

One frame written in plain TypeGPU, then piece by piece with the kit, and the seven rules every module follows.

On this page

TypeGPU Kit is a set of modules for TypeGPU. Your program keeps the GPU device, the loop and every command. Each module takes over one piece you would otherwise write by hand, such as textures that follow the canvas size, a glow or a pool of particles.

This page writes one frame in plain TypeGPU, then moves it onto the kit one piece at a time. Each step introduces one of the seven rules every module follows, yours included.

The frame draws rings that ripple out from the middle of the canvas. A small program on the GPU, a kernel, moves the ripple forward each frame, and a fragment function colours every pixel from it.

Try Turn on Glow to add the bloom from A module borrows. This is the frame this page builds.

TypeGPU starts from a root, which holds the GPU device and creates everything else. A pipeline holds one or more GPU functions compiled with the settings they run with. The program asks the root for two pieces of GPU memory and two pipelines:

import {
import common
common
,
import d
d
,
import std
std
,
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
} from 'typegpu';
const
const root: TgpuRoot
root
= await
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
init: (options?: InitOptions) => Promise<TgpuRoot>

Requests a new GPU device and creates a root around it. If a specific device should be used instead, use

@see ― initFromDevice. *

@example

When given no options, the function will ask the browser for a suitable GPU device.

const root = await tgpu.init();

@example

If there are specific options that should be used when requesting a device, you can pass those in.

const adapterOptions: GPURequestAdapterOptions = ...;
const deviceDescriptor: GPUDeviceDescriptor = ...;
const root = await tgpu.init({ adapter: adapterOptions, device: deviceDescriptor });

init
();
const
const context: GPUCanvasContext
context
=
const root: TgpuRoot
root
.
TgpuRoot.configureContext(options: ConfigureContextOptions): GPUCanvasContext

Creates and configures context for the provided canvas. Automatically sets the format to navigator.gpu.getPreferredCanvasFormat() if not provided.

@throws ― An error if no context could be obtained

configureContext
({
canvas: HTMLCanvasElement | OffscreenCanvas

The canvas for which a context will be created and configured.

canvas
:
var document: Document

window.document returns a reference to the document contained in the window.

MDN Reference

document
.
ParentNode.querySelector<"canvas">(selectors: "canvas"): HTMLCanvasElement | null (+4 overloads)

Returns the first element that is a descendant of node that matches selectors.

MDN Reference

querySelector
('canvas')! });
const
const tint: TgpuUniform<d.Vec4f>
tint
=
const root: TgpuRoot
root
.
TgpuRoot.createUniform<d.Vec4f>(typeSchema: d.Vec4f, initial?: ((buffer: TgpuBuffer<NoInfer<d.Vec4f>>) => void) | d.InferInput<NoInfer<d.Vec4f>> | undefined): TgpuUniform<d.Vec4f> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for small data. For a general-purpose buffer, use

TgpuRoot.createBuffer

.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createUniform
(
import d
d
.
const vec4f: d.Vec4f
vec4f
,
import d
d
.
const vec4f: d.Vec4f
(x: number, y: number, z: number, w: number) => d.v4f (+9 overloads)
vec4f
(0.2, 0.6, 1, 1)); // written by the CPU
const
const phase: TgpuMutable<d.F32>
phase
=
const root: TgpuRoot
root
.
TgpuRoot.createMutable<d.F32>(typeSchema: d.F32, initial?: number | ((buffer: TgpuBuffer<NoInfer<d.F32>>) => void) | undefined): TgpuMutable<d.F32> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Can be mutated in-place on the GPU. For a general-purpose buffer, use

TgpuRoot.createBuffer

.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createMutable
(
import d
d
.
const f32: d.F32
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
); // written by the kernel
const
const advance: TgpuComputeFn<{}>
advance
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
computeFn: (options: {
workgroupSize: number[];
}) => TgpuComputeFnShell<{}> (+1 overload)
computeFn
({
workgroupSize: number[]
workgroupSize
: [1] })(() => {
'use gpu';
const phase: TgpuMutable<d.F32>
phase
.
TgpuMutable<F32>.$: number
$
+= 0.05;
});
const
const rings: TgpuFragmentFn<{
uv: d.Vec2f;
}, d.Vec4f>
rings
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
fragmentFn: <{
uv: d.Vec2f;
}, d.Vec4f>(options: {
in: {
uv: d.Vec2f;
};
out: d.Vec4f;
}) => TgpuFragmentFnShell<{
uv: d.Vec2f;
}, d.Vec4f> (+1 overload)
fragmentFn
({
in: {
uv: d.Vec2f;
}
in
: {
uv: d.Vec2f
uv
:
import d
d
.
const vec2f: d.Vec2f
vec2f
},
out: d.Vec4f
out
:
import d
d
.
const vec4f: d.Vec4f
vec4f
})(({
uv: d.v2f
uv
}) => {
'use gpu';
const
const wave: number
wave
=
import std
std
.
function sin(value: number): number (+1 overload)
export sin
sin
(
import std
std
.
length<d.v2f>(value: d.v2f): number (+1 overload)
export length
length
(
uv: d.v2f
uv
-
import d
d
.
const vec2f: d.Vec2f
(xy: number) => d.v2f (+3 overloads)
vec2f
(0.5)) * 40 -
const phase: TgpuMutable<d.F32>
phase
.
TgpuMutable<F32>.$: number
$
) * 0.5 + 0.5;
return
const tint: TgpuUniform<d.Vec4f>
tint
.
TgpuUniform<Vec4f>.$: d.v4f
$
*
const wave: number
wave
;
});
const
const advancing: TgpuComputePipeline
advancing
=
const root: TgpuRoot
root
.
WithBinding.createComputePipeline<{}>(descriptor: TgpuComputePipeline.Descriptor<{}>): TgpuComputePipeline
createComputePipeline
({
compute: TgpuComputeFn<{}>
compute
:
const advance: TgpuComputeFn<{}>
advance
});
const
const drawing: TgpuRenderPipeline<d.Vec4f>
drawing
=
const root: TgpuRoot
root
.
WithBinding.createRenderPipeline<{}, {}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}, d.Vec4f>(descriptor: TgpuRenderPipeline<in Targets = never>.DescriptorBase & {
attribs?: {} | undefined;
vertex: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>);
fragment: TgpuFragmentFn<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<...>) => d.v4f | (AnyAutoCustoms & Partial<...>));
targets?: TgpuColorTargetState;
}): TgpuRenderPipeline<...> (+2 overloads)
createRenderPipeline
({
vertex: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>)
vertex
:
import common
common
.
const fullScreenTriangle: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}>
export fullScreenTriangle

A vertex function that defines a single full-screen triangle out of three points.

@example

import { common } from 'typegpu';
const pipeline = root.createRenderPipeline({
vertex: common.fullScreenTriangle,
fragment: yourFragmentShader,
});
pipeline.draw(3);

fullScreenTriangle
,
fragment: TgpuFragmentFn<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<InferGPURecord<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}>>) => d.v4f | (AnyAutoCustoms & Partial<InferGPURecord<{
readonly $fragDepth: import("node_modules/typegpu/builtin").BuiltinFragDepth;
readonly $sampleMask: import("node_modules/typegpu/builtin").BuiltinSampleMask;
}>>))
fragment
:
const rings: TgpuFragmentFn<{
uv: d.Vec2f;
}, d.Vec4f>
rings
, // draws in the canvas's format
});
  • 'use gpu' marks a function TypeGPU compiles for the GPU. Inside one, +, -, * and / work on vectors such as d.vec2f.
  • A uniform holds a few values that are the same for every pixel. The CPU writes it. A mutable buffer is memory that kernels write. A shader reads either through .$.
  • configureContext connects the canvas to the root’s device. Its format and a pipeline’s both default to the browser’s preferred format.
  • common.fullScreenTriangle is TypeGPU’s vertex function for one triangle that covers the canvas. It hands each pixel its uv, which runs from 0 to 1 across the canvas.
  • Compiling a pipeline takes time, so a program creates its pipelines once, before the first frame.

The GPU doesn’t run commands as they are called. An encoder records them. Work goes into passes: a compute pass runs kernels, and a render pass draws into textures. A submit sends what the encoder recorded to the GPU, which runs it in order:

function
function frame(): void
frame
() {
const
const encoder: TgpuCommandEncoder
encoder
=
const root: TgpuRoot
root
.
TgpuRoot.createCommandEncoder(descriptor?: GPUCommandEncoderDescriptor): TgpuCommandEncoder

Creates a

TgpuCommandEncoder

for batching multiple render/compute passes (and draws within them) into a single submission.

@example

const encoder = root.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [{ view: msaaTexture, resolveTarget: context }],
});
scenePipeline.with(pass).draw(vertexCount);
skyPipeline.with(pass).draw(3);
pass.end();
encoder.submit();

createCommandEncoder
();
const
const compute: TgpuComputePass
compute
=
const encoder: TgpuCommandEncoder
encoder
.
TgpuCommandEncoder.beginComputePass(descriptor?: TgpuComputePassDescriptor): TgpuComputePass

Begins recording a compute pass

beginComputePass
();
const compute: TgpuComputePass
compute
.
TgpuComputePass.setPipeline(pipeline: TgpuComputePipeline): void

Sets the current

TgpuComputePipeline

for subsequent dispatches

setPipeline
(
const advancing: TgpuComputePipeline
advancing
);
const compute: TgpuComputePass
compute
.
TgpuComputePass.dispatchWorkgroups(x: number, y?: number, z?: number): void
dispatchWorkgroups
(1); // runs the kernel once
const compute: TgpuComputePass
compute
.
TgpuComputePass.end(): void

Completes the recording of this compute pass

end
();
const
const pass: TgpuRenderPass
pass
=
const encoder: TgpuCommandEncoder
encoder
.
TgpuCommandEncoder.beginRenderPass(descriptor: TgpuRenderPassDescriptor): TgpuRenderPass

Begins recording a render pass. Attachment views accept TypeGPU textures, texture views and canvas contexts, next to raw

GPUTextureView

s.

beginRenderPass
({
TgpuRenderPassDescriptor.colorAttachments?: ColorAttachment | readonly (ColorAttachment | null)[] | undefined
colorAttachments
: {
ColorAttachment.view: GPUCanvasContext | GPUTextureView | (ColorTextureConstraint & RenderFlag) | TgpuTextureView<d.WgslTexture<WgslTextureProps>> | TgpuTextureRenderView

A

GPUTextureView

describing the texture subresource that will be output to for this color attachment.

view
:
const context: GPUCanvasContext
context
.
GPUCanvasContext.getCurrentTexture(): GPUTexture (+1 overload)

Get the

GPUTexture

that will be composited to the document by the

GPUCanvasContext

next. Note: The same

GPUTexture

object will be returned by every call to

GPUCanvasContext#getCurrentTexture

until "[$Expire the current texture$]" runs, even if that

GPUTexture

is destroyed, failed validation, or failed to allocate.

getCurrentTexture
().
GPUTexture.createView(descriptor?: GPUTextureViewDescriptor): GPUTextureView (+1 overload)

Creates a

GPUTextureView

.

@param ― descriptor - Description of the GPUTextureView to create.

createView
() },
});
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.setPipeline(pipeline: TgpuRenderPipeline): void

Sets the current

TgpuRenderPipeline

for subsequent draw calls

setPipeline
(
const drawing: TgpuRenderPipeline<never>
drawing
);
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void
draw
(3); // the triangle's three corners
const pass: TgpuRenderPass
pass
.
TgpuRenderPass.end(): void

Completes the recording of this render pass

end
();
const encoder: TgpuCommandEncoder
encoder
.
TgpuCommandEncoder.submit(): void

Finishes the recording and submits the resulting command buffer to the device queue

submit
(); // one command buffer for the whole frame
function requestAnimationFrame(callback: FrameRequestCallback): number
requestAnimationFrame
(
function frame(): void
frame
);
}
function requestAnimationFrame(callback: FrameRequestCallback): number
requestAnimationFrame
(
function frame(): void
frame
);

A larger program also needs a loop with time, textures that follow the canvas size, effects such as a glow, and thousands of objects. The kit’s modules provide those.

The kit’s frames runs the loop part of frame(). It creates the encoder, calls your function with it, and submits once your function returns. web.surface configures the canvas and follows its size. The passes stay yours:

import {
import frames
frames
} from '@typegpu/kit';
import * as
import web
web
from '@typegpu/kit/web';
const
const surface: web.Surface
surface
=
import web
web
.
function surface(root: TgpuRoot, canvas: HTMLCanvasElement, options?: web.SurfaceOptions): web.Surface

Configures a canvas for the root. Matches its drawing buffer to the layout size or the fixed options.size. Throws if the fixed size is invalid.

@param ― canvas the canvas it configures and sizes

@returns ― a surface you draw into and destroy

surface
(
const root: TgpuRoot
root
,
const canvas: HTMLCanvasElement
canvas
);
const
const loop: frames.Frames
loop
=
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

@submits ― always once a frame after your recorder returns, and again at each frame.submit()

@param ― record your frame, recorded into each frame's encoder

@returns ― a loop you run with each frame's time and destroy

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const
const compute: TgpuComputePass
compute
=
frame: frames.Frame
frame
.
Frame.encoder: TgpuCommandEncoder

Records commands for submission after the recorder returns. submit() replaces this encoder. Read it at each call instead of keeping it, and let the frame submit it.

encoder
.
TgpuCommandEncoder.beginComputePass(descriptor?: TgpuComputePassDescriptor): TgpuComputePass

Begins recording a compute pass

beginComputePass
();
const compute: TgpuComputePass
compute
.
TgpuComputePass.setPipeline(pipeline: TgpuComputePipeline): void

Sets the current

TgpuComputePipeline

for subsequent dispatches

setPipeline
(
const advancing: TgpuComputePipeline
advancing
);
const compute: TgpuComputePass
compute
.
TgpuComputePass.dispatchWorkgroups(x: number, y?: number, z?: number): void
dispatchWorkgroups
(1);
const compute: TgpuComputePass
compute
.
TgpuComputePass.end(): void

Completes the recording of this compute pass

end
();
const
const pass: TgpuRenderPass
pass
=
frame: frames.Frame
frame
.
Frame.encoder: TgpuCommandEncoder

Records commands for submission after the recorder returns. submit() replaces this encoder. Read it at each call instead of keeping it, and let the frame submit it.

encoder
.
TgpuCommandEncoder.beginRenderPass(descriptor: TgpuRenderPassDescriptor): TgpuRenderPass

Begins recording a render pass. Attachment views accept TypeGPU textures, texture views and canvas contexts, next to raw

GPUTextureView

s.

beginRenderPass
({
TgpuRenderPassDescriptor.colorAttachments?: ColorAttachment | readonly (ColorAttachment | null)[] | undefined
colorAttachments
: {
ColorAttachment.view: GPUTextureView | (ColorTextureConstraint & RenderFlag) | TgpuTextureView<WgslTexture<WgslTextureProps>> | TgpuTextureRenderView | GPUCanvasContext

A

GPUTextureView

describing the texture subresource that will be output to for this color attachment.

view
:
const surface: web.Surface
surface
.
Surface.view(frame: frames.Frame): GPUTextureView

Returns a view of the current canvas texture, created once per texture. Applies pending size changes first, which a pass using context would skip.

view
(
frame: frames.Frame
frame
) } });
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.setPipeline(pipeline: TgpuRenderPipeline): void

Sets the current

TgpuRenderPipeline

for subsequent draw calls

setPipeline
(
const drawing: TgpuRenderPipeline<never>
drawing
);
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void
draw
(3);
const pass: TgpuRenderPass
pass
.
TgpuRenderPass.end(): void

Completes the recording of this render pass

end
();
}); // submits frame.encoder after this returns
import frames
frames
.
function animate(loop: Pick<frames.Frames, "run"> & Partial<Pick<frames.Frames, "seconds">>, options?: frames.AnimateOptions): frames.Animation
export animate

Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps back, and stops while the surface is paused. Destroying the animation keeps the loop alive. Another animation on the same loop continues from its recorded time. A frame error, or a run that returns false because the loop was destroyed, stops the animation.

@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before

@returns ― an animation you destroy to stop the frames

animate
(
const loop: frames.Frames
loop
); // runs the loop at every animation frame

frame holds the encoder, the time in seconds and dt, the seconds since the last frame.

The first rule is that your program owns the device, the loop, the encoder, the passes and the submit. No module submits during a frame. Each records into a pass or an encoder you hand it, so the GPU runs the frame in the order of your calls.

A glow makes the bright rings bleed light. It needs the frame drawn into a texture with more range than the canvas, a high dynamic range (HDR) texture. A blur then reads that texture. Three modules cover it:

  • targets holds a set of textures that follow the canvas size. fit() replaces them when the size changes.
  • bloom blurs the bright parts of a texture into a glow texture.
  • finish, the final pass, brings HDR colour into the canvas’s range and adds the glow.
import {
import bloom
bloom
,
import finish
finish
,
import targets
targets
} from '@typegpu/kit';
const
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
=
import targets
targets
.
function create<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>(root: TgpuRoot, source: targets.SizeSource, specs: {
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}, options?: targets.Options): targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>

Creates render targets that follow a size. Replaces the whole set when the size changes. Put targets needed only sometimes in their own set and create that set when needed. Throws for transient targets with sampling, storage or mip levels, for multisampled targets with storage or mip levels, and for layered targets that are multisampled, mipped or have more layers than the device allows.

@param ― source the size it follows, such as a surface

@param ― specs a format and options per target, by name

@param ― options.resolution the fraction of each side drawn, which changes without allocating

@returns ― a set of targets you fit every frame and destroy

create
(
const root: TgpuRoot
root
,
const surface: web.Surface
surface
, {
hdr: {
readonly format: "rgba16float";
readonly sampled: true;
}
hdr
: {
format: "rgba16float"
format
: 'rgba16float',
sampled: true
sampled
: true } });
const
const hdr: () => targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
hdr
= () =>
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.textures: {
readonly hdr: targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>;
}

Provides the current textures. A size change replaces them.

textures
.
hdr: targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
hdr
;
const
const glow: bloom.Bloom
glow
=
import bloom
bloom
.
function create(root: TgpuRoot, options: bloom.Options): bloom.Bloom

Creates bloom from a chain of half-size textures. Each level downsamples with 13 taps, then a tent filter adds it to the next larger level. The result is mip 0 of output, at half the source size. With region, passes draw and sample only that region; changing the region allocates nothing.

@allocates ― on resize: a new chain and the bind groups of its passes; so does a new source

@owns ― targets, a sampler, 3 pipelines, 2 bind groups and a buffer per level: the chain of glow levels, the settings, a group for each pass, and the region each pass reads

@records ― record after whatever wrote the source; then output holds the glow.

@param ― options.source the HDR picture, read at every record

@param ― options.region the part of the source that holds the picture, read at every record

@returns ― a bloom you record every frame and destroy

create
(
const root: TgpuRoot
root
, {
Options.source: Source

Provides the HDR picture: a rendered picture, such as aa, or a function returning a texture, such as () => screen.textures.hdr. record reads it on every call, so the texture can be rebuilt.

@cpu

source
:
const hdr: () => targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
hdr
});
const
const final: finish.Finish
final
=
import finish
finish
.
function create(root: TgpuRoot, options: finish.Options): finish.Finish

Creates the final pass of a frame. It reads the source, adds glow, tone maps, grades, applies the vignette, encodes and dithers. It draws one triangle into the caller pass.

@allocates ― on resize: a bind group for a new source or glow

@owns ― 2 buffers, a sampler, a pipeline, 2 bind groups: the settings, the regions it reads, a group for the glow and one for each texture the source returns

@records ― record into a pass of its own on the view you give, usually the canvas's, or draw into the caller's pass, after the bloom's record.

@param ― options.source the picture, rendered or a texture, read at every draw

@param ― options.region the part of the source that holds the picture, read at every draw

@param ― options.glow a bloom, or a glow of your own, added before tone mapping

@param ― options.exposure an adapted exposure, read on the GPU

@returns ― a final pass you draw every frame

create
(
const root: TgpuRoot
root
, {
Options.format: GPUTextureFormat

Sets the output format, such as the canvas format.

format
:
const surface: web.Surface
surface
.
Surface.format: GPUTextureFormat

Reports the format of its textures, which pipelines that draw into it target.

format
,
Options.source: Source

Provides the picture at any size: a rendered picture, such as aa or blur, or a function returning a texture, such as () => screen.textures.hdr. draw reads it on every call, so the texture can be rebuilt.

@cpu

source
:
const hdr: () => targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
hdr
,
Options.glow?: Rendered | undefined

Adds a bloom, or a glow of your own such as an emission target, before tone mapping. draw reads its output and region on every call. Default none.

glow
});
const
const drawing: TgpuRenderPipeline<d.Vec4f>
drawing
=
const root: TgpuRoot
root
.
WithBinding.createRenderPipeline<{}, {}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}, d.Vec4f>(descriptor: TgpuRenderPipeline<in Targets = never>.DescriptorBase & {
attribs?: {} | undefined;
vertex: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>);
fragment: TgpuFragmentFn<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<...>) => d.v4f | (AnyAutoCustoms & Partial<...>));
targets?: TgpuColorTargetState;
}): TgpuRenderPipeline<...> (+2 overloads)
createRenderPipeline
({
vertex: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>)
vertex
:
import common
common
.
const fullScreenTriangle: TgpuVertexFn<{}, {
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}>
export fullScreenTriangle

A vertex function that defines a single full-screen triangle out of three points.

@example

import { common } from 'typegpu';
const pipeline = root.createRenderPipeline({
vertex: common.fullScreenTriangle,
fragment: yourFragmentShader,
});
pipeline.draw(3);

fullScreenTriangle
,
fragment: TgpuFragmentFn<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<InferGPURecord<{
uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
}>>) => d.v4f | (AnyAutoCustoms & Partial<InferGPURecord<{
readonly $fragDepth: import("node_modules/typegpu/builtin").BuiltinFragDepth;
readonly $sampleMask: import("node_modules/typegpu/builtin").BuiltinSampleMask;
}>>))
fragment
:
const rings: TgpuFragmentFn<{
uv: d.Vec2f;
}, d.Vec4f>
rings
,
targets?: TgpuColorTargetState
targets
: {
format?: GPUTextureFormat | undefined

The

GPUTextureFormat

of this color target. The pipeline will only be compatible with

GPURenderPassEncoder

s which use a

GPUTextureView

of this format in the corresponding color attachment.

@default ― navigator.gpu.getPreferredCanvasFormat()

format
: 'rgba16float' }, // into the HDR texture now
});
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

@submits ― always once a frame after your recorder returns, and again at each frame.submit()

@param ― record your frame, recorded into each frame's encoder

@returns ― a loop you run with each frame's time and destroy

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.fit(): boolean

Rebuilds all textures if the source size changed, destroying the old textures first. Updates regions for the current resolution. Returns true after a rebuild so callers can update bind groups that hold old textures. Call before recording passes that use the targets. A rebuild that throws destroys what it made and leaves the set unfitted, so the next call rebuilds it.

fit
();
const
const pass: TgpuRenderPass
pass
=
frame: frames.Frame
frame
.
Frame.encoder: TgpuCommandEncoder

Records commands for submission after the recorder returns. submit() replaces this encoder. Read it at each call instead of keeping it, and let the frame submit it.

encoder
.
TgpuCommandEncoder.beginRenderPass(descriptor: TgpuRenderPassDescriptor): TgpuRenderPass

Begins recording a render pass. Attachment views accept TypeGPU textures, texture views and canvas contexts, next to raw

GPUTextureView

s.

beginRenderPass
({
TgpuRenderPassDescriptor.colorAttachments?: ColorAttachment | readonly (ColorAttachment | null)[] | undefined
colorAttachments
: {
ColorAttachment.view: TgpuTextureRenderView | (ColorTextureConstraint & RenderFlag) | GPUTextureView | TgpuTextureView<d.WgslTexture<WgslTextureProps>> | GPUCanvasContext

A

GPUTextureView

describing the texture subresource that will be output to for this color attachment.

view
:
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.views: {
readonly hdr: GPUTextureView;
}

Provides attachment views of mip 0, created once per rebuild.

views
.
hdr: GPUTextureView
hdr
} });
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.setPipeline(pipeline: TgpuRenderPipeline): void

Sets the current

TgpuRenderPipeline

for subsequent draw calls

setPipeline
(
const drawing: TgpuRenderPipeline<d.Vec4f>
drawing
);
const pass: TgpuRenderPass
pass
.
TgpuRenderCommands.draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void
draw
(3);
const pass: TgpuRenderPass
pass
.
TgpuRenderPass.end(): void

Completes the recording of this render pass

end
();
const glow: bloom.Bloom
glow
.
Bloom.record(target: frames.Frame | TgpuCommandEncoder, options?: Timed): void

Records bloom passes after the source is written. Optional timer writes measure the passes together.

record
(
frame: frames.Frame
frame
); // opens its own passes
const final: finish.Finish
final
.
Finish.record(target: frames.Frame | TgpuCommandEncoder, view: GPUTextureView, options?: finish.RecordOptions): void

Opens a pass on view, such as surface.view(frame), draws into it and ends it. A viewport draws the picture into that rectangle and clears the rest, transparent with alpha: 'premultiplied' and black otherwise. Optional timer writes measure the pass.

record
(
frame: frames.Frame
frame
,
const surface: web.Surface
surface
.
Surface.view(frame: frames.Frame): GPUTextureView

Returns a view of the current canvas texture, created once per texture. Applies pending size changes first, which a pass using context would skip.

view
(
frame: frames.Frame
frame
));
});

Each module came from a factory, create(root, options). A factory allocates what the module needs and returns a handle:

  • Resources, as TypeGPU objects you read and write. glow.settings is a uniform, so glow.settings.patch({ threshold: 0.8 }) changes the threshold. glow.output is the glow texture, which your own passes can sample.
  • Recording methods, such as glow.record(frame), which record into what you pass them.
  • 'use gpu' functions your shaders can call, on modules that have them, such as particles’ emit.
  • destroy(), which frees what the module made and nothing it borrowed. glow.destroy() frees the glow’s textures, and the screen’s stay.

The second rule is that a module is a factory that borrows. It takes the root and the resources you hand it, and destroys only what it made, so two glows share nothing. A takes the smallest piece of the frame it needs. One that adds to a pass you opened takes the pass. One that records passes or copies of its own takes the frame or its encoder. One that works after the submit takes the frame. Maths on the CPU takes numbers, as view.update(frame.dt) does.

The figure shows a larger frame: a flow field, particles, a and a glow, each recording into the one encoder. Turn a module off to see what it recorded.

One frame's passes and the resources they read and write

    Try Turn a module off to remove its calls or passes. Point at a resource to follow it from the writing pass to its readers.

    Next to plain WebGPU, TypeGPU and a such as three.js, the kit keeps TypeGPU’s shaders and schemas and leaves you the passes and the submit:

    WebGPU TypeGPU TypeGPU Kit Three.js
    Shaders WGSL strings TypeScript marked 'use gpu' TypeGPU shader functions built-in materials, TSL for your own
    Memory layout byte offsets, by hand schemas such as d.struct TypeGPU schemas and tables attributes and uniforms it uploads
    Objects rows in buffers a scene graph of Object3D
    Passes and order yours yours yours; modules record into them the renderer’s
    The submit yours yours, or one per call without an encoder yours, once a frame the renderer’s
    Reusable pieces functions, and accessors modules that borrow your root classes and add-ons

    Creating GPU objects during a frame costs time and memory the frame can’t spare. A pipeline compiled during a frame stalls it. So the modules allocate when you create them, compile in initAsync, and only record during frames:

    await Promise.all([
    advancing.initAsync(),
    drawing.initAsync(),
    glow.initAsync(),
    final.initAsync(),
    ]);

    After that a steady frame creates no GPU objects. The figure runs a scene on a recording root. A recording root needs no GPU and counts what the device creates. Run a frame twice and the counts stay put.

    A recording root's counters and command log

    WGSL in log.shaders
    Try Press frame again to see that a steady frame allocates nothing, with changed counters highlighted. Reset and run a frame before initAsync() to see compilation on first use. steps sets how many fixed steps a frame records.

    The third rule is that costs are stated and checked. Each module’s page ends with a card generated from its source, and the card states the module’s costs:

    • allocates names anything a module creates after setup, such as the a video feed makes for each camera frame it copies.
    • owns lists what the module allocates.
    • binds counts the and uniforms its shaders add. WebGPU guarantees 8 storage buffers per shader stage, so the counts tell you what fits in one pipeline.
    • records says where its work goes and in which order.
    • injects names the accessors it fills, which the next section explains.
    • submits setup marks the few calls that submit on their own, such as meshPool.add without an encoder, so you make them while loading.

    recordingRoot() runs your own scene the same way in a test.

    The ripple can become a module too. The colouring shader reads its phase through an accessor, a typed value that shader code reads and a pipeline can refill. Make the accessor inside createRipple, with that ripple’s phase as its default. heightAt then carries its own fill:

    export function
    function createRipple(root: TgpuRoot): {
    heightAt: (uv: d.v2f) => number;
    step: (pass: TgpuComputePass) => void;
    }
    createRipple
    (
    root: TgpuRoot
    root
    :
    (alias) interface TgpuRoot
    import TgpuRoot
    TgpuRoot
    ) {
    const
    const phase: TgpuMutable<d.F32>
    phase
    =
    root: TgpuRoot
    root
    .
    TgpuRoot.createMutable<d.F32>(typeSchema: d.F32, initial?: number | ((buffer: TgpuBuffer<NoInfer<d.F32>>) => void) | undefined): TgpuMutable<d.F32> (+1 overload)

    Allocates memory on the GPU, allows passing data between host and shader. Can be mutated in-place on the GPU. For a general-purpose buffer, use

    TgpuRoot.createBuffer

    .

    @param ― typeSchema The type of data that this buffer will hold.

    @param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

    createMutable
    (
    import d
    d
    .
    const f32: d.F32
    export f32

    A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

    Can also be called to cast a value to an f32.

    @example const value = f32(); // 0

    @example const value = f32(1.23); // 1.23

    @example const value = f32(true); // 1

    f32
    );
    const
    const ripple: TgpuAccessor<d.F32>
    ripple
    =
    const tgpu: {
    const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
    fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
    comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
    resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
    resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
    init: typeof import("node_modules/typegpu/core/root/init").init;
    initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
    slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
    lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
    ... 10 more ...;
    '~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
    }

    @module ― typegpu

    tgpu
    .
    accessor: <d.F32>(schema: d.F32, defaultValue?: DataAccessorIn<NoInfer<d.F32>> | undefined) => TgpuAccessor<d.F32> (+1 overload)
    accessor
    (
    import d
    d
    .
    const f32: d.F32
    export f32

    A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

    Can also be called to cast a value to an f32.

    @example const value = f32(); // 0

    @example const value = f32(1.23); // 1.23

    @example const value = f32(true); // 1

    f32
    ,
    const phase: TgpuMutable<d.F32>
    phase
    );
    const
    const advance: TgpuComputeFn<{}>
    advance
    =
    const tgpu: {
    const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
    fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
    comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
    resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
    resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
    init: typeof import("node_modules/typegpu/core/root/init").init;
    initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
    slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
    lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
    ... 10 more ...;
    '~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
    }

    @module ― typegpu

    tgpu
    .
    computeFn: (options: {
    workgroupSize: number[];
    }) => TgpuComputeFnShell<{}> (+1 overload)
    computeFn
    ({
    workgroupSize: number[]
    workgroupSize
    : [1] })(() => {
    'use gpu';
    const phase: TgpuMutable<d.F32>
    phase
    .
    TgpuMutable<F32>.$: number
    $
    += 0.05;
    });
    const
    const advancing: TgpuComputePipeline
    advancing
    =
    root: TgpuRoot
    root
    .
    WithBinding.createComputePipeline<{}>(descriptor: TgpuComputePipeline.Descriptor<{}>): TgpuComputePipeline
    createComputePipeline
    ({
    compute: TgpuComputeFn<{}>
    compute
    :
    const advance: TgpuComputeFn<{}>
    advance
    });
    return {
    heightAt: (uv: d.v2f) => number
    heightAt
    : (
    uv: d.v2f
    uv
    :
    import d
    d
    .
    export v2f

    Interface representing its WGSL vector type counterpart: vec2f or vec2. A vector with 2 elements of type f32

    v2f
    ) => {
    'use gpu';
    return
    import std
    std
    .
    function sin(value: number): number (+1 overload)
    export sin
    sin
    (
    import std
    std
    .
    length<d.v2f>(value: d.v2f): number (+1 overload)
    export length
    length
    (
    uv: d.v2f
    uv
    -
    import d
    d
    .
    const vec2f: d.Vec2f
    (xy: number) => d.v2f (+3 overloads)
    vec2f
    (0.5)) * 40 -
    const ripple: TgpuAccessor<d.F32>
    ripple
    .
    TgpuAccessor<F32>.$: number
    $
    ) * 0.5 + 0.5;
    },
    step: (pass: TgpuComputePass) => void
    step
    : (
    pass: TgpuComputePass
    pass
    :
    (alias) interface TgpuComputePass
    import TgpuComputePass

    A compute pass recording into a

    TgpuCommandEncoder

    .

    Dispatch either by binding TypeGPU pipelines to it (pipeline.with(pass).dispatchWorkgroups(...)), or proxy-style via pass.setPipeline(pipeline) followed by pass.dispatchWorkgroups(...).

    Call end() when done recording.

    TgpuComputePass
    ) => {
    pass: TgpuComputePass
    pass
    .
    TgpuComputePass.setPipeline(pipeline: TgpuComputePipeline): void

    Sets the current

    TgpuComputePipeline

    for subsequent dispatches

    setPipeline
    (
    const advancing: TgpuComputePipeline
    advancing
    );
    pass: TgpuComputePass
    pass
    .
    TgpuComputePass.dispatchWorkgroups(x: number, y?: number, z?: number): void
    dispatchWorkgroups
    (1);
    },
    };
    }

    A shader that calls heightAt reads that ripple, and its pipeline needs :

    const
    const rings: TgpuFragmentFn<{
    uv: d.Vec2f;
    }, d.Vec4f>
    rings
    =
    const tgpu: {
    const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
    fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
    comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
    resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
    resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
    init: typeof import("node_modules/typegpu/core/root/init").init;
    initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
    slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
    lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
    ... 10 more ...;
    '~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
    }

    @module ― typegpu

    tgpu
    .
    fragmentFn: <{
    uv: d.Vec2f;
    }, d.Vec4f>(options: {
    in: {
    uv: d.Vec2f;
    };
    out: d.Vec4f;
    }) => TgpuFragmentFnShell<{
    uv: d.Vec2f;
    }, d.Vec4f> (+1 overload)
    fragmentFn
    ({
    in: {
    uv: d.Vec2f;
    }
    in
    : {
    uv: d.Vec2f
    uv
    :
    import d
    d
    .
    const vec2f: d.Vec2f
    vec2f
    },
    out: d.Vec4f
    out
    :
    import d
    d
    .
    const vec4f: d.Vec4f
    vec4f
    })(({
    uv: d.v2f
    uv
    }) => {
    'use gpu';
    return
    import d
    d
    .
    const vec4f: d.Vec4f
    (x: number, y: number, z: number, w: number) => d.v4f (+9 overloads)
    vec4f
    (0.2, 0.6, 1, 1) *
    const ripple: {
    heightAt(uv: d.v2f): number;
    }
    ripple
    .
    function heightAt(uv: d.v2f): number
    heightAt
    (
    uv: d.v2f
    uv
    );
    });
    const
    const drawing: TgpuRenderPipeline<d.Vec4f>
    drawing
    =
    const root: TgpuRoot
    root
    .
    WithBinding.createRenderPipeline<{}, {}, {
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    }, d.Vec4f>(descriptor: TgpuRenderPipeline<in Targets = never>.DescriptorBase & {
    attribs?: {} | undefined;
    vertex: TgpuVertexFn<{}, {
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    }> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>);
    fragment: TgpuFragmentFn<{
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    } & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<...>) => d.v4f | (AnyAutoCustoms & Partial<...>));
    targets?: TgpuColorTargetState;
    }): TgpuRenderPipeline<...> (+2 overloads)
    createRenderPipeline
    ({
    vertex: TgpuVertexFn<{}, {
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    }> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>)
    vertex
    :
    import common
    common
    .
    const fullScreenTriangle: TgpuVertexFn<{}, {
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    }>
    export fullScreenTriangle

    A vertex function that defines a single full-screen triangle out of three points.

    @example

    import { common } from 'typegpu';
    const pipeline = root.createRenderPipeline({
    vertex: common.fullScreenTriangle,
    fragment: yourFragmentShader,
    });
    pipeline.draw(3);

    fullScreenTriangle
    ,
    fragment: TgpuFragmentFn<{
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    } & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<InferGPURecord<{
    uv: import("node_modules/typegpu/data/wgslTypes").Vec2f;
    }>>) => d.v4f | (AnyAutoCustoms & Partial<InferGPURecord<{
    readonly $fragDepth: import("node_modules/typegpu/builtin").BuiltinFragDepth;
    readonly $sampleMask: import("node_modules/typegpu/builtin").BuiltinSampleMask;
    }>>))
    fragment
    :
    const rings: TgpuFragmentFn<{
    uv: d.Vec2f;
    }, d.Vec4f>
    rings
    ,
    targets?: TgpuColorTargetState
    targets
    : {
    format?: GPUTextureFormat | undefined

    The

    GPUTextureFormat

    of this color target. The pipeline will only be compatible with

    GPURenderPassEncoder

    s which use a

    GPUTextureView

    of this format in the corresponding color attachment.

    @default ― navigator.gpu.getPreferredCanvasFormat()

    format
    : 'rgba16float' },
    });

    The fourth rule is that modules connect through TypeGPU’s own accessors, slots and pipe, never through a registry. The kit’s modules connect this way everywhere:

    • Every renderer reads the camera through one accessor, cameras.current. A scene picks its camera with .pipe(view.inject()).
    • Any kernel can start particles in sparks with sparks.emit, which carries its own fill.

    An accessor that each pipeline fills, such as cameras.current, is a . A placeholder that needs a fill, like this one, defaults to unfilled, which throws an error naming the inject() to pipe. Connecting modules covers and placeholders, callbacks and resources that are replaced.

    Call createRipple(root) twice and you have two ripples. Nothing else tells them apart. Each ripple’s heightAt reads its own phase, so one shader can read both .

    The fifth rule is that identity is JS identity. The kit keeps no registry and no string keys. Resources live inside instances. Module scope holds only schemas, and pure functions. A name, such as the 'Enemy' in table.define('Enemy', …), only labels types and WGSL.

    A pipeline is compiled from its code, and a value captured into the code is part of it. Ten ripples with their centres captured into the shader would compile ten pipelines. With the centres in a buffer, one pipeline draws all ten. An eleventh ripple needs one more row and no new pipeline:

    // One pipeline per ripple: each centre is part of a shader's code
    const
    const ringsAround: ((uv: d.v2f) => number)[]
    ringsAround
    =
    const centres: d.v2f[]
    centres
    .
    Array<v2f>.map<(uv: d.v2f) => number>(callbackfn: (value: d.v2f, index: number, array: d.v2f[]) => (uv: d.v2f) => number, thisArg?: any): ((uv: d.v2f) => number)[]

    Calls a defined callback function on each element of an array, and returns an array that contains the results.

    @param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

    @param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

    map
    ((
    centre: d.v2f
    centre
    ) => (
    uv: d.v2f
    uv
    :
    import d
    d
    .
    export v2f

    Interface representing its WGSL vector type counterpart: vec2f or vec2. A vector with 2 elements of type f32

    v2f
    ) => {
    'use gpu';
    return
    import std
    std
    .
    function sin(value: number): number (+1 overload)
    export sin
    sin
    (
    import std
    std
    .
    length<d.v2f>(value: d.v2f): number (+1 overload)
    export length
    length
    (
    uv: d.v2f
    uv
    -
    centre: d.v2f
    centre
    ) * 40);
    });
    // One pipeline for every ripple: the centres are data
    const
    const centreOf: TgpuReadonly<d.WgslArray<d.Vec2f>>
    centreOf
    =
    const root: TgpuRoot
    root
    .
    TgpuRoot.createReadonly<d.WgslArray<d.Vec2f>>(typeSchema: d.WgslArray<d.Vec2f>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.Vec2f>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.Vec2f>>> | undefined): TgpuReadonly<d.WgslArray<d.Vec2f>> (+1 overload)

    Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for large data. For a general-purpose buffer, use

    TgpuRoot.createBuffer

    .

    @param ― typeSchema The type of data that this buffer will hold.

    @param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

    createReadonly
    (
    import d
    d
    .
    arrayOf<d.Vec2f>(elementType: d.Vec2f, elementCount: number): d.WgslArray<d.Vec2f> (+2 overloads)
    export arrayOf

    @location ― . Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).

    arrayOf
    (
    import d
    d
    .
    const vec2f: d.Vec2f
    vec2f
    , 16),
    const centres: d.v2f[]
    centres
    );
    const
    const ringsOf: (i: number, uv: d.v2f) => number
    ringsOf
    = (
    i: number
    i
    : number,
    uv: d.v2f
    uv
    :
    import d
    d
    .
    export v2f

    Interface representing its WGSL vector type counterpart: vec2f or vec2. A vector with 2 elements of type f32

    v2f
    ) => {
    'use gpu';
    return
    import std
    std
    .
    function sin(value: number): number (+1 overload)
    export sin
    sin
    (
    import std
    std
    .
    length<d.v2f>(value: d.v2f): number (+1 overload)
    export length
    length
    (
    uv: d.v2f
    uv
    -
    const centreOf: TgpuReadonly<d.WgslArray<d.Vec2f>>
    centreOf
    .
    TgpuReadonly<WgslArray<Vec2f>>.$: d.v2f[]
    $
    [
    i: number
    i
    ]) * 40);
    };

    The sixth rule is that many of a thing are rows in a buffer, and state that evolves stays on the GPU. The kit gives those buffers structure:

    • A table is a buffer of rows with named fields. The CPU writes some fields, kernels write the others, and the uploads only what changed.
    • Instances draw every mesh’s objects from a table’s rows, and particles live in a pool of rows.

    Data on the GPU covers rows, , settings and reading results back.

    A real scene draws more than colour. TAA needs to know where each pixel was last frame, picking needs an id at every pixel, and the depth decides what is in front. Every renderer would have to write all of these.

    Instead, passes.create describes once what each target holds. A renderer hands over a drawing: what each corner carries to its pixels, what a pixel looks like, and how to draw. Here is the ripple as :

    import {
    import passes
    passes
    } from '@typegpu/kit';
    const
    const Seen: d.WgslStruct<{
    color: d.Vec4f;
    }>
    Seen
    =
    import d
    d
    .
    struct<{
    color: d.Vec4f;
    }>(props: {
    color: d.Vec4f;
    }): d.WgslStruct<{
    color: d.Vec4f;
    }>
    export struct

    Creates a struct schema that can be used to construct GPU buffers. Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema). The order of members matches the passed in properties object.

    @example const CircleStruct = d.struct({ radius: d.f32, pos: d.vec3f });

    @param ― props Record with string keys and TgpuData values, each entry describing one struct member.

    struct
    ({
    color: d.Vec4f
    color
    :
    import d
    d
    .
    const vec4f: d.Vec4f
    vec4f
    }); // what a pixel looks like
    const
    const scene: passes.Description<{
    readonly hdr: typeof passes.color;
    }>
    scene
    =
    import passes
    passes
    .
    function create<Specs<{
    readonly hdr: {
    readonly format: "rgba16float";
    readonly sampled: true;
    };
    }>, {
    readonly hdr: typeof passes.color;
    }>(root: TgpuRoot, screen: targets.Targets<Specs<{
    readonly hdr: {
    readonly format: "rgba16float";
    readonly sampled: true;
    };
    }>>, writes: {
    readonly hdr: typeof passes.color;
    }, options?: passes.TargetOptions<Specs<{
    readonly hdr: {
    readonly format: "rgba16float";
    readonly sampled: true;
    };
    }>> | undefined): passes.Description<{
    readonly hdr: typeof passes.color;
    }> (+1 overload)

    Describes the targets and outputs for scene passes. With a surface such as the canvas, writes only each renderer's colour. With a target set, writes colour into the target marked color, depth into the target marked depth, and other outputs into their named targets. Multisampled targets resolve according to resolve. Targets with layers draw one pass per layer, and every target the description draws into needs the same layers. add builds a renderer's drawing. begin starts a pass. pipe supplies fills such as a camera.

    @param ― screen the surface, or the targets, which give the formats; each one the description names is drawn into

    @param ― writes what fills each target, by its key in screen

    @returns ― a description you destroy, which holds the pipelines it builds

    create
    (
    const root: TgpuRoot
    root
    ,
    const screen: targets.Targets<Specs<{
    readonly hdr: {
    readonly format: "rgba16float";
    readonly sampled: true;
    };
    }>>
    screen
    , {
    hdr: typeof passes.color
    hdr
    :
    import passes
    passes
    .
    const color: typeof passes.color

    Marks the target that receives each renderer's colour.

    color
    });
    const
    const water: passes.Drawn
    water
    =
    const scene: passes.Description<{
    readonly hdr: typeof passes.color;
    }>
    scene
    .
    Into<{ readonly hdr: typeof color; }>.add<d.WgslStruct<{
    position: d.Vec4f;
    uv: d.Vec2f;
    }>, {
    color: d.v4f;
    }>(drawing: passes.Drawing<d.WgslStruct<{
    position: d.Vec4f;
    uv: d.Vec2f;
    }>, {
    color: d.v4f;
    }>): passes.Drawn (+1 overload)

    Builds a pipeline for drawing that writes every described output and returns its draw methods. If the drawing cannot supply the fields an output reads, type checking fails with that target's name and those fields. Use without to leave it out or instead to replace it.

    add
    ({
    ...
    import passes
    passes
    .
    const fullScreen: {
    Vertex: d.WgslStruct<{
    position: d.Vec4f;
    uv: d.Vec2f;
    }>;
    at: (vertexIndex: number, _instanceIndex: number) => {
    position: d.v4f;
    uv: d.v2f;
    };
    }

    Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0. Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.

    fullScreen
    , // one triangle over the screen, carrying uv
    Shaders<WgslStruct<{ position: Vec4f; uv: Vec2f; }>, { color: v4f; }>.pixelOf?: ((vertex: {
    position: d.v4f;
    uv: d.v2f;
    }) => {
    color: d.v4f;
    }) | undefined

    Computes data at a pixel from the interpolated vertex. position is the pixel position. Required for descriptions that write colour or outputs, and for depthOf and sampleMask.

    pixelOf
    : (
    corner: {
    position: d.v4f;
    uv: d.v2f;
    }
    corner
    :
    import d
    d
    .
    type Infer<T> = T extends {
    readonly [$repr]: infer TRepr;
    } ? TRepr : T
    export Infer

    Extracts the inferred representation of a resource. For inferring types as seen by the GPU, see

    InferGPU

    @example type A = Infer // => number type B = Infer<WgslArray> // => number[] type C = Infer<Atomic> // => number

    Infer
    <typeof
    import passes
    passes
    .
    const fullScreen: {
    Vertex: d.WgslStruct<{
    position: d.Vec4f;
    uv: d.Vec2f;
    }>;
    at: (vertexIndex: number, _instanceIndex: number) => {
    position: d.v4f;
    uv: d.v2f;
    };
    }

    Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0. Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.

    fullScreen
    .
    type Vertex: d.WgslStruct<{
    position: d.Vec4f;
    uv: d.Vec2f;
    }>
    Vertex
    >) => {
    'use gpu';
    return
    const Seen: d.WgslStruct
    (props?: {
    color: d.v4f;
    } | undefined) => {
    color: d.v4f;
    }
    Seen
    ({
    color: d.v4f
    color
    :
    import d
    d
    .
    const vec4f: d.Vec4f
    (x: number, y: number, z: number, w: number) => d.v4f (+9 overloads)
    vec4f
    (0.2, 0.6, 1, 1) *
    const ripple: {
    heightAt(uv: d.v2f): number;
    }
    ripple
    .
    function heightAt(uv: d.v2f): number
    heightAt
    (
    corner: {
    position: d.v4f;
    uv: d.v2f;
    }
    corner
    .
    uv: d.v2f
    uv
    ) });
    },
    Shaders<WgslStruct<{ position: Vec4f; uv: Vec2f; }>, { color: v4f; }>.color?: passes.Output<{
    color: d.v4f;
    }, {
    position: d.v4f;
    uv: d.v2f;
    }> | undefined

    Supplies the output for the target marked passes.color. Required when the description has one.

    color
    :
    import passes
    passes
    .
    const shaded: passes.Output<{
    readonly color: d.v4f;
    }, unknown>

    Writes the pixel's color unchanged as a renderer's color output.

    shaded
    , // writes the pixel's colour as it is
    Drawing<WgslStruct<{ position: Vec4f; uv: Vec2f; }>, { color: v4f; }>.draw(pass: TgpuRenderCommands): void

    Records a draw into the pass, on which the description has set the pipeline it built. That pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its layout, so give such a layout to one drawing.

    draw
    : (
    pass: TgpuRenderCommands
    pass
    ) =>
    pass: TgpuRenderCommands
    pass
    .
    TgpuRenderCommands.draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void
    draw
    (3),
    });
    import frames
    frames
    .
    function create(root: TgpuRoot, record: Recorder): frames.Frames

    Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

    @submits ― always once a frame after your recorder returns, and again at each frame.submit()

    @param ― record your frame, recorded into each frame's encoder

    @returns ― a loop you run with each frame's time and destroy

    create
    (
    const root: TgpuRoot
    root
    , (
    frame: frames.Frame
    frame
    ) =>
    const scene: passes.Description<{
    readonly hdr: typeof passes.color;
    }>
    scene
    .
    Description<{ readonly hdr: typeof color; }>.record(frame: frames.Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
    readonly hdr: typeof passes.color;
    }> | undefined): void

    Begins a pass, draws drawn or each drawing in a list in order, then ends the pass. Reuse the list to avoid allocating each frame. Call begin yourself when you need to choose drawings per frame. Records nothing while enabled is false.

    record
    (
    frame: frames.Frame
    frame
    , [
    const water: passes.Drawn
    water
    ]));

    scene.add builds the pipeline that writes every target the lists. Add a motion target to the description and the same drawing writes motion too.

    The seventh rule is that scenes are described once. Every renderer, the kit’s included, hands over a drawing, and the description compiles its pipelines. Scenes and passes covers , shadows and other views.

    The kit has no scene graph, ECS, physics, required asset format or engine loop. Parent-child transforms, game state and input stay in your code. A host, such as web.host or React Native’s useScene, runs a scene for you, and the scene still records its own frame.

    Modules return TypeGPU resources, and most fit in one source file. You can edit a module or write your own and record both into the same encoder. The kit can also share a device with three.js or vgpu. Beside other renderers shows how to pass buffers, textures and images between them.

    Modules covers the module contract in detail.

    recording methodA recording method records a module's work into the pass, the encoder or the frame you hand it, and never submits.Recording methods →
    readbackA readback copies a buffer during a frame and hands it to the CPU a frame or two later, without making the frame wait.Results back →
    rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
    slotA slot is a row's place in its buffers, which a new row can take once the first is removed.Row ids →
    bind groupA bind group is a set of buffers, textures and samplers that a pipeline reads, and a pipeline has room for four.Words →
    storage bufferA storage buffer is GPU memory that shaders read by index and kernels can write, which is where the kit keeps rows.Words →
    fillA fill is the resource a pipeline binds for an accessor its shaders read.Members and placeholders →
    placeholderA placeholder is an accessor with no resource of its own, which each pipeline fills through the inject() of the module it reads.Members and placeholders →
    memberA member is a function or accessor on what a factory returns that reads that instance's own resources, so a pipeline that uses it needs no fill.Members and placeholders →
    instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
    hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
    tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
    fixed stepA fixed step advances a simulation by one set length of time, and each frame runs a whole number of them, so the result is the same at any frame rate.A fixed step →
    drawingA drawing is what a renderer hands to a pass description: what each vertex carries to its pixels, what a pixel looks like and the draw call.Every renderer is a drawing →
    pass descriptionA pass description says once which textures a pass draws into and what each holds, and builds the pipeline for every drawing added to it.Scenes and passes →
    outputAn output is a value every drawing writes at each pixel beside its colour, such as motion or an id.Outputs every drawing writes →