A mesh from meshes, imported from @typegpu/kit/geometry, has a vertexCount and a vertexAt(i) function marked 'use gpu'. The function computes each vertex from its index. A vertex shader can therefore draw a box without a vertex buffer.
A shape built one triangle at a time from its indices
Try Step through vertices to build triangles, with back faces dashed. The sphere, cylinder and torus use fewer segments than their defaults.
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
Each shape is centred at the origin. Each vertex is a meshes.Vertex with position, an outward normal and uv coordinates.
Shape
Size
Division
box()
width, height, depth default to 1
widthSegments, heightSegments, depthSegments default to 1
plane()
width, depth default to 1, in xz with normal +y
widthSegments, depthSegments default to 1
sphere()
radius defaults to 0.5
segments around default to 32, rings default to 16
cylinder()
radius defaults to 0.5, height defaults to 1, caps defaults to true
radialSegments default to 32, heightSegments default to 1
torus()
radius defaults to 0.35, tube defaults to 0.15
ringSegments default to 48, tubeSegments default to 24
icosphere()
radius defaults to 0.5
segments along each of its 20 triangles’ edges default to 4
capsule()
radius defaults to 0.25, height of the middle defaults to 0.5
segments along each patch’s edges default to 4
roundedBox()
width, height, depth default to 1, radius defaults to 0.1
segments along each patch’s edges default to 4
Use the option names in the , such as box({ width: 2, height: 0.5 }) or sphere({ segments: 12, rings: 8 }). The icosphere has evenly spaced triangles without crowded poles. Its interpolate function places points within each triangle.
Triangles wind counter-clockwise when viewed from outside, matching WebGPU’s default frontFace. Use cullMode: 'back' to draw the outside and 'front' to draw the inside, as of a room around the camera.
Combine shapes while keeping their vertices computed from indices:
Creates a 4-by-4 matrix which translates by the given vector v.
@param ― vector - The vector by which to translate.
@returns ― The translation matrix.
translation4(
import d
d.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(0,0.5,0))),
);
meshes.transform(shape, matrix) translates, rotates and scales with a d.m4x4f, including normals. Mirroring preserves triangle winding.
meshes.concat(a, b, ...) joins shapes with the same schema and topology into an indexed geometry. Its inputs can be unindexed.
meshes.map(shape, schema, fn) converts each vertex to schema. meshes.attach(shape, struct, fn) adds the fields returned by fn. Both preserve whether the shape is indexed.
The shapes are indexed. indexAt(i) identifies the vertex used by corner i, so triangles can share vertices. A box has 24 vertices and 36 indices.
Draw
Buffers
Draw with
Each vertex computed
meshes.unindexed(shape)
none
draw(vertexCount)
once per corner, every
meshes.bakeIndices(root, shape)
index
drawIndexed(indexCount)
about once, when the GPU reuses it
meshes.bake(root, shape)
vertex and index
drawIndexed(indexCount)
once, when baked
A box vertex needs only a few branches and a matrix multiply, so computing it each frame is cheap. A 32 × 16 sphere has 2 880 corners, each requiring sines and cosines. Bake shapes with more than a few hundred vertices. For many shapes drawn through one pipeline, use a mesh pool.
vertexIndex);// vertexIndex contains the value read from the index buffer
return{
position:d.v4f
position:
import cameras
cameras.
consttoClip:(point:d.v3f)=>d.v4f
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
Apply a baked mesh’s inject() to the pipeline. The vertex layout and index buffer belong to a pipeline, so do not apply it to the root.
Pass { encoder } or { pass } to record the fill into your own commands. Use bakeAsync or bakeIndicesAsync to compile fill pipelines under a loading screen.
A fully baked mesh exposes its vertices buffer and the layout set by inject() for vertex attributes. Call updateVertices(options) to refill vertices when values read by vertexAt change.
destroy() frees buffers allocated by the bake. It leaves caller-supplied buffers intact.
Bake option
Default
vertices
a new buffer
A vertex and matching the shape schema, with capacity for at least vertexCount. For bake only.
indices
a new buffer
A u32 index and storage buffer with capacity for at least indexCount.
encoder
none
Records the fill into your encoder instead of submitting one of its own.
pass
none
Records the fill into your compute pass. Not with encoder.
with
the root
Creates fill pipelines from this configuration, such as root.pipe(fill) when vertexAt reads .
bindGroups
none
Sets these on fill pipelines when vertexAt reads a caller-supplied layout.
A set of live lists takes a vertex or index count for each group in draws. A geometry supplies that count, so pass the shape:
const
constBlock:table.TableDef<"Block",{
shape:d.U32;
position:d.Vec3f;
},{}>
Block=
import table
table.
functiondefine<"Block",{
shape:d.U32;
position:d.Vec3f;
},{}>(name:"Block",parts:{
host?:{
shape:d.U32;
position:d.Vec3f;
}|undefined;
device?:{}|undefined;
}):table.TableDef<"Block",{
shape:d.U32;
position:d.Vec3f;
},{}>
Declares CPU-written host fields and GPU-written device fields using the records accepted by
d.struct. Throws if no fields are declared, a field
appears in both parts, the CPU writer cannot write a field type such as f16, or a field uses a
reserved member name such as alive.
name labels structs, buffers, WGSL functions and errors. It is not a lookup key. The
definition itself brands row ids, as RowId<typeof Enemy>.
@param ― name a label for ids and WGSL
@param ― parts the host fields the CPU writes and the device fields the GPU writes
@returns ― a definition whose getters shaders read and that table.create allocates
define('Block',{
host?:{
shape:d.U32;
position: d.Vec3f;
}|undefined
host:{
shape:d.U32
shape:
import d
d.
constu32:d.U32
export u32
A schema that represents an unsigned 32-bit integer value. (equivalent to u32 in WGSL)
Can also be called to cast a value to an u32 in accordance with WGSL casting rules.
Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1,
2^20].
@param ― def the definition its shaders were written against, from table.define
@returns ― a table you destroy
create(
constroot:TgpuRoot
root,
constBlock:table.TableDef<"Block",{
shape:d.U32;
position:d.Vec3f;
},{}>
Block,{
Options<T extends AnyTableDef>.capacity: number
Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0
to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The
generation has 29 bits at 8 rows and 12 bits at 2^20 rows.
Creates a list of live slots and an indirect draw per group. Each group reserves capacity
slots. A shader finds rows with live.slot(group, i) using a captured group index. With
firstInstance, it can use live.instanceSlot(instanceIndex) instead. Throws if the groups,
draws or workgroup size are invalid, the slot buffer exceeds maxStorageBufferBindingSize,
compact over the capacity needs more than maxComputeWorkgroupsPerDimension workgroups, or
firstInstance lacks its required feature.
@param ― options.alive whether a slot holds a live row, carrying the fills of what it reads, such
as a table's from rows.live(), spread into the options with its capacity
@param ― options.draws one draw per group
@returns ― live lists you run every frame and destroy
Provides the definition's shader members bound to this table, such as reds.gpu.position(i)
and reds.gpu.device.$[i]. A shader reads several tables of one definition through their
gpu members, with nothing piped.
A sprite is a square facing the camera. The shapes have no square in the xy plane. Read a 2 × 2 plane through position.xz, from -1 to 1, to place its 6 vertices facing the camera:
Gives the unit x and y axes of the view in world space, for quads that face the screen. With
the viewing direction from forwardOf, they form a right-handed basis.
right*
constcorner:d.v2f
corner.
v2f.x: number
x+
import cameras
cameras.
constcurrent:TgpuAccessor<d.WgslStruct<{
viewProjection:d.Mat4x4f;
position:d.Vec3f;
right:d.Vec3f;
up:d.Vec3f;
}>>
Provides the camera for a pipeline. A camera's inject() fills it with the camera uniform.
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
toClip(
constworld:d.v3f
world),
uv:d.v2f
uv:
constcorner:d.v2f
corner*0.5+0.5};
};
This use of the plane mirrors it, so its triangles wind clockwise on screen. Use the default cullMode: 'none' for sprites.
Passing both encoder and pass to a bake throws Supply either an encoder or a compute pass, not both.
A bake throws if a supplied buffer is too small. The message names the vertex or index count, such as The vertex count … exceeds the buffer capacity ….
concat throws if schemas or topologies differ. attach throws if a field already exists on the vertex.
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
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 →
storage bufferA storage buffer is GPU memory that shaders read by index and kernels can write, which is where the kit keeps rows.Words →
accessorAn accessor is a typed value that shader code reads and that each pipeline can fill with a different resource.Modules connect through TypeGPU →
bind groupA bind group is a set of buffers, textures and samplers that a pipeline reads, and a pipeline has room for four.Words →