Skip to content

Start4 of 5

Starter scenes

Four whole scenes to start from, a full-screen shader, a lit mesh with a shadow, a frame finished with bloom and particles stepped on the GPU.

Read firstGetting started, for the project these scenes run in

On this page

Each scene on this page is a whole src/scene.ts for the project from Getting started. Replace yours with one of them and the page draws it. You can also have the initializer start a project from one. It asks which, and its --scene option takes shader, lit, finished or simulation. The first three build on each other: a shader alone, then that light a mesh, then the same finished for the screen. The fourth moves particles on the GPU, the start of a simulation.

Try Pause to hold the rings. They ripple out from the middle as the time the shader reads advances.

The initializer writes this scene unless you ask for another. One fragment function colours every pixel, and a uniform gives it the time. It takes two types from the kit and the rest from TypeGPU:

src/scene.ts
import type {
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
,
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
} from '@typegpu/kit';
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
, type
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
} from 'typegpu';
export async function
function createScene(root: TgpuRoot, surface: Surface): Promise<{
frame(frame: Frame): void;
}>
createScene
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
surface: Surface
surface
:
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
) {
const
const time: TgpuUniform<d.F32>
time
=
root: TgpuRoot
root
.
TgpuRoot.createUniform<d.F32>(typeSchema: d.F32, initial?: number | ((buffer: TgpuBuffer<NoInfer<d.F32>>) => void) | undefined): TgpuUniform<d.F32> (+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 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 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
- 0.5) * 40 -
const time: TgpuUniform<d.F32>
time
.
TgpuUniform<F32>.$: number
$
* 3) * 0.5 + 0.5;
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 wave: number
wave
;
});
const
const drawing: TgpuRenderPipeline<d.Vec4f>
drawing
=
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
:
surface: Surface
surface
.
Surface.format: GPUTextureFormat

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

format
},
});
return {
function frame(frame: Frame): void
frame
(
frame: Frame
frame
:
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
) {
const time: TgpuUniform<d.F32>
time
.
TgpuBufferBindingBase<F32>.write(data: number, options?: BufferWriteOptions): void
write
(
frame: Frame
frame
.
Frame.time: number

Reports seconds since the first submitted frame.

time
);
const
const pass: TgpuRenderPass
pass
=
frame: 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<d.WgslTexture<WgslTextureProps>> | TgpuTextureRenderView | GPUCanvasContext

A

GPUTextureView

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

view
:
surface: Surface
surface
.
Surface.view(frame: Frame): GPUTextureView

Returns a view of the current texture, created once per texture. React Native requires the frame to present after submission.

view
(
frame: Frame
frame
) },
});
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
();
},
};
}

surface.view(frame) is the canvas’s texture for this frame. The pass goes into frame.encoder, which the submits after frame returns.

Try Drag to look round. The box casts its shadow on the slab, on the side away from the sun.

Two of one box stand under a sun that casts a shadow. The second is scaled into a slab. pipelines.compile compiles the lighting’s shadow pipelines and the scene’s before the first frame. destroy frees the modules the scene made:

src/scene.ts
import {
import cameras
cameras
,
import instances
instances
,
import lighting
lighting
,
import meshPool
meshPool
,
import passes
passes
,
import pipelines
pipelines
,
import targets
targets
,
type
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
,
type
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
,
} from '@typegpu/kit';
import {
import meshes
meshes
} from '@typegpu/kit/geometry';
import type {
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
} from 'typegpu';
export async function
function createScene(root: TgpuRoot, surface: Surface): Promise<{
view: cameras.OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>
createScene
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
surface: targets.Surface
surface
:
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
) {
const
const view: cameras.OrbitCamera
view
=
import cameras
cameras
.
function orbit(root: TgpuRoot, options: cameras.OrbitOptions): cameras.OrbitCamera

Creates a perspective camera that orbits a target and eases towards a goal set by input.

@returns ― a camera you update every frame

orbit
(
root: TgpuRoot
root
, {
OrbitOptions.size: targets.SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

size
:
surface: targets.Surface
surface
,
OrbitOptions.target: readonly [number, number, number]

Sets the initial point that the camera orbits and looks at. Change it through goal.target.

target
: [0, 0, 0],
OrbitOptions.distance: number

Sets the initial distance from the target to the eye, in world units. Change it through goal.distance.

distance
: 6,
OrbitOptions.yaw?: number | undefined

Sets the initial yaw in radians around +y. At 0, the camera is on +z looking towards -z. Default 0.

yaw
: 0.6,
OrbitOptions.pitch?: number | undefined

Sets the initial pitch in radians above the horizon. Default 0.6.

pitch
: 0.5,
});
const
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
=
import lighting
lighting
.
function create<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>(root: TgpuRoot, options?: ({
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>

Creates lighting with a sun, sky and fog. It can also read point lights from a table or a function and cast shadows. Pipe its injection into each pipeline that uses it. Throws if points names no source or more than one, a light function has neither count nor candidates, a table comes with count, or candidates.ranges is anything other than a positive integer.

@injects ― hook the shading hooks its options name: reflect, ambient, fog, sunShadow and attenuation

@injects ― definition the sun, sky and fog, the shadows and the point lights, which shading reads

@binds ― 1 uniform: shading.shade, the sun, sky and fog

@binds ― 2 storage, 1 uniform: shading.shade with a table of point lights

@binds ― 3 storage, 1 uniform: shading.shade with a table of lights whose positions are on the device, the table's two parts

@binds ― 1 uniform: shading.shade with points.light or points.spot, plus what the function binds

@binds ― 0 storage: shading.shade with points.candidates, plus what their functions bind, 2 storage for a neighbour grid's range and slot

@binds ― 1 uniform: shading.shade with a shadow, the sun's light space and cascades, beside the depth array and its comparison sampler

@binds ― 1 uniform: shading.shade with pointShadow, each shadow's light, layers and views, beside their depth array and the comparison sampler

@owns ― 1 to 3 buffers, a sampler, targets, a cameras.layered, passes: the sun, sky and fog; with a shadow, its light space, the views of its cascades, a comparison sampler, the depth array and the passes that draw it; with pointShadow, the same for the lights' faces

@records ― shadow.record and pointShadow.record with what was added to them, before the passes that shade

@param ― options.shadow the sun's shadow, with a depth pass per cascade

@param ― options.pointShadow shadows from pointShadow.define that cast gives to lights of points.table, with a depth pass per face

@param ― options.points point lights from a table or a 'use gpu' function. Every lit point visits each slot up to the table's highest live one, or count with a function, unless candidates names the slots that may reach it

@returns ― lighting you destroy

create
(
root: TgpuRoot
root
, {
shadow: {
readonly extent: 12;
} & lighting.FixedShadowOptions

Enables and configures the shadow from the sun. Default none.

shadow
: {
extent: 12

Sets the width of the square covered by the map in world units. The square is centred on the point passed to follow. Change it with setExtent. A shadow with an eye takes none. Default 20.

extent
: 12 },
settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
} & (Partial<InferInput<WgslStruct<{
sunDirection: Vec3f;
sunIntensity: F32;
sunColor: Vec3f;
skyIntensity: F32;
skyTop: Vec3f;
fogDensity: F32;
skyBottom: Vec3f;
fogFalloff: F32;
fogColor: Vec3f;
skyReflection: F32;
fogStart: F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
sunDirection: [-0.6, 0.7, 0.5]
sunDirection
: [-0.6, 0.7, 0.5] },
});
const
const pool: meshPool.MeshPool<{}>
pool
=
import meshPool
meshPool
.
function create<{}>(root: TgpuRoot, options: meshPool.Options<{}>): meshPool.MeshPool<{}>

Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and weights. Extras add the size of their struct per vertex.

@unstable

@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads

@injects ― member the extras pool.extra reads

@binds ― 1 storage: positionAt, the positions

@binds ― 2 storage: vertexAt, the positions and the normals and uvs

@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1

@binds ― 1 storage: influencesAt, the joints and weights

@binds ― 1 storage: boundsOf, every mesh's box

@binds ― 1 storage: pool.extra, every vertex's extras

@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage

@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode

@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a pipeline per pair of shape functions, textures, samplers, bind groups, what images makes: positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures

@returns ― a pool you add meshes and models to and destroy

create
(
root: TgpuRoot
root
, {
Options<E extends Extras = {}>.capacity: number

Limits the number of meshes to at most 256.

capacity
: 1 });
const
const box: meshPool.Mesh
box
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
import meshes
meshes
.
function box({ width, height, depth, widthSegments, heightSegments, depthSegments, }?: meshes.BoxOptions): meshes.IndexedGeometry
box
());
const
const things: instances.Instances<Plain>
things
=
import instances
instances
.
function create(root: TgpuRoot, pool: meshPool.MeshPool, options: instances.Options & {
readonly kind?: Plain;
}): instances.Instances<Plain> (+3 overloads)

Creates a set of mesh instances with transforms, materials and optional custom fields. Each instance uses a row, and renderers draw one list of live rows per mesh.

@param ― pool the mesh pool whose meshes it draws

@param ― options.kind a kind from instances.define

@returns ― a set of instances you flush every frame and destroy

create
(
root: TgpuRoot
root
,
const pool: meshPool.MeshPool<{}>
pool
, {
Options<K extends AnyKind = Plain>.capacity: number

Limits the number of rows. A mesh instance uses one row; a model instance uses one row per mesh.

capacity
: 2 });
const things: instances.Instances<Plain>
things
.
Instances<Plain>.add(mesh: meshPool.Mesh | Pick<meshPool.Model, "meshes">, values?: {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
} | ((mesh: meshPool.Mesh, index: number) => {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
}) | undefined): instances.Id<...>

Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row, and all rows move and change together under one id. values may be a function of each mesh, to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the group is empty, a posed kind receives a mesh without joints or the set is full. When values or a write throws, it adds no row and rethrows.

add
(
const box: meshPool.Mesh
box
, {
position?: InferInput<Vec3f> | ArrayLike<number> | undefined
position
: [0, 0.5, 0],
color?: InferInput<Vec3f> | ArrayLike<number> | undefined
color
: [0.95, 0.45, 0.2] });
const things: instances.Instances<Plain>
things
.
Instances<Plain>.add(mesh: meshPool.Mesh | Pick<meshPool.Model, "meshes">, values?: {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
} | ((mesh: meshPool.Mesh, index: number) => {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
}) | undefined): instances.Id<...>

Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row, and all rows move and change together under one id. values may be a function of each mesh, to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the group is empty, a posed kind receives a mesh without joints or the set is full. When values or a write throws, it adds no row and rethrows.

add
(
const box: meshPool.Mesh
box
, {
position?: InferInput<Vec3f> | ArrayLike<number> | undefined
position
: [0, -0.1, 0],
scale?: number | InferInput<Vec3f> | ArrayLike<number> | undefined

Sets one scale factor for all axes or a separate factor per axis.

scale
: [8, 0.2, 8],
color?: InferInput<Vec3f> | ArrayLike<number> | undefined
color
: [0.14, 0.15, 0.18] });
const
const renderer: instances.Renderer
renderer
=
const things: instances.Instances<Plain>
things
.
Instances<Plain>.renderer(options?: instances.RendererOptions): instances.Renderer

Creates a renderer for colour and shadow pass descriptions, lit by the lighting each description gives through beneath. Use pipe to fill resources read by kind callbacks, or another lighting.

renderer
();
const
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>
screen
=
import targets
targets
.
function create<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>(root: TgpuRoot, source: targets.SizeSource, specs: {
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}, options?: targets.Options): targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>

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
(
root: TgpuRoot
root
,
surface: targets.Surface
surface
, {
color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
}
color
: {
format: GPUTextureFormat
format
:
surface: targets.Surface
surface
.
Surface.format: GPUTextureFormat

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

format
,
samples: 4
samples
: 4 },
depth: {
readonly format: "depth24plus";
readonly samples: 4;
}
depth
: {
format: "depth24plus"
format
: 'depth24plus',
samples: 4
samples
: 4 },
});
const
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>, {
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>, writes: {
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<...> | undefined): passes.Description<...> (+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
(
root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>
screen
,
{
color: typeof passes.color
color
:
import passes
passes
.
const color: typeof passes.color

Marks the target that receives each renderer's colour.

color
,
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

depth
},
{
TargetOptions<Specs<{ readonly color: { readonly format: GPUTextureFormat; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; }>>.resolve?: {
readonly color?: targets.Surface | "depth" | undefined;
readonly depth?: targets.Surface | "color" | undefined;
} | undefined

Maps multisampled targets to their resolve destinations at the end of a pass. A destination can be another target in the set or a surface such as the canvas. Default none.

resolve
: {
color?: targets.Surface | "depth" | undefined
color
:
surface: targets.Surface
surface
} },
)
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.pipe(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>

Adds fill after existing fills and returns a description of the same passes. Piped fills take precedence over a drawing's own. For example, passes.create(…).pipe(view.inject()) uses the camera from view.

pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

Fills cameras.current for the pipelines created from the configuration it is piped into.

inject
())
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.beneath(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>

Adds fill after the fills given to earlier beneath calls and returns a description of the same passes. A drawing's own fills take precedence over these, and piped fills over both, so beneath supplies defaults such as a lighting. A compound drawing that passes its own from to pipeline gets them by starting from with inject().

beneath
(
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
());
const
const shown: passes.Drawn
shown
=
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Into<{ readonly color: typeof color; readonly depth: typeof depth; }>.add<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>(drawing: passes.Compound<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>): 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
(
const renderer: instances.Renderer
renderer
);
const
const cast: passes.Drawn
cast
=
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
ShadowPasses.add<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>(drawing: passes.Compound<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>): passes.Drawn (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
(
const renderer: instances.Renderer
renderer
);
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
([
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
,
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
]);
return {
view: cameras.OrbitCamera
view
,
function frame(frame: Frame): void
frame
(
frame: Frame
frame
:
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
) {
const view: cameras.OrbitCamera
view
.
OrbitCamera.update(dt: number): void

Eases towards the goal by dt seconds and writes the uniform if the view changed. Call once per frame.

update
(
frame: Frame
frame
.
Frame.dt: number

Reports seconds since the previous submitted frame. The first frame has a dt of zero.

dt
);
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>
screen
.
Targets<Specs<{ readonly color: { readonly format: GPUTextureFormat; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; }>>.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 things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: Frame | TgpuCommandEncoder): void

Uploads changed rows. When instances are added or removed, it also uploads live rows per mesh and updates draw counts. Call this once per frame before drawing. HistoryInstances take the frame or its encoder and throw without one.

flush
();
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: Frame | TgpuCommandEncoder, casters: passes.Drawn | readonly passes.Drawn[], options?: lighting.ShadowRecordOptions): void

Clears the map in a depth pass per cascade that redraw picks and draws the casters built by add. Call this while recording each frame, before drawing shaded surfaces. When disabled, it draws nothing and makes every point sunlit. A frame that draws no cascade writes a timer's timestamps from an empty compute pass.

record
(
frame: Frame
frame
,
const cast: passes.Drawn
cast
);
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.record(frame: Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}> | 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: Frame
frame
,
const shown: passes.Drawn
shown
);
},
function destroy(): void
destroy
() {
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
Lighting.destroy(): void

Destroys the shadows' maps and the casters added to them.

destroy
();
const things: instances.Instances<Plain>
things
.
function destroy(): void

Destroys the storage buffers.

destroy
();
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.destroy(): void

Destroys the buffers and textures.

destroy
();
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: GPUTextureFormat;
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
}>>
screen
.
Targets<Specs<{ readonly color: { readonly format: GPUTextureFormat; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; }>>.destroy(): void

Destroys the current textures.

destroy
();
},
};
}
  • cameras.orbit is the view. view.update eases it towards its goal each frame.
  • lighting.create holds the sun, and its shadow group gives it a shadow map.
  • meshPool stores the box’s vertices and instances the drawn from them. flush uploads the rows that changed.
  • targets allocates multisampled colour and depth at size. fit reallocates them when the canvas resizes.
  • passes describes the pass that draws into them and resolves into the surface. pipe(view.inject()) gives its drawings the camera, and beneath(light.inject()) the light.
  • scene.add(renderer) and light.shadow.add(renderer) build the ’s pipelines for the lit pass and for the shadow map. A frame records the shadow map first, then the pass that reads it.

The scene returns its view, so the page can connect orbit controls to it:

src/index.ts
import * as
import web
web
from '@typegpu/kit/web';
import {
function createScene(root: TgpuRoot, surface: Surface): Promise<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>
createScene
} from './scene.ts';
const
const canvas: HTMLCanvasElement
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')!;
import web
web
.
function host<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>(createScene: web.CreateScene<Record<never, never>, {
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>, hosting: web.HostOptions<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>): web.Hosted<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}> (+1 overload)

Runs a scene on a canvas with a root, surface, frame loop and animation. destroy tears them down in order. Use send to control the scene or onFrame to read it. If scene options are optional, call host(createScene, { canvas }). Throws if both device and root are supplied.

@param ― createScene the scene file's createScene

@param ― options the scene's third argument

@param ― hosting the canvas, the device or root, and what the page runs beside the scene

@returns ― a hosted scene you send closures to and destroy

host
(
function createScene(root: TgpuRoot, surface: Surface): Promise<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>
createScene
, {
HostOptions<S extends Scene>.canvas: HTMLCanvasElement

Supplies the canvas for the scene.

canvas
,
HostOptions<{ view: OrbitCamera; frame(frame: Frame): void; destroy(): void; }, Surface>.attach?: ((stage: Stage<{
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}, web.Surface>) => Detach | void) | undefined

Connects page code, such as orbit controls, to the stage after scene creation. The host frees what it returns with the scene. Default none.

@cpu

attach
: ({
scene: {
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}

Holds the scene the host created.

scene
}) =>
import web
web
.
function orbitControls(orbit: {
readonly goal: web.OrbitGoal;
}, element: HTMLElement, options?: web.OrbitControlsOptions): web.OrbitControls

Connects pointer input to an orbit camera's goal. Drag to orbit and use the wheel or pinch to zoom. With pan, drag the other button to move the target. update eases the camera towards the goal. Throws if pan is enabled but the goal has no target.

@param ― orbit an orbit camera, whose goal it writes

@param ― element what takes the drag, the wheel and the pinch

@returns ― the controls, which you destroy to remove the listeners

orbitControls
(
scene: {
view: OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}

Holds the scene the host created.

scene
.
view: OrbitCamera
view
,
const canvas: HTMLCanvasElement
canvas
),
});
Try Drag to look round. The box is brighter than the screen can show, so bloom spreads a glow past its edges.

The box now emits light brighter than the screen’s white. Three changes to the lit scene keep that light and turn it into glow:

src/scene.ts
import {
import bloom
bloom
,
import cameras
cameras
,
import finish
finish
,
import instances
instances
,
import lighting
lighting
,
import meshPool
meshPool
,
import passes
passes
,
import pipelines
pipelines
,
import targets
targets
,
type
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
,
type
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
,
} from '@typegpu/kit';
import {
import meshes
meshes
} from '@typegpu/kit/geometry';
import type {
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
} from 'typegpu';
export async function
function createScene(root: TgpuRoot, surface: Surface): Promise<{
view: cameras.OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>
createScene
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
surface: targets.Surface
surface
:
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
) {
const
const view: cameras.OrbitCamera
view
=
import cameras
cameras
.
function orbit(root: TgpuRoot, options: cameras.OrbitOptions): cameras.OrbitCamera

Creates a perspective camera that orbits a target and eases towards a goal set by input.

@returns ― a camera you update every frame

orbit
(
root: TgpuRoot
root
, {
OrbitOptions.size: targets.SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

size
:
surface: targets.Surface
surface
,
OrbitOptions.target: readonly [number, number, number]

Sets the initial point that the camera orbits and looks at. Change it through goal.target.

target
: [0, 0, 0],
OrbitOptions.distance: number

Sets the initial distance from the target to the eye, in world units. Change it through goal.distance.

distance
: 6,
OrbitOptions.yaw?: number | undefined

Sets the initial yaw in radians around +y. At 0, the camera is on +z looking towards -z. Default 0.

yaw
: 0.6,
OrbitOptions.pitch?: number | undefined

Sets the initial pitch in radians above the horizon. Default 0.6.

pitch
: 0.5,
});
const
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
=
import lighting
lighting
.
function create<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>(root: TgpuRoot, options?: ({
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>

Creates lighting with a sun, sky and fog. It can also read point lights from a table or a function and cast shadows. Pipe its injection into each pipeline that uses it. Throws if points names no source or more than one, a light function has neither count nor candidates, a table comes with count, or candidates.ranges is anything other than a positive integer.

@injects ― hook the shading hooks its options name: reflect, ambient, fog, sunShadow and attenuation

@injects ― definition the sun, sky and fog, the shadows and the point lights, which shading reads

@binds ― 1 uniform: shading.shade, the sun, sky and fog

@binds ― 2 storage, 1 uniform: shading.shade with a table of point lights

@binds ― 3 storage, 1 uniform: shading.shade with a table of lights whose positions are on the device, the table's two parts

@binds ― 1 uniform: shading.shade with points.light or points.spot, plus what the function binds

@binds ― 0 storage: shading.shade with points.candidates, plus what their functions bind, 2 storage for a neighbour grid's range and slot

@binds ― 1 uniform: shading.shade with a shadow, the sun's light space and cascades, beside the depth array and its comparison sampler

@binds ― 1 uniform: shading.shade with pointShadow, each shadow's light, layers and views, beside their depth array and the comparison sampler

@owns ― 1 to 3 buffers, a sampler, targets, a cameras.layered, passes: the sun, sky and fog; with a shadow, its light space, the views of its cascades, a comparison sampler, the depth array and the passes that draw it; with pointShadow, the same for the lights' faces

@records ― shadow.record and pointShadow.record with what was added to them, before the passes that shade

@param ― options.shadow the sun's shadow, with a depth pass per cascade

@param ― options.pointShadow shadows from pointShadow.define that cast gives to lights of points.table, with a depth pass per face

@param ― options.points point lights from a table or a 'use gpu' function. Every lit point visits each slot up to the table's highest live one, or count with a function, unless candidates names the slots that may reach it

@returns ― lighting you destroy

create
(
root: TgpuRoot
root
, {
shadow: {
readonly extent: 12;
} & lighting.FixedShadowOptions

Enables and configures the shadow from the sun. Default none.

shadow
: {
extent: 12

Sets the width of the square covered by the map in world units. The square is centred on the point passed to follow. Change it with setExtent. A shadow with an eye takes none. Default 20.

extent
: 12 },
settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
} & (Partial<InferInput<WgslStruct<{
sunDirection: Vec3f;
sunIntensity: F32;
sunColor: Vec3f;
skyIntensity: F32;
skyTop: Vec3f;
fogDensity: F32;
skyBottom: Vec3f;
fogFalloff: F32;
fogColor: Vec3f;
skyReflection: F32;
fogStart: F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
sunDirection: [-0.6, 0.7, 0.5]
sunDirection
: [-0.6, 0.7, 0.5] },
});
const
const pool: meshPool.MeshPool<{}>
pool
=
import meshPool
meshPool
.
function create<{}>(root: TgpuRoot, options: meshPool.Options<{}>): meshPool.MeshPool<{}>

Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and weights. Extras add the size of their struct per vertex.

@unstable

@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and weights influencesAt reads, and the boxes boundsOf reads

@injects ― member the extras pool.extra reads

@binds ― 1 storage: positionAt, the positions

@binds ― 2 storage: vertexAt, the positions and the normals and uvs

@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1

@binds ― 1 storage: influencesAt, the joints and weights

@binds ― 1 storage: boundsOf, every mesh's box

@binds ― 1 storage: pool.extra, every vertex's extras

@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in the fragment stage

@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at once, and a model's images generate their mips as they decode

@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a pipeline per pair of shape functions, textures, samplers, bind groups, what images makes: positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt it bakes, and per shape added the uniform of its ranges and their group; each image decoded once per format it is read in, and a group per set of a mesh's textures

@returns ― a pool you add meshes and models to and destroy

create
(
root: TgpuRoot
root
, {
Options<E extends Extras = {}>.capacity: number

Limits the number of meshes to at most 256.

capacity
: 1 });
const
const box: meshPool.Mesh
box
=
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.add(shape: meshPool.Shape, target?: Frame | TgpuCommandEncoder): meshPool.Mesh (+1 overload)

Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it records there; otherwise, it submits at once. The bake's pipeline inlines the shape's vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those functions, unless initAsync compiled it for the shapes option. Throws when the pool is full.

add
(
import meshes
meshes
.
function box({ width, height, depth, widthSegments, heightSegments, depthSegments, }?: meshes.BoxOptions): meshes.IndexedGeometry
box
());
const
const things: instances.Instances<Plain>
things
=
import instances
instances
.
function create(root: TgpuRoot, pool: meshPool.MeshPool, options: instances.Options & {
readonly kind?: Plain;
}): instances.Instances<Plain> (+3 overloads)

Creates a set of mesh instances with transforms, materials and optional custom fields. Each instance uses a row, and renderers draw one list of live rows per mesh.

@param ― pool the mesh pool whose meshes it draws

@param ― options.kind a kind from instances.define

@returns ― a set of instances you flush every frame and destroy

create
(
root: TgpuRoot
root
,
const pool: meshPool.MeshPool<{}>
pool
, {
Options<K extends AnyKind = Plain>.capacity: number

Limits the number of rows. A mesh instance uses one row; a model instance uses one row per mesh.

capacity
: 2 });
const things: instances.Instances<Plain>
things
.
Instances<Plain>.add(mesh: meshPool.Mesh | Pick<meshPool.Model, "meshes">, values?: {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
} | ((mesh: meshPool.Mesh, index: number) => {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
}) | undefined): instances.Id<...>

Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row, and all rows move and change together under one id. values may be a function of each mesh, to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the group is empty, a posed kind receives a mesh without joints or the set is full. When values or a write throws, it adds no row and rethrows.

add
(
const box: meshPool.Mesh
box
, {
position?: InferInput<Vec3f> | ArrayLike<number> | undefined
position
: [0, 0.5, 0],
emission?: InferInput<Vec3f> | ArrayLike<number> | undefined
emission
: [2, 0.4, 0.1] });
const things: instances.Instances<Plain>
things
.
Instances<Plain>.add(mesh: meshPool.Mesh | Pick<meshPool.Model, "meshes">, values?: {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
} | ((mesh: meshPool.Mesh, index: number) => {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
}) | undefined): instances.Id<...>

Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row, and all rows move and change together under one id. values may be a function of each mesh, to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the group is empty, a posed kind receives a mesh without joints or the set is full. When values or a write throws, it adds no row and rethrows.

add
(
const box: meshPool.Mesh
box
, {
position?: InferInput<Vec3f> | ArrayLike<number> | undefined
position
: [0, -0.1, 0],
scale?: number | InferInput<Vec3f> | ArrayLike<number> | undefined

Sets one scale factor for all axes or a separate factor per axis.

scale
: [8, 0.2, 8],
color?: InferInput<Vec3f> | ArrayLike<number> | undefined
color
: [0.14, 0.15, 0.18] });
const
const renderer: instances.Renderer
renderer
=
const things: instances.Instances<Plain>
things
.
Instances<Plain>.renderer(options?: instances.RendererOptions): instances.Renderer

Creates a renderer for colour and shadow pass descriptions, lit by the lighting each description gives through beneath. Use pipe to fill resources read by kind callbacks, or another lighting.

renderer
();
const
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
=
import targets
targets
.
function create<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>(root: TgpuRoot, source: targets.SizeSource, specs: {
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}, options?: targets.Options): targets.Targets<...>

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
(
root: TgpuRoot
root
,
surface: targets.Surface
surface
, {
color: {
readonly format: "rgba16float";
readonly samples: 4;
}
color
: {
format: "rgba16float"
format
: 'rgba16float',
samples: 4
samples
: 4 },
depth: {
readonly format: "depth24plus";
readonly samples: 4;
}
depth
: {
format: "depth24plus"
format
: 'depth24plus',
samples: 4
samples
: 4 },
hdr: {
readonly format: "rgba16float";
readonly sampled: true;
}
hdr
: {
format: "rgba16float"
format
: 'rgba16float',
sampled: true
sampled
: true },
});
const
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>, {
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>, writes: {
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<...> | undefined): passes.Description<...> (+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
(
root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
,
{
color: typeof passes.color
color
:
import passes
passes
.
const color: typeof passes.color

Marks the target that receives each renderer's colour.

color
,
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

depth
},
{
TargetOptions<Specs<{ readonly color: { readonly format: "rgba16float"; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.resolve?: {
readonly color?: targets.Surface | "depth" | "hdr" | undefined;
readonly depth?: targets.Surface | "color" | "hdr" | undefined;
readonly hdr?: targets.Surface | "color" | "depth" | undefined;
} | undefined

Maps multisampled targets to their resolve destinations at the end of a pass. A destination can be another target in the set or a surface such as the canvas. Default none.

resolve
: {
color?: targets.Surface | "depth" | "hdr" | undefined
color
: 'hdr' } },
)
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.pipe(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>

Adds fill after existing fills and returns a description of the same passes. Piped fills take precedence over a drawing's own. For example, passes.create(…).pipe(view.inject()) uses the camera from view.

pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

Fills cameras.current for the pipelines created from the configuration it is piped into.

inject
())
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.beneath(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>

Adds fill after the fills given to earlier beneath calls and returns a description of the same passes. A drawing's own fills take precedence over these, and piped fills over both, so beneath supplies defaults such as a lighting. A compound drawing that passes its own from to pipeline gets them by starting from with inject().

beneath
(
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
());
const
const shown: passes.Drawn
shown
=
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Into<{ readonly color: typeof color; readonly depth: typeof depth; }>.add<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>(drawing: passes.Compound<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>): 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
(
const renderer: instances.Renderer
renderer
);
const
const cast: passes.Drawn
cast
=
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
ShadowPasses.add<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>(drawing: passes.Compound<{
color: v4f;
}, {
position: v4f;
world: v3f;
normal: v3f;
uv: v2f;
uv1: v2f;
row: number;
}>): passes.Drawn (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
(
const renderer: instances.Renderer
renderer
);
const
const source: () => targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
source
= () =>
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly color: { readonly format: "rgba16float"; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.textures: {
readonly color: targets.Target<{
readonly format: "rgba16float";
readonly samples: 4;
}>;
readonly depth: targets.Target<{
readonly format: "depth24plus";
readonly samples: 4;
}>;
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
(
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
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
(
root: TgpuRoot
root
, {
Options.format: GPUTextureFormat

Sets the output format, such as the canvas format.

format
:
surface: targets.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
,
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
});
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
([
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
,
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
,
const glow: bloom.Bloom
glow
,
const final: finish.Finish
final
]);
return {
view: cameras.OrbitCamera
view
,
function frame(frame: Frame): void
frame
(
frame: Frame
frame
:
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
) {
const view: cameras.OrbitCamera
view
.
OrbitCamera.update(dt: number): void

Eases towards the goal by dt seconds and writes the uniform if the view changed. Call once per frame.

update
(
frame: Frame
frame
.
Frame.dt: number

Reports seconds since the previous submitted frame. The first frame has a dt of zero.

dt
);
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly color: { readonly format: "rgba16float"; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; 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 things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: Frame | TgpuCommandEncoder): void

Uploads changed rows. When instances are added or removed, it also uploads live rows per mesh and updates draw counts. Call this once per frame before drawing. HistoryInstances take the frame or its encoder and throw without one.

flush
();
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: Frame | TgpuCommandEncoder, casters: passes.Drawn | readonly passes.Drawn[], options?: lighting.ShadowRecordOptions): void

Clears the map in a depth pass per cascade that redraw picks and draws the casters built by add. Call this while recording each frame, before drawing shaded surfaces. When disabled, it draws nothing and makes every point sunlit. A frame that draws no cascade writes a timer's timestamps from an empty compute pass.

record
(
frame: Frame
frame
,
const cast: passes.Drawn
cast
);
const scene: passes.Description<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Description<{ readonly color: typeof color; readonly depth: typeof depth; }>.record(frame: Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly color: typeof passes.color;
readonly depth: typeof passes.depth;
}> | 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: Frame
frame
,
const shown: passes.Drawn
shown
);
const glow: bloom.Bloom
glow
.
Bloom.record(target: Frame | TgpuCommandEncoder, options?: Timed): void

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

record
(
frame: Frame
frame
);
const final: finish.Finish
final
.
Finish.record(target: 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: Frame
frame
,
surface: targets.Surface
surface
.
Surface.view(frame: Frame): GPUTextureView

Returns a view of the current texture, created once per texture. React Native requires the frame to present after submission.

view
(
frame: Frame
frame
));
},
function destroy(): void
destroy
() {
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 12;
};
readonly settings: {
readonly sunDirection: [-0.6, 0.7, 0.5];
};
}>
light
.
Lighting.destroy(): void

Destroys the shadows' maps and the casters added to them.

destroy
();
const things: instances.Instances<Plain>
things
.
function destroy(): void

Destroys the storage buffers.

destroy
();
const pool: meshPool.MeshPool<{}>
pool
.
MeshPool<{}>.destroy(): void

Destroys the buffers and textures.

destroy
();
const screen: targets.Targets<Specs<{
readonly color: {
readonly format: "rgba16float";
readonly samples: 4;
};
readonly depth: {
readonly format: "depth24plus";
readonly samples: 4;
};
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly color: { readonly format: "rgba16float"; readonly samples: 4; }; readonly depth: { readonly format: "depth24plus"; readonly samples: 4; }; readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.destroy(): void

Destroys the current textures.

destroy
();
const glow: bloom.Bloom
glow
.
Bloom.destroy(): void

Destroys the glow texture.

destroy
();
},
};
}
  • The gain hdr, a float texture the pass resolves into, so colours above 1 survive the pass.
  • bloom reads hdr and blurs what is bright.
  • finish records last. It adds the glow, maps the image to the screen through a and writes the surface.
Try Drag to look round. Every mote is a row the GPU steps. Motes turn from blue to ice as they speed up near the eye, then start again at the rim.

12 000 motes circle an eye, fall towards it and start again near the rim. They stay on the GPU between frames, and swirl, a 'use gpu' function you write, moves each one a step at a time. Slow motes draw blue and fast ones ice, and their light adds up where they crowd:

src/scene.ts
import {
import cameras
cameras
,
import clock
clock
,
type Particle = {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
const Particle: d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>

This type describes a particle in shaders.

Particle
,
import particles
particles
,
import passes
passes
,
import pipelines
pipelines
,
type
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
,
type
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
,
} from '@typegpu/kit';
import {
(alias) namespace perlin3d
import perlin3d
perlin3d
,
const randf: {
seed: TgpuFn<(seed: d.F32) => d.Void>;
seed2: TgpuFn<(seed: d.Vec2f) => d.Void>;
seed3: TgpuFn<(seed: d.Vec3f) => d.Void>;
seed4: TgpuFn<(seed: d.Vec4f) => d.Void>;
sample: TgpuFn<() => d.F32>;
sampleExclusive: TgpuFn<() => d.F32>;
normal: TgpuFn<(mu: d.F32, sigma: d.F32) => d.F32>;
... 10 more ...;
onUnitSphere: TgpuFn<...>;
}
randf
} from '@typegpu/noise';
import {
import d
d
,
import std
std
, type
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
} from 'typegpu';
/** How many motes circle the eye, and how far from it they start again. */
const
const MOTES: 12000

How many motes circle the eye, and how far from it they start again.

MOTES
= 12_000;
const
const RIM: 3.2
RIM
= 3.2;
/** The kit's blue for slow motes and its ice for fast ones. */
const
const SLOW: d.v3f

The kit's blue for slow motes and its ice for fast ones.

SLOW
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.3, 0.47, 1);
const
const FAST: d.v3f
FAST
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.85, 0.94, 1);
/**
* One step of a mote: it circles the eye, faster closer in, falls slowly towards it, drifts on
* noise that changes with its age and is pulled back to the disc. In the eye it starts again near
* the rim, as every mote does on its first step.
*/
const
const swirl: (mote: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

One step of a mote: it circles the eye, faster closer in, falls slowly towards it, drifts on noise that changes with its age and is pulled back to the disc. In the eye it starts again near the rim, as every mote does on its first step.

swirl
= (
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
:
type Particle = {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

This type describes a particle in shaders.

Particle
) => {
'use gpu';
const
const p: d.v3f
p
=
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
position: d.v3f
position
;
const
const radius: number
radius
=
import std
std
.
function max(fst: number, ...rest: number[]): number (+1 overload)
export max
max
(
import std
std
.
length<d.v2f>(value: d.v2f): number (+1 overload)
export length
length
(
const p: d.v3f
p
.
xz: d.v2f
xz
), 0.05);
const
const around: d.v3f
around
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(-
const p: d.v3f
p
.
v3f.z: number
z
, 0,
const p: d.v3f
p
.
v3f.x: number
x
) /
const radius: number
radius
;
const
const inward: d.v3f
inward
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(-
const p: d.v3f
p
.
v3f.x: number
x
, 0, -
const p: d.v3f
p
.
v3f.z: number
z
) /
const radius: number
radius
;
const
const spiral: d.v3f
spiral
= (
const around: d.v3f
around
+
const inward: d.v3f
inward
* 0.3) * (1.6 /
import std
std
.
function sqrt(value: number): number (+1 overload)
export sqrt
sqrt
(
const radius: number
radius
));
const
const at: d.v3f
at
=
const p: d.v3f
p
* 0.5 +
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0,
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
age: number

Holds particle age in seconds.

age
* 0.15, 0);
const
const drift: d.v3f
drift
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(
(alias) namespace perlin3d
import perlin3d
perlin3d
.
index.sample(pos: d.v3f): number
export index.sample
sample
(
const at: d.v3f
at
),
(alias) namespace perlin3d
import perlin3d
perlin3d
.
index.sample(pos: d.v3f): number
export index.sample
sample
(
const at: d.v3f
at
+ 31),
(alias) namespace perlin3d
import perlin3d
perlin3d
.
index.sample(pos: d.v3f): number
export index.sample
sample
(
const at: d.v3f
at
+ 57));
const
const next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
=
function Particle(props?: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
} | undefined): {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

This type describes a particle in shaders.

Particle
(
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
);
const next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
.
velocity: d.v3f
velocity
=
const spiral: d.v3f
spiral
+
const drift: d.v3f
drift
-
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0,
const p: d.v3f
p
.
v3f.y: number
y
, 0);
if (
const radius: number
radius
< 0.2 +
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
seed: number

Holds a random value in [0, 1), fixed at birth, for variation in update and shade.

seed
* 0.4) {
const randf: {
seed: TgpuFn<(seed: d.F32) => d.Void>;
seed2: TgpuFn<(seed: d.Vec2f) => d.Void>;
seed3: TgpuFn<(seed: d.Vec3f) => d.Void>;
seed4: TgpuFn<(seed: d.Vec4f) => d.Void>;
sample: TgpuFn<() => d.F32>;
sampleExclusive: TgpuFn<() => d.F32>;
normal: TgpuFn<(mu: d.F32, sigma: d.F32) => d.F32>;
... 10 more ...;
onUnitSphere: TgpuFn<...>;
}
randf
.
seed2: (seed: d.v2f) => void

Threads do not share the generator's State. As a result, unless you change the seed in each thread, each thread will produce the same sequence. randf.randSeed2 sets the private seed of the thread.

@param ― seed seed value to set. For the best results, all elements should be in [-1000, 1000] range.

seed2
(
import d
d
.
const vec2f: d.Vec2f
(x: number, y: number) => d.v2f (+3 overloads)
vec2f
(
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
seed: number

Holds a random value in [0, 1), fixed at birth, for variation in update and shade.

seed
,
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
age: number

Holds particle age in seconds.

age
));
const
const rim: d.v2f
rim
=
const randf: {
seed: TgpuFn<(seed: d.F32) => d.Void>;
seed2: TgpuFn<(seed: d.Vec2f) => d.Void>;
seed3: TgpuFn<(seed: d.Vec3f) => d.Void>;
seed4: TgpuFn<(seed: d.Vec4f) => d.Void>;
sample: TgpuFn<() => d.F32>;
sampleExclusive: TgpuFn<() => d.F32>;
normal: TgpuFn<(mu: d.F32, sigma: d.F32) => d.F32>;
... 10 more ...;
onUnitSphere: TgpuFn<...>;
}
randf
.
onUnitCircle: () => d.v2f

Returns a random 2D vector uniformly distributed on a unit circle.

onUnitCircle
() * (
const RIM: 3.2
RIM
-
const randf: {
seed: TgpuFn<(seed: d.F32) => d.Void>;
seed2: TgpuFn<(seed: d.Vec2f) => d.Void>;
seed3: TgpuFn<(seed: d.Vec3f) => d.Void>;
seed4: TgpuFn<(seed: d.Vec4f) => d.Void>;
sample: TgpuFn<() => d.F32>;
sampleExclusive: TgpuFn<() => d.F32>;
normal: TgpuFn<(mu: d.F32, sigma: d.F32) => d.F32>;
... 10 more ...;
onUnitSphere: TgpuFn<...>;
}
randf
.
sample: () => number

Returns a random f32 value in [0, 1) range.

sample
());
const next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
.
position: d.v3f
position
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(
const rim: d.v2f
rim
.
v2f.x: number
x
, 0,
const rim: d.v2f
rim
.
v2f.y: number
y
);
}
return
const next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
;
};
/** A soft dot whose light adds to what is behind it, blue when slow and ice when fast. */
const
const glow: (mote: Particle, local: d.v2f) => d.v4f

A soft dot whose light adds to what is behind it, blue when slow and ice when fast.

glow
= (
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
:
type Particle = {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

This type describes a particle in shaders.

Particle
,
local: d.v2f
local
:
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';
const
const edge: number
edge
=
import std
std
.
function saturate(value: number): number (+1 overload)
export saturate
saturate
(1 -
import std
std
.
length<d.v2f>(value: d.v2f): number (+1 overload)
export length
length
(
local: d.v2f
local
));
const
const color: d.v3f
color
=
import std
std
.
mix<d.v3f>(e1: d.v3f, e2: d.v3f, e3: number): d.v3f (+2 overloads)
export mix
mix
(
const SLOW: d.v3f

The kit's blue for slow motes and its ice for fast ones.

SLOW
,
const FAST: d.v3f
FAST
,
import std
std
.
function smoothstep(edge0: number, edge1: number, x: number): number (+1 overload)
export smoothstep
smoothstep
(0.9, 2.4,
import std
std
.
length<d.v3f>(value: d.v3f): number (+1 overload)
export length
length
(
mote: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
mote
.
velocity: d.v3f
velocity
)));
return
import d
d
.
const vec4f: d.Vec4f
(v0: AnyNumericVec3Instance, w: number) => d.v4f (+9 overloads)
vec4f
(
const color: d.v3f
color
* (
const edge: number
edge
*
const edge: number
edge
* 0.8), 0);
};
export async function
function createScene(root: TgpuRoot, surface: Surface): Promise<{
view: cameras.OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}>
createScene
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
surface: Surface
surface
:
(alias) interface Surface
import Surface

Provides a destination for frames, such as a canvas from web.surface or native.surface, or a texture from offscreenSurface in a test. Pass the frame to view for code that works with every destination.

Surface
) {
const
const view: cameras.OrbitCamera
view
=
import cameras
cameras
.
function orbit(root: TgpuRoot, options: cameras.OrbitOptions): cameras.OrbitCamera

Creates a perspective camera that orbits a target and eases towards a goal set by input.

@returns ― a camera you update every frame

orbit
(
root: TgpuRoot
root
, {
OrbitOptions.size: SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

size
:
surface: Surface
surface
,
OrbitOptions.target: readonly [number, number, number]

Sets the initial point that the camera orbits and looks at. Change it through goal.target.

target
: [0, 0, 0],
OrbitOptions.distance: number

Sets the initial distance from the target to the eye, in world units. Change it through goal.distance.

distance
: 8.5,
OrbitOptions.yaw?: number | undefined

Sets the initial yaw in radians around +y. At 0, the camera is on +z looking towards -z. Default 0.

yaw
: 0.3,
OrbitOptions.pitch?: number | undefined

Sets the initial pitch in radians above the horizon. Default 0.6.

pitch
: 0.6,
});
const
const sim: clock.FixedStep
sim
=
import clock
clock
.
function fixedStep(options: clock.FixedStepOptions): clock.FixedStep

Accumulates elapsed time for fixed simulation steps. Accumulates nothing while paused. Throws unless step is finite and above 0 and maxSteps is an integer above 0.

@returns ― a clock whose update says how many steps to run each frame

fixedStep
({
FixedStepOptions.step: number

Sets the step duration in seconds, such as 1 / 120.

step
: 1 / 60 });
const
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
=
import particles
particles
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: particles.Options & {
readonly particle?: typeof Particle;
}): particles.Particles (+1 overload)

Creates a GPU particle pool. CPU bursts and kernel emit calls allocate ring slots. Fixed steps move particles, and live lists list only live particles for drawing.

@injects ― member emit and the pool, which read its own buffers in any pipeline

@binds ― 2 storage: emit, the pool and its ring counter

@binds ― 1 storage: alive or particle, the pool

@binds ― 1 storage, 1 uniform: drawnAt, the pool and the last compact's ahead

@owns ― 6 buffers, 2 pipelines, liveLists: the pool, its ring counter, the burst queue and three uniforms; the live lists list the live particles. Each description drawing is added to builds its pipeline.

@records ― spawn once a submission before compact, step once per fixed step, compact once after the steps, then the draw a description added drawing as; clear whenever you like.

@param ― camera the camera the quads face unless place says otherwise; the callbacks read it too

@param ― options.update a 'use gpu' function; it and the other callbacks carry the fills of what they read beside the camera, such as tgpu.fn(rise).pipe(noise.inject())

@returns ― a system you destroy

create
(
root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options<S extends Schema = WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.capacity: number

Limits the number of particles alive at once. Each emitted particle takes the next ring slot.

capacity
:
const MOTES: 12000

How many motes circle the eye, and how far from it they start again.

MOTES
,
Options<S extends Schema = WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.step: number

Sets the length of a step in seconds, such as a fixed-step clock's sim.step. Each step advances by it.

step
:
const sim: clock.FixedStep
sim
.
FixedStep.step: number

Sets the step duration in seconds. A new value applies from the next update: unstepped time carries over, capped at maxSteps new steps, and time keeps the seconds already stepped. Particles and machines take its value when created and keep it. Throws unless the value is finite and above 0.

step
,
Options<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.update?: ((particle: NoInfer<{
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>, dt: number, slot: number) => NoInfer<{
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>) | undefined

Updates every live particle at the start of each step, including its first, before gravity, drag and motion. dt is the step duration in seconds. Use the slot for related data, such as pushing a trail point. Return the particle to keep, or set life to 0 to end it. The step kernel binds 1 storage buffer, the pool, so update and died share the other 7 of a stage. Default none, which leaves it unchanged.

@gpu

update
:
const swirl: (mote: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

One step of a mote: it circles the eye, faster closer in, falls slowly towards it, drifts on noise that changes with its age and is pulled back to the disc. In the eye it starts again near the rim, as every mote does on its first step.

swirl
,
Options<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.shade?: ((particle: NoInfer<{
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>, local: d.v2f) => d.v4f) | undefined

Returns premultiplied colour for a quad fragment at local coordinates in [-1, 1]. It shares 6 storage buffers with place, as place says. Default softDisc.

@gpu

shade
:
const glow: (mote: Particle, local: d.v2f) => d.v4f

A soft dot whose light adds to what is behind it, blue when slow and ice when fast.

glow
,
Options<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.settings?: Partial<d.InferInput<d.WgslStruct<{
gravity: d.Vec3f;
drag: d.F32;
}>>> | undefined

Sets initial gravity and drag over defaults. Set both to zero when update controls motion. Default defaults.

settings
: {
gravity: [number, number, number]
gravity
: [0, 0, 0],
drag: number
drag
: 0 },
});
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
Particles<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.burst(burst: particles.Burst<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>): boolean

Queues a burst for the next spawn, trimming it to the remaining capacity. Returns false if the queue is full or queued bursts fill capacity. Throws for a NaN count.

burst
({
Burst<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.count: number

Sets the burst count. All bursts queued before the same spawn share the system capacity.

count
:
const MOTES: 12000

How many motes circle the eye, and how far from it they start again.

MOTES
,
Burst<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.position: readonly [number, number, number]

Sets the centre of the starting box.

position
: [0, 0, 0],
Burst<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.size?: number | undefined

Sets quad width in world units. Default 0.1.

size
: 0.05,
Burst<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.life?: number | undefined

Sets particle lifetime in seconds. Default 1.

life
: 1e9 });
const
const scene: passes.Description<{
readonly color: typeof passes.color;
}>
scene
=
import passes
passes
.
function create(root: TgpuRoot, screen: passes.Screen, options?: passes.Options): passes.Description<{
readonly color: 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
(
root: TgpuRoot
root
,
surface: Surface
surface
, {
Options.clear?: readonly number[] | GPUColorDict | undefined

Sets the color target value where nothing drew. The pass reads it at each begin, so writing into it changes the next pass. Default transparent black.

clear
: [0.004, 0.006, 0.016, 1] })
.
Description<{ readonly color: typeof color; }>.pipe(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
}>

Adds fill after existing fills and returns a description of the same passes. Piped fills take precedence over a drawing's own. For example, passes.create(…).pipe(view.inject()) uses the camera from view.

pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

Fills cameras.current for the pipelines created from the configuration it is piped into.

inject
());
const
const shown: passes.Drawn
shown
=
const scene: passes.Description<{
readonly color: typeof passes.color;
}>
scene
.
Into<{ readonly color: typeof color; }>.add<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
color: d.v4f;
}>(drawing: passes.Drawing<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
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
(
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
System.drawing: passes.Drawing<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
color: d.v4f;
}>

Provides the particle drawing for pass descriptions, as in scene.add(system.drawing). It supplies colour, world position and corner data to outputs, tests depth without writing it and draws the list from the last compact. The description initAsync also compiles system kernels.

drawing
);
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
([
const scene: passes.Description<{
readonly color: typeof passes.color;
}>
scene
]);
return {
view: cameras.OrbitCamera
view
,
function frame(frame: Frame): void
frame
(
frame: Frame
frame
:
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
) {
const view: cameras.OrbitCamera
view
.
OrbitCamera.update(dt: number): void

Eases towards the goal by dt seconds and writes the uniform if the view changed. Call once per frame.

update
(
frame: Frame
frame
.
Frame.dt: number

Reports seconds since the previous submitted frame. The first frame has a dt of zero.

dt
);
const
const compute: TgpuComputePass
compute
=
frame: 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 motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
System.spawn(pass: TgpuComputePass): void

Spawns queued bursts before compact. Record it before steps to move those particles this frame, or after steps to show bursts queued during the steps. Each encoder takes one spawn with bursts, submitted before the next: the bursts upload through the queue before the submit runs, so a second spawn before then, in any pass or encoder, replaces the first one's bursts. Throws when one pass spawns bursts twice.

spawn
(
const compute: TgpuComputePass
compute
);
for (let
let steps: number
steps
=
const sim: clock.FixedStep
sim
.
FixedStep.update(dt: number): number

Adds dt seconds and returns the number of steps to run. Each step lasts step seconds, so a GPU kernel can use a fixed duration. All steps in a frame see the same queued CPU writes. Keep a step counter on the GPU for values that must change per step.

update
(
frame: Frame
frame
.
Frame.dt: number

Reports seconds since the previous submitted frame. The first frame has a dt of zero.

dt
);
let steps: number
steps
> 0;
let steps: number
steps
--)
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
System.step(pass: TgpuComputePass): void

Advances every live particle by one fixed step.

step
(
const compute: TgpuComputePass
compute
);
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
System.compact(pass: TgpuComputePass, ahead: number): void

Lists live particles for drawing. Record this once per frame after simulation steps. Drawing moves each particle ahead seconds along its velocity, such as a fixed-step clock's sim.ahead, so motion follows the display rate between steps.

compact
(
const compute: TgpuComputePass
compute
,
const sim: clock.FixedStep
sim
.
FixedStep.ahead: number

Reports the unstepped time in seconds, capped at one step. Equals alpha * step. Use it to draw objects that far along their velocity between simulation steps.

ahead
);
const compute: TgpuComputePass
compute
.
TgpuComputePass.end(): void

Completes the recording of this compute pass

end
();
const scene: passes.Description<{
readonly color: typeof passes.color;
}>
scene
.
Description<{ readonly color: typeof color; }>.record(frame: Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly color: 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: Frame
frame
,
const shown: passes.Drawn
shown
);
},
function destroy(): void
destroy
() {
const motes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
motes
.
System.destroy(): void

Destroys the pool, its counter, the burst queue and the live lists.

destroy
();
},
};
}
  • particles.create keeps the motes in a GPU buffer and runs swirl on each one as its update, in of its own. glow is its shade, and the default add blend sums the light of overlapping motes. Gravity and drag are 0 because swirl sets each velocity itself.
  • One burst starts every mote in the eye, so the first step sends it to the rim. spawn creates the burst’s motes, step moves them all, and compact lists the live ones for drawing.
  • clock.fixedStep turns each frame’s time into steps of 1/60 s, so the motes move at the same speed at any frame rate. sim.ahead is the time left over. Pass it to compact so the drawing can place each mote that many seconds farther along its velocity.
  • perlin3d and randf come from @typegpu/noise: smooth noise for the drift, and a random point near the rim for each mote that reaches the eye.

The scene returns its view, so src/index.ts is the one from the lit scene.

  • Each example is a scene of this shape and links to its source.
  • The module map lists what else a scene can create.
  • The hosting page covers controlling a scene from the page and running it on React Native.
moduleA module is one piece of GPU work, made by a factory that borrows your root and returns resources, shader functions and methods that record into your frame.A module borrows →
frameA frame is one turn of the loop, and the object your function gets for it, which holds the encoder, the time and the time since the last frame.You own the frame →
hostA host runs a scene for you, which means it makes the device, the surface and the frame loop and frees them in order.Hosting scenes →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
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 →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
surfaceA surface is a canvas set up for your root, which keeps its drawing buffer the size the page shows it at.Surfaces →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
targetA target is a texture that a frame draws into.Scenes and passes →
tone curveA tone curve maps light of any brightness into the range a screen can show, keeping detail in the bright parts.Words →
kernelA kernel is a compute function that the GPU runs many times at once, each run on its own thread.A frame in plain TypeGPU →