Memory on the GPU can be allocated and managed through buffers. That way, WGSL shaders can be provided with an additional context, or retrieve the
results of parallel computation back to JS. When creating a buffer, a schema for the contained values has to be provided, which allows for:
Calculating the required size of the buffer,
Automatic conversion to-and-from a binary representation,
Type-safe APIs for writing and reading.
As an example, let’s create a buffer for storing particles.
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
To create a buffer, you will need to define its schema by composing data types imported from typegpu/data. Every WGSL data-type can be represented as JS schemas, including
structs and arrays. They will be explored in more detail in a following chapter.
const countBuffer =
const root:TgpuRoot
root.
TgpuRoot.createBuffer<d.U32>(typeSchema: d.U32, initial?: number | ((buffer:TgpuBuffer<NoInfer<d.U32>>)=>void) |undefined): TgpuBuffer<d.U32> (+1 overload)
Allocates memory on the GPU, allows passing data between host and shader.
@remarks ― Typed wrapper around a GPUBuffer.
@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)
createBuffer(
import d
d.
const u32: 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 memory on the GPU, allows passing data between host and shader.
@remarks ― Typed wrapper around a GPUBuffer.
@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)
createBuffer(
import d
d.
struct<{
a:d.F32;
b:d.F32;
}>(props: {
a: d.F32;
b: d.F32;
}): d.WgslStruct<{
a:d.F32;
b:d.F32;
}>
export struct
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
For type annotations, you can use named aliases instead of intersecting with usage flags manually:
TgpuUniformBuffer, TgpuStorageBuffer, TgpuVertexBuffer, and TgpuIndexBuffer.
const
const buffer:TgpuUniformBuffer<d.U32>
buffer:
type TgpuUniformBuffer<TextendsBaseData> =TgpuBuffer<T> &UniformFlag
TgpuUniformBuffer<
import d
d.
export U32
Unsigned 32-bit integer schema representing a single WGSL u32 value.
U32> =
const root:TgpuRoot
root.
TgpuRoot.createBuffer<d.U32>(typeSchema: d.U32, initial?: number | ((buffer:TgpuBuffer<NoInfer<d.U32>>)=>void) |undefined): TgpuBuffer<d.U32> (+1 overload)
Allocates memory on the GPU, allows passing data between host and shader.
@remarks ― Typed wrapper around a GPUBuffer.
@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)
createBuffer(
import d
d.
const u32: 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.
It is also possible to add any of the GPUBufferUsage flags to a typed buffer object, using the .$addFlags method.
Though it shouldn’t be necessary in most scenarios as majority of the flags are handled automatically by the library
or indirectly through the .$usage method.
Flags can only be added this way if the typed buffer was not created with an existing GPU buffer.
If it was, then all flags need to be provided to the existing buffer when constructing it.
You can also pass an initial value to the root.createBuffer function.
When the buffer is created, it will be mapped at creation, and the initial value will be written to the buffer.
// Will be initialized to `100`
const
const buffer1:TgpuBuffer<d.U32>
buffer1 =
const root:TgpuRoot
root.
TgpuRoot.createBuffer<d.U32>(typeSchema: d.U32, initial?: number | ((buffer:TgpuBuffer<NoInfer<d.U32>>)=>void) |undefined): TgpuBuffer<d.U32> (+1 overload)
Allocates memory on the GPU, allows passing data between host and shader.
@remarks ― Typed wrapper around a GPUBuffer.
@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)
createBuffer(
import d
d.
const u32: 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.
@exampleconst value = u32(); // 0
@exampleconst value = u32(7); // 7
@exampleconst value = u32(3.14); // 3
@exampleconst value = u32(-1); // 4294967295
@exampleconst value = u32(-3.1); // 0
u32, 100);
// Will be initialized to an array of two vec3fs with the specified values.
For cases where a plain typed value is not enough, you can also pass an initializer callback.
It receives the newly created typed buffer while it is still mapped, so you can populate it with multiple writes or helper utilities before the first upload.
You can also create a buffer using an existing WebGPU buffer. This is useful when you have existing logic but want to introduce type-safe data operations.
To write data to a buffer from the CPU, you can use the .write(value) method. The typed schema enables auto-complete as well as static validation of this
method’s arguments.
const
const Particle: d.WgslStruct<{
position:d.Vec2f;
health:d.U32;
}>
Particle =
import d
d.
struct<{
position:d.Vec2f;
health:d.U32;
}>(props: {
position: d.Vec2f;
health: d.U32;
}): d.WgslStruct<{
position:d.Vec2f;
health:d.U32;
}>
export struct
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
.write() accepts several equivalent forms — you don’t need to construct typed instances:
Input form
Example for vec3f
Example for mat2x2f
Notes
Typed instance
d.vec3f(1, 2, 3)
d.mat2x2f(1, 2, 3, 4)
Allocates a TypeGPU wrapper object
Plain JS array
[1, 2, 3]
[1, 2, 3, 4]
No TypeGPU wrapper allocated
TypedArray
new Float32Array([1, 2, 3])
new Float32Array([1, 2, 3, 4])
Bytes copied as-is — must match GPU layout
ArrayBuffer
rawBytes
rawBytes
Bytes copied as-is — must match GPU layout
When data already lives in tuples or typed arrays, skipping typed instance construction avoids allocating TypeGPU wrapper objects, which can reduce garbage-collector pressure in hot paths such as per-frame updates or simulation ticks.
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
@location ― .
Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).
arrayOf(
const Particle: d.WgslStruct<{
position:d.Vec3f;
velocity:d.Vec3f;
health:d.F32;
}>
Particle, 100));
// Bytes already laid out exactly as the GPU expects
declare const
const rawBytes:ArrayBuffer
rawBytes:
interface ArrayBuffer
Represents a raw buffer of binary data, which is used to store data for the
different typed arrays. ArrayBuffers cannot be read from or written to directly,
but can be passed to a typed array or DataView Object to interpret the raw
buffer as needed.
You can write a contiguous slice of data into a buffer using the optional second argument of .write().
Pass the values to write along with startOffset - the byte position at which writing begins.
An optional endOffset specifies the byte offset at which writing stops entirely.
Combined with startOffset and d.memoryLayoutOf, this lets you write to a precise region of the buffer. If omitted, writing will continue until the end of the provided data or the end of the buffer, whichever comes first.
When you want to update only a subset of a buffer’s fields, you can use the .patch(data) method. This method updates only the fields provided in the data object and leaves the rest unchanged.
The format of the data value depends on your schema type:
For d.struct schemas:
Provide an object with keys corresponding to the subset of the schema’s fields you wish to update.
For d.array schemas:
Provide an object with numeric keys as indices mapped to new values (sparse update),
a plain array for full replacement, or a TypedArray for byte-level replacement.
const
const Planet: d.WgslStruct<{
radius:d.F32;
mass:d.F32;
position:d.Vec3f;
colors:d.WgslArray<d.Vec3f>;
}>
Planet =
import d
d.
struct<{
radius:d.F32;
mass:d.F32;
position:d.Vec3f;
colors:d.WgslArray<d.Vec3f>;
}>(props: {
radius: d.F32;
mass: d.F32;
position: d.Vec3f;
colors: d.WgslArray<d.Vec3f>;
}): d.WgslStruct<{
radius:d.F32;
mass:d.F32;
position:d.Vec3f;
colors:d.WgslArray<d.Vec3f>;
}>
export struct
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
When the buffer schema is an array<struct<...>>, you can write the data in a struct-of-arrays form with writeSoA from typegpu/common.
This is useful when your CPU-side data is already stored per-field, such as simulation attributes kept in separate typed arrays.
const
const Particle: d.WgslStruct<{
pos:d.Vec3f;
vel:d.F32;
}>
Particle =
import d
d.
struct<{
pos:d.Vec3f;
vel:d.F32;
}>(props: {
pos: d.Vec3f;
vel: d.F32;
}): d.WgslStruct<{
pos:d.Vec3f;
vel:d.F32;
}>
export struct
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
writeSoA converts those field-wise arrays into the buffer’s GPU array-of-structs layout before uploading.
For the example above, the resulting bytes match two Particle structs laid out in memory, including the padding required by vec3f.
You can also restrict the write to a slice of the destination buffer:
const
const Entry: d.WgslStruct<{
id:d.U32;
values:d.WgslArray<d.Vec3f>;
}>
Entry =
import d
d.
struct<{
id:d.U32;
values:d.WgslArray<d.Vec3f>;
}>(props: {
id: d.U32;
values: d.WgslArray<d.Vec3f>;
}): d.WgslStruct<{
id:d.U32;
values:d.WgslArray<d.Vec3f>;
}>
export struct
Creates a struct schema that can be used to construct GPU buffers.
Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema).
The order of members matches the passed in properties object.
The byte offset of the primitive within the buffer.
offset,
endOffset?: number |undefined
endOffset:
const end:PrimitiveOffsetInfo
end.
PrimitiveOffsetInfo.offset: number
The byte offset of the primitive within the buffer.
offset,
},
);
If endOffset is omitted, TypeGPU infers the written range from the provided field arrays and stops at the shortest complete element count implied by the data.
startOffset is still byte-based and should point to the start of a struct element, so d.memoryLayoutOf is the safest way to compute it.
All struct fields must be present in the SoA object.
There’s also an option to copy value from another typed buffer using the .copyFrom(buffer) method,
as long as both buffers have a matching data schema.
For a mapped buffer, TypeGPU clears the mapped memory directly.
Otherwise, it records and submits a WebGPU clearBuffer command.
Both .copyFrom(...) and .clear() accept an optional command encoder as the last argument.
The command is then recorded into the encoder instead of being submitted on its own.
Call .destroy() when an owned buffer is no longer needed.
TypeGPU releases a buffer that it created itself; if the TypeGPU wrapper was created around an existing GPUBuffer, the external buffer remains owned by its original caller.
TypeGPU also allows for the use of index buffers. An index buffer is a buffer containing a sequence of u32 or u16 indices, which indicate in which order vertices will be processed. This is particularly useful for rendering geometry, where vertices are often shared between multiple primitives (e.g., triangles), as it avoids duplicating vertex data.
You may refer to the pipelines section for usage details.
Creates a compute pipeline that executes the given callback in an exact number of threads.
This is different from createComputePipeline() in that it does a bounds check on the
thread id, where as regular pipelines do not and work in units of workgroups.
@param ― callback A function converted to WGSL and executed on the GPU.
It can accept up to 3 parameters (x, y, z) which correspond to the global invocation ID
of the executing thread.
@example
If no parameters are provided, the callback will be executed once, in a single thread.
const fooPipeline = root
.createGuardedComputePipeline(()=> {
'use gpu';
console.log('Hello, GPU!');
});
fooPipeline.dispatchThreads();
// [GPU] Hello, GPU!
@example
One parameter means n-threads will be executed in parallel.
const fooPipeline = root
.createGuardedComputePipeline((x)=> {
'use gpu';
if (x %16===0) {
// Logging every 16th thread
console.log('I am the', x, 'thread');
}
});
// executing 512 threads
fooPipeline.dispatchThreads(512);
// [GPU] I am the 256 thread
// [GPU] I am the 272 thread
// ... (30 hidden logs)
// [GPU] I am the 16 thread
// [GPU] I am the 240 thread
createGuardedComputePipeline((
x: number
x) => {
'use gpu';
// Access and modify the bound buffer via the layout
For scenarios where buffers remain consistent across multiple compute or render operations,
TypeGPU offers fixed resources that appear bindless from a code perspective.
Fixed buffers are created using dedicated root methods.
Creates a compute pipeline that executes the given callback in an exact number of threads.
This is different from createComputePipeline() in that it does a bounds check on the
thread id, where as regular pipelines do not and work in units of workgroups.
@param ― callback A function converted to WGSL and executed on the GPU.
It can accept up to 3 parameters (x, y, z) which correspond to the global invocation ID
of the executing thread.
@example
If no parameters are provided, the callback will be executed once, in a single thread.
const fooPipeline = root
.createGuardedComputePipeline(()=> {
'use gpu';
console.log('Hello, GPU!');
});
fooPipeline.dispatchThreads();
// [GPU] Hello, GPU!
@example
One parameter means n-threads will be executed in parallel.
Dispatches the pipeline.
Unlike TgpuComputePipeline.dispatchWorkgroups(), this method takes in the
number of threads to run in each dimension.
Under the hood, the number of expected threads is sent as a uniform, and
"guarded" by a bounds check.
dispatchThreads(100);
TypeGPU automatically generates a “catch-all” bind group and populates it with the fixed resources.
Each entry is visible only to the shader stages that use it, so it doesn’t count towards the limits of other stages, such as maxStorageBuffersPerShaderStage.
You can also use resolveWithContext to access the automatically generated bind group and layout containing your fixed resources.