Skip to content

Concept3 of 5

Connecting modules

How a shader in one module reads the buffers and textures of another, and how the kit's own modules do it.

Read firstHow the kit works, for the frame and the seven rules every module follows

On this page

A particle reads the camera. A fish’s steering reads the neighbour grid. Your lighting reads ambient occlusion. Each time, a shader reads resources another owns. An instance’s members read that ’s own resources. A shader calls them and the pipeline needs nothing more, as with the ripple in How the kit works. A placeholder, such as the current camera, is filled by each pipeline from root.pipe(view.inject()).

A weather module keeps the wind in a uniform and offers windAt to other shaders. A snow module’s kernel calls it, so the snow takes the weather as an argument:

export function
function createWeather(root: TgpuRoot): {
state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>;
windAt: () => d.v2f;
}
createWeather
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
) {
const
const state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>
state
=
root: TgpuRoot
root
.
TgpuRoot.createUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>(typeSchema: d.WgslStruct<{
wind: d.Vec2f;
}>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslStruct<{
wind: d.Vec2f;
}>>>) => void) | d.InferInput<NoInfer<d.WgslStruct<{
wind: d.Vec2f;
}>>> | undefined): TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>> (+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
(
const WeatherState: d.WgslStruct<{
wind: d.Vec2f;
}>
WeatherState
);
return {
state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>
state
,
windAt: () => d.v2f
windAt
: () => {
'use gpu';
return
const state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>
state
.
TgpuUniform<WgslStruct<{ wind: Vec2f; }>>.$: {
wind: d.v2f;
}
$
.
wind: d.v2f
wind
;
},
};
}
export function
function createSnow(root: TgpuRoot, weather: ReturnType<typeof createWeather>): TgpuComputePipeline
createSnow
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
weather: {
state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>;
windAt: () => d.v2f;
}
weather
:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any

Obtain the return type of a function type

ReturnType
<typeof
function createWeather(root: TgpuRoot): {
state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>;
windAt: () => d.v2f;
}
createWeather
>) {
const
const drift: TgpuMutable<d.WgslArray<d.Vec2f>>
drift
=
root: TgpuRoot
root
.
TgpuRoot.createMutable<d.WgslArray<d.Vec2f>>(typeSchema: d.WgslArray<d.Vec2f>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.Vec2f>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.Vec2f>>> | undefined): TgpuMutable<d.WgslArray<d.Vec2f>> (+1 overload)

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

TgpuRoot.createBuffer

.

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

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

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

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

arrayOf
(
import d
d
.
const vec2f: d.Vec2f
vec2f
, 1024));
const
const fall: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
fall
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
computeFn: <{
gid: d.BuiltinGlobalInvocationId;
}>(options: {
in: {
gid: d.BuiltinGlobalInvocationId;
};
workgroupSize: number[];
}) => TgpuComputeFnShell<{
gid: d.BuiltinGlobalInvocationId;
}> (+1 overload)
computeFn
({
workgroupSize: number[]
workgroupSize
: [64],
in: {
gid: d.BuiltinGlobalInvocationId;
}
in
: {
gid: d.BuiltinGlobalInvocationId
gid
:
import d
d
.
const builtin: {
readonly vertexIndex: d.BuiltinVertexIndex;
readonly instanceIndex: d.BuiltinInstanceIndex;
readonly clipDistances: d.BuiltinClipDistances;
readonly position: d.BuiltinPosition;
readonly frontFacing: d.BuiltinFrontFacing;
readonly fragDepth: d.BuiltinFragDepth;
readonly primitiveIndex: d.BuiltinPrimitiveIndex;
readonly sampleIndex: d.BuiltinSampleIndex;
... 11 more ...;
readonly numSubgroups: d.BuiltinNumSubgroups;
}
export builtin
builtin
.
globalInvocationId: d.BuiltinGlobalInvocationId
globalInvocationId
} })(({
gid: d.v3u
gid
,
}) => {
'use gpu';
if (
gid: d.v3u
gid
.
v3u.x: number
x
>= 1024) return;
const drift: TgpuMutable<d.WgslArray<d.Vec2f>>
drift
.
TgpuMutable<WgslArray<Vec2f>>.$: d.v2f[]
$
[
gid: d.v3u
gid
.
v3u.x: number
x
] +=
weather: {
state: TgpuUniform<d.WgslStruct<{
wind: d.Vec2f;
}>>;
windAt: () => d.v2f;
}
weather
.
windAt: () => d.v2f
windAt
();
});
return
root: TgpuRoot
root
.
WithBinding.createComputePipeline<{
gid: d.BuiltinGlobalInvocationId;
}>(descriptor: TgpuComputePipeline.Descriptor<{
gid: d.BuiltinGlobalInvocationId;
}>): TgpuComputePipeline
createComputePipeline
({
compute: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
compute
:
const fall: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
fall
});
}
  • windAt reads this weather’s uniform in any pipeline. Two weathers’ windAt work side by side in one kernel.
  • A takes each module it reads as a named argument, never a list of modules.

An instance’s members carry their fill. They are made in create and read that instance’s resources: particles’ emit, the grid’s walk, counters’ add, ’ slot, text’s setLabel, the picker’s found, and the gpu members of a table or a machine. One kernel reads two of one definition through reds.gpu and blues.gpu.

A placeholder is filled by the pipeline. Each pipeline holds one fill for it, the last one piped:

  • A hook is a piece each pipeline chooses. Two can then draw the same through two cameras, such as a scene and a reflection. Hooks include cameras.current, the lighting’s reflect, ambient, fog and sunShadow, ao.at, dof.circle and video.sample.
  • A definition’s members, such as Enemy.position(i), exist before any table. material or a machine’s guards can use those members to work with any table of that definition. The table’s inject() fills them. The ’s vertexAt, the environment’s cube and the sun are placeholders too.

Two limits come with members:

  • A member is bound when its instance is created, and can’t be re-pointed at another copy. Code that serves any table of a layout reads the definition’s placeholders.
  • A pipeline that reads a member of a destroyed instance fails as it resolves, with TypeGPU’s This buffer has been destroyed.

The figure shows which resources a pipeline binds. Try calling the members of two block tables, reading through their definition or reading through the camera hook. Pipe in neither, one or both of the offered fills. When using both, you can change their order.

The resources a pipeline binds when two instances fill it

Try Choose what the shader reads and which instances fill the pipeline. A member binds its own instance whatever is piped; a placeholder binds the last instance piped.

Each module’s card lists its placeholders.

A module that takes a 'use gpu' function, such as particles’ update or bloom’s bright, builds its pipelines without knowing what the function reads. A member the function calls needs nothing more. For a placeholder, pipe its fill into the function itself:

const dust = particles.create(root, view, {
capacity: 2048,
step,
shade: tgpu.fn(puff).pipe(light.inject()), // reads the sun
});

Particles’ update, born, died and place, a trail’s width and shade, and the lighting’s shading hooks all take functions this way. A callback can read cameras.current.$ without a fill, because the description of passes fills the camera.

A fill binds a fixed resource, so replacing the resource would need a new pipeline. A resource that is replaced, such as a texture that follows the screen size or each new camera frame, goes in a bindings part instead. Your program shares every part into one layout before the pipelines that read the parts are built. It then sets that layout’s group on each pass.

  • Ambient occlusion and depth of field keep their textures in parts, because they follow the depth’s size.
  • A live video binds each camera frame through its part.
  • passes.create(…, { shared: { ao: occlusion.part } }) shares the parts, sets their group on every pass the description opens and fills them in the pipelines it builds.

A pipeline that reads a placeholder nothing filled fails at first use or in initAsync. Warm-up therefore catches it while loading. Placeholders that need a fill, such as cameras.current, default to unfilled, whose error names the inject() to add, as in The pipeline is missing a fill for `cameras.current`. …. Yours can do the same:

const wind = tgpu.accessor(d.vec2f, unfilled('the wind', 'weather', 'a `createWeather`'));

Some parts must be shared. A pipeline that reads one nobody shared throws as it builds, and the error names the call to add. If the part is shared but a pass description wasn’t given it, the draw throws instead, because the pass has no group for it.

Ambient occlusion and lighting use every way of connecting. The occlusion reaches the lighting through a callback. Both read the camera through a hook. The occlusion’s texture sits in a shared part, because a resize of the depth replaces it. The scene fills its shared parts in every pipeline it builds, so the callback needs no fill of its own:

import {
import ao
ao
,
import lighting
lighting
,
import passes
passes
,
import shading
shading
} from '@typegpu/kit';
const
const occlusion: ao.Ao
occlusion
=
import ao
ao
.
function create(root: TgpuRoot, view: cameras.CameraBase, options: ao.Options): ao.Ao

Creates ground-truth ambient occlusion (GTAO) from a depth texture drawn before shading. As Jimenez and others describe it in 2016, a trace walks slices directions per pixel with 3 steps each way and XeGTAO's falloff, and a denoise blurs 3 × 3 pixels of the same surface. Shading reads the result through ao.at, usually in an ambient hook: (material, point) => shading.hemisphere(material, point) * ao.at(point.position), in a description that shares the occlusion's part.

@injects ― hook the texture and region ao.at reads, from the part

@binds ― 0 storage, 1 uniform: ao.at, the region and frame, beside the texture

@allocates ― on resize: two textures for a new depth size and the bind groups of its passes; so does a new depth or normal texture

@owns ― targets, 2 or 3 buffers, 2 pipelines, 2 bind groups: the raw and the denoised occlusion; the settings, the region and frame, and with temporal the frame indices; the trace and the denoise, with a group each

@records ― record after the pass that draws depth, before the passes that shade; with temporal, a copy advances the frame.

@param ― view the camera that drew depth, which shading's cameras.current must match

@param ― options.depth the depth drawn before shading, read at every record

@param ― options.normal normals from ao.normal drawn with depth, read at every record

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

@returns ― occlusion you record every frame and destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options.depth: () => targets.Depth

Returns a sampled depth texture drawn before shading, such as a half-resolution prepass. record reads it on every call. Its size sets the size of the occlusion.

@cpu

depth
: () =>
const early: targets.Targets<Specs<{
readonly depth: {
readonly format: "depth32float";
readonly scale: 0.5;
readonly sampled: true;
};
}>>
early
.
Targets<Specs<{ readonly depth: { readonly format: "depth32float"; readonly scale: 0.5; readonly sampled: true; }; }>>.textures: {
readonly depth: targets.Target<{
readonly format: "depth32float";
readonly scale: 0.5;
readonly sampled: true;
}>;
}

Provides the current textures. A size change replaces them.

textures
.
depth: targets.Target<{
readonly format: "depth32float";
readonly scale: 0.5;
readonly sampled: true;
}>
depth
});
const
const sky: (material: shading.Material, point: shading.Point) => d.v3f
sky
= (
material: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
material
:
import shading
shading
.
type Material = {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}

This schema describes a surface with the glTF metallic-roughness model. New fields are only appended, each off at zero. Make one with a materials preset or copy one with Material(m), then assign the fields you set: a struct literal stops compiling when a field is added.

Material
,
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
:
import shading
shading
.
type Point = {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}

This schema describes a point being shaded in world space. New fields are only appended, each off at zero. Make one with pointAt, a copy Point(p) or a zero Point(), then assign the fields you set: a struct literal stops compiling when a field is added.

Point
) => {
'use gpu';
return
import shading
shading
.
const hemisphere: (material: shading.Material, point: shading.Point) => d.v3f

Computes ambient light by blending sky and ground colours according to the surface normal. Reflections sample the sky in the reflection direction. Roughness blends them towards diffuse light, and skyReflection scales them. The material's occlusion darkens both.

hemisphere
(
material: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
material
,
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
) *
import ao
ao
.
const at: (position: d.v3f) => number

Returns the visibility of sky light at a world position, from 0 in a closed crease to 1 in the open. It projects the position through cameras.current and blends the 4 nearest texels whose eye distance matches. Where none matches, such as on a translucent surface in front of the opaque one, it returns 1. Call it from shading, such as an ambient hook, in a description that shares the occlusion's part.

at
(
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
.
position: d.v3f
position
);
};
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly shading: {
readonly ambient: (material: shading.Material, point: shading.Point) => d.v3f;
};
}>(root: TgpuRoot, options?: ({
readonly shading: {
readonly ambient: (material: shading.Material, point: shading.Point) => d.v3f;
};
} & lighting.Options) | undefined): lighting.Lighting

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
(
const root: TgpuRoot
root
, {
shading: {
readonly ambient: (material: shading.Material, point: shading.Point) => d.v3f;
} & lighting.Shading

Sets the functions that shading.shade calls. Default pbr, hemisphere, heightFog, sunShadowed and reaching.

shading
: {
ambient: ((material: shading.Material, point: shading.Point) => d.v3f) & shading.AmbientHook

Computes ambient light. Default shading.hemisphere.

ambient
:
const sky: (material: shading.Material, point: shading.Point) => d.v3f
sky
}, // a callback
});
const
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
readonly depth: {
readonly format: "depth24plus";
};
}>, {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
readonly depth: {
readonly format: "depth24plus";
};
}>>, writes: {
readonly hdr: 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
(
const root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
readonly depth: {
readonly format: "depth24plus";
};
}>>
screen
,
{
hdr: typeof passes.color
hdr
:
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
},
{
Options.shared?: Shared | Readonly<Record<string, AnyPart>> | undefined

Shares these parts, by key, in one layout the description owns: every pass begin and record start sets its group, and every pipeline the description builds reads the parts through it. Takes the result of bindings.share instead when another description or a pass of your own reads the same parts. Create the description before any other pipeline that reads the parts. Default none.

shared
: {
ao: Part<Entries>
ao
:
const occlusion: ao.Ao
occlusion
.
Ao.part: Part<Entries>

Provides the texture and its region for ao.at. Share it before creating the pipelines that shade, so a new depth size replaces the texture without replacing pipelines: give passes.create { shared: { ao: occlusion.part } }, or call bindings.share(root, { ao: occlusion.part }) for passes of your own. A pipeline that reads ao.at without the share throws as it builds.

part
} }, // a part
)
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.pipe(fill: Inject): passes.Description<{
readonly hdr: 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
()) // a hook
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.pipe(fill: Inject): passes.Description<{
readonly hdr: 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 light: lighting.Lighting
light
.
Lighting.inject(): Inject

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

inject
()); // placeholders: the sun, the lights, the shadow

Ambient occlusion runs this scene in full, and Write a module builds a module of your own.

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 →
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 →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
factoryA factory is the function that creates a module, which allocates what the module needs and returns its resources, functions and recording methods.A module borrows →
live listA live list is a list of the live rows of one group, made on the GPU each frame so that a draw covers only them.Only what is alive →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
pass descriptionA pass description says once which textures a pass draws into and what each holds, and builds the pipeline for every drawing added to it.Scenes and passes →
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 →
kindA kind adds fields to the rows of a set of instances and replaces functions in the shaders that draw them.Kinds →
mesh poolA mesh pool stores every mesh's vertices in shared buffers, so one pipeline can draw any mesh.Mesh pool →