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
importtype{
(alias)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame,
(alias)interfaceSurface
importSurface
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.
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
consttime: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.
constf32:d.F32
export f32
A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)
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.
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)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame,
type
(alias)interfaceSurface
importSurface
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.
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.
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.
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
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.
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,
constpool: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.
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.
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.
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.
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.
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,
constscreen:targets.Targets<Specs<{
readonly color:{
readonly format:GPUTextureFormat;
readonly samples:4;
};
readonly depth:{
readonly format:"depth24plus";
readonly samples:4;
};
}>>
screen,
{
color:typeofpasses.color
color:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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.
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
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(
constlight: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.
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.
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([
constlight:lighting.LightingOf<{
readonly shadow:{
readonly extent:12;
};
readonly settings:{
readonly sunDirection:[-0.6,0.7,0.5];
};
}>
light,
constscene:passes.Description<{
readonly color:typeofpasses.color;
readonly depth:typeofpasses.depth;
}>
scene]);
return{
view:cameras.OrbitCamera
view,
functionframe(frame:Frame):void
frame(
frame: Frame
frame:
(alias)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame){
constview: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.
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.
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.
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.
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,
constshown:passes.Drawn
shown);
},
functiondestroy():void
destroy(){
constlight: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.
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:
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
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
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)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame,
type
(alias)interfaceSurface
importSurface
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.
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.
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.
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
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.
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,
constpool: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.
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.
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.
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.
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
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,
constscreen: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:typeofpasses.color
color:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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.
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
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(
constlight: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.
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.
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.
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.
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([
constlight:lighting.LightingOf<{
readonly shadow:{
readonly extent:12;
};
readonly settings:{
readonly sunDirection:[-0.6,0.7,0.5];
};
}>
light,
constscene:passes.Description<{
readonly color:typeofpasses.color;
readonly depth:typeofpasses.depth;
}>
scene,
constglow:bloom.Bloom
glow,
constfinal:finish.Finish
final]);
return{
view:cameras.OrbitCamera
view,
functionframe(frame:Frame):void
frame(
frame: Frame
frame:
(alias)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame){
constview: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.
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.
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.
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.
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.
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));
},
functiondestroy():void
destroy(){
constlight: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.
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,
typeParticle={
position:d.v3f;
age:number;
velocity:d.v3f;
life:number;
color:d.v4f;
size:number;
seed:number;
}
constParticle: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)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame,
type
(alias)interfaceSurface
importSurface
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)namespaceperlin3d
import perlin3d
perlin3d,
constrandf:{
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>;
...10more...;
onUnitSphere:TgpuFn<...>;
}
randf}from'@typegpu/noise';
import{
import d
d,
import std
std,type
(alias)interfaceTgpuRoot
importTgpuRoot
TgpuRoot}from'typegpu';
/** How many motes circle the eye, and how far from it they start again. */
const
constMOTES:12000
How many motes circle the eye, and how far from it they start again.
MOTES=12_000;
const
constRIM:3.2
RIM=3.2;
/** The kit's blue for slow motes and its ice for fast ones. */
const
constSLOW:d.v3f
The kit's blue for slow motes and its ice for fast ones.
SLOW=
import d
d.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(0.3,0.47,1);
const
constFAST:d.v3f
FAST=
import d
d.
constvec3f: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
constswirl:(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.
Holds a random value in [0, 1), fixed at birth, for variation in update and shade.
seed*0.4){
constrandf:{
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>;
...10more...;
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.
constvec2f: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
constrim:d.v2f
rim=
constrandf:{
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>;
...10more...;
onUnitSphere:TgpuFn<...>;
}
randf.
onUnitCircle:()=>d.v2f
Returns a random 2D vector uniformly distributed on a unit circle.
onUnitCircle()*(
constRIM:3.2
RIM-
constrandf:{
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>;
...10more...;
onUnitSphere:TgpuFn<...>;
}
randf.
sample:()=> number
Returns a random f32 value in [0, 1) range.
sample());
constnext:{
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.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(
constrim:d.v2f
rim.
v2f.x: number
x,0,
constrim:d.v2f
rim.
v2f.y: number
y);
}
return
constnext:{
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
constglow:(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:
typeParticle={
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
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.
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.
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())
Sets the length of a step in seconds, such as a fixed-step clock's sim.step. Each step
advances by it.
step:
constsim: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.
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:
constswirl:(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.
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:
constglow:(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.
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.
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
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
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(
constmotes: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.
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([
constscene:passes.Description<{
readonly color:typeofpasses.color;
}>
scene]);
return{
view:cameras.OrbitCamera
view,
functionframe(frame:Frame):void
frame(
frame: Frame
frame:
(alias)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame){
constview: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
constcompute: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.
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(
constcompute:TgpuComputePass
compute);
for(let
let steps:number
steps=
constsim: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.
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(
constcompute:TgpuComputePass
compute,
constsim: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.
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,
constshown:passes.Drawn
shown);
},
functiondestroy():void
destroy(){
constmotes: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 →