A horse may walk, gallop, graze or bolt. Tracking this by hand requires a state field, a start time and transition checks each step. Weighted choices need cumulative probabilities, and gait changes need separate speed thresholds to prevent flicker. A state machine defines the states and their transitions. Run it per GPU with machines.create or on the CPU with machines.run.
Forty horses move between four gait states
Try Raise urgency until a horse's pace crosses 5.2 m/s and it gallops, then lower it. The horse keeps galloping until its pace falls below 4.2 m/s. Startle bolts every horse that is not bolting already.
Declares states, ordered transitions and events for a state machine. Each state can run hooks
when entered or left. Use run on the CPU with plain functions, or create on the GPU with
shader functions that take row slots. Needs no root, so define it where the resources its hooks
read live.
name brands states as State<'Mood'> and labels WGSL functions and errors. It is not a lookup
key. Throws for undeclared transition targets or events, invalid delays, chances or rates,
chances that sum above 1, or a transition with both a chance and a rate. Also throws for missing
states, duplicate events, more than 31 events, numeric state names or reserved names such as
state and __proto__.
@param ― name a label for types and WGSL
@param ― spec the events, then the states; machines start in the first
@returns ― a definition that run runs on the CPU and create runs per row on the GPU
Allows the transition when the guard returns true. Checked last, after the other conditions
hold.
when:
functioncalm(i:number):boolean
calm,
Transition<K extends string,E extends string>.rate?: number |undefined
Sets an average transition rate per second. For a step of dt seconds, reserves a share 1 - e^(-rate * dt) of the roll after earlier shares. Truncates shares at 1.
Transition<"bolting"|"walking"|"galloping"|"grazing","startle">.after?: number |((i:number)=> number)|undefined
Sets the delay in seconds after entering the state. A function computes the delay for machine
i.
after:4,
Transition<K extends string,E extends string>.rate?: number |undefined
Sets an average transition rate per second. For a step of dt seconds, reserves a share 1 - e^(-rate * dt) of the roll after earlier shares. Truncates shares at 1.
Creates a GPU state machine for every slot in a table or another set of rows. Rows start in the
first state without running enter. Call start(slot) when adding a row. Shaders read rows
with gpu.state(i) and gpu.since(i), and send events with gpu.send. Throws for invalid
capacity or step duration, a capacity whose threads, 64 to a workgroup, pass the device's
maxComputeWorkgroupsPerDimension, invalid or duplicate listed states, more than 256 lists, or
lists exceeding maxStorageBufferBindingSize.
@param ― def the definition, from machines.define
@param ― options.alive whether a slot holds a live row, such as a table's from rows.live(),
spread into the options with its capacity
@returns ― rows you step at each fixed step and destroy
Options<N extends string = string>.capacity: number
Sets the number of row slots, from 0 to capacity - 1. Must be an integer in [1, 2^24].
capacity:8192,
Options<N extends string = string>.step: number
Sets the length of a step in seconds, such as a fixed-step clock's sim.step. Transitions
compile it into their waits and rate shares.
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.
step});
Conditions A transition requires all its conditions to hold. on checks an event, after checks time in the state, and chance or rate checks a random roll. when, a shader function of the row, runs last. The first matching transition runs, at most once per step.
Start state Machines start in the first state. A state is a number, a literal in WGSL: Gait.galloping is 1.
Two thresholdsgalloping leaves below 4.2 m/s and walking above 5.2, so a horse between them keeps its gait instead of flickering.
Chances Chance transitions take consecutive shares of one roll per step. Values of 0.05, 0.15 and 0.3 take 5, 15 and 30 % of the rolls. Later transitions get the remaining rolls. If none match, the state rolls again next step.
Rates A rate matches once per 1 / rate seconds on average, independent of step length. A calm walking horse starts grazing every 33 s on average. A grazing horse waits at least 4 s, then resumes walking after another 3 s on average.
Shared transitions A transition declared outside the , like startled, needs as const so its target stays a name.
Where to define The definition needs no root. Define it where its guards and reach the resources they read, such as inside the that makes the herd, so they call the herd’s .
Errors TypeScript rejects a target or an event the definition doesn’t declare, and a state named like a number or one of the definition’s members, such as state or start. define throws for those too, and for a negative delay, chances past 1, or a chance and a rate on one transition.
gaits.gpu holds members bound to these rows. Shaders read a row’s state with gaits.gpu.state(i) and its seconds in it with gaits.gpu.since(i), and compute shaders send an event with gaits.gpu.send.startle(i). A pipeline that reads them needs .
Records a frame into one encoder and submits once, with a clock. Borrows the root. The
synchronous recorder borrows each frame's encoder.
@submits ― always once a frame after your recorder returns, and again at each frame.submit()
@param ― record your frame, recorded into each frame's encoder
@returns ― a loop you run with each frame's time and destroy
create(
constroot:TgpuRoot
root,(
frame:frames.Frame
frame)=>{
const
constpass:TgpuComputePass
pass=
frame:frames.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.
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:frames.Frame
frame.
Frame.dt: number
Reports seconds since the previous submitted frame. The first frame has a dt of zero.
Uploads pending CPU starts and events, records one step for every live row, then lists the
rows in each state of lists. Guards and hooks are row-local: another row's state reads from
before or after that row's step, and an event to another row may reach this step or the next.
step(
constpass:TgpuComputePass
pass);
}
constpass:TgpuComputePass
pass.
TgpuComputePass.end(): void
Completes the recording of this compute pass
end();
});
step(pass) updates every live row once. A newly started row runs only its state’s enter. Other rows advance their time by one step and check transitions. A transition runs the old state’s exit, changes the state and runs its enter. Both hooks are shader functions of the row. Put ongoing state work in your own , as move does by branching on gait.state(i).
The skeletons run 300 machines this way. Each enter rolls the next action’s length or destination, writes its motion to the skeleton’s row and starts its clip with the poses verbs. An attacker’s enter walks a neighbour grid to turn on the nearest skeleton.
Members Guards and hooks read the definition’s members, such as Gait.state(i), which the step fills with its rows. They can’t read gaits.gpu, because the step binds the rows read-write.
State in hooksGait.state(i) reads the old state in exit and the new one in enter. A transition to the state it leaves runs both and starts since from 0.
Time in guards In a guard, Gait.since(i) reads time before this step. after compares against time including this step.
Events An event lasts until the row’s next step, which handles or drops it. Events sent after a ’s last step wait for the next frame. A hook’s event to its own row reaches the next step.
Row-local Guards and hooks are exact for their own row only. Another row’s state reads from before or after that row’s step, and an event to it may reach this step or the next. Compare rows in a kernel after the step.
Delaysafter rounds delays up to whole steps. A 4 s delay at 1/60 s takes 240 steps. Use after: (i) => … for a per-row delay in seconds, evaluated every step.
Rolls A state with chances or rates rolls once a step from randf, seeded by row and step. Pass roll(i, tick) to draw it another way, such as from a blue-noise texture.
Random numbersGait.roll(i) draws a number in [0, 1) from roll in guards, hooks and after functions. An after function runs every step, so a delay rolled there changes each step. For a fixed random delay, roll in enter, store the result in a field and read it from after.
Fills What pipe(fill) fills also reaches alive and roll, which share the step’s pipeline with guards and hooks. Members of instances need no fill.
Empty slotsalive skips the without a row. A gives it with its capacity and span, so a step runs no above the span: machines.create(root, Gait, { ...horses.live(), step: sim.step }).
Reading back Read rows back for a test or a display of your own.
move runs for every horse and branches on its state. A group of 32 lanes executes a state’s branch whenever any of its rows uses that state. Scattered bolting horses therefore make nearly every group execute the bolt branch. Pass lists to collect rows by state each step, and a kernel over one state’s list.
Creates a GPU state machine for every slot in a table or another set of rows. Rows start in the
first state without running enter. Call start(slot) when adding a row. Shaders read rows
with gpu.state(i) and gpu.since(i), and send events with gpu.send. Throws for invalid
capacity or step duration, a capacity whose threads, 64 to a workgroup, pass the device's
maxComputeWorkgroupsPerDimension, invalid or duplicate listed states, more than 256 lists, or
lists exceeding maxStorageBufferBindingSize.
@param ― def the definition, from machines.define
@param ― options.alive whether a slot holds a live row, such as a table's from rows.live(),
spread into the options with its capacity
@returns ― rows you step at each fixed step and destroy
Options<N extends string = string>.capacity: number
Sets the number of row slots, from 0 to capacity - 1. Must be an integer in [1, 2^24].
capacity:
constCOUNT:8192
COUNT,
Options<N extends string = string>.step: number
Sets the length of a step in seconds, such as a fixed-step clock's sim.step. Transitions
compile it into their waits and rate shares.
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.
Lists rows in these states after each step into listed, for kernels that run over them.
Uses one word per row for each listed state. Accepts at most 256 states. Default none.
Holds the rows in each state of lists after the last step, group k for lists[k], for
work of your own through listed.slot and listed.dispatch. Undefined without lists.
Returns the live row count for group in a shader. Kernels run by
dispatch must return for threads at or beyond this count. Pass group as a captured
constant.
count(0))return;
functionflee(i:number):void
flee(
constbolting:LiveLists
bolting.
LiveLists.slot: (group:number,i:number)=> number
Returns the slot of live row i in group. Pass group as a captured constant.
Records a frame into one encoder and submits once, with a clock. Borrows the root. The
synchronous recorder borrows each frame's encoder.
@submits ― always once a frame after your recorder returns, and again at each frame.submit()
@param ― record your frame, recorded into each frame's encoder
@returns ― a loop you run with each frame's time and destroy
create(
constroot:TgpuRoot
root,(
frame:frames.Frame
frame)=>{
const
constpass:TgpuComputePass
pass=
frame:frames.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.
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:frames.Frame
frame.
Frame.dt: number
Reports seconds since the previous submitted frame. The first frame has a dt of zero.
Uploads pending CPU starts and events, records one step for every live row, then lists the
rows in each state of lists. Guards and hooks are row-local: another row's state reads from
before or after that row's step, and an event to another row may reach this step or the next.
Dispatches the pipeline set on the compute pass over the live rows of group. Record it after
compact. Dispatches enough workgroups of workgroupSize for count(group) threads. Each
thread finds its row with slot(group, i).
dispatch(
constpass:TgpuComputePass
pass,0);
}
constpass:TgpuComputePass
pass.
TgpuComputePass.end(): void
Completes the recording of this compute pass
end();
});
gaits.listed is a set of live lists. Each step fills it with the rows in the states they end the step in, in no order.
listed.dispatch(pass, k) runs the pipeline set on the pass over the list from the most recent step, in of 64 threads. A thread past listed.count(k) returns, and the rest find their row with listed.slot(k, i).
Each list uses one word per row. At most 256 states can have lists.
Rows sit in the first state without running its enter. start(slot, state?) puts a row in a state as you add it, and its enter runs at the next step. The stampede starts its whole herd galloping this way.
A start skips the old state’s exit and drops the row’s waiting events, from the CPU or from kernels.
The next step uploads starts and events with queue.writeBuffer. Consecutive started slots use one write. Call flush() before the frame’s steps when a frame may draw without stepping.
With kernelStarts: true, compute shaders can start rows with gaits.gpu.start(i, Gait.bolting). The row applies the start at its next step. A kernel start takes precedence over a CPU start in the same step.
A definition with plain functions for guards and hooks runs on the CPU with machines.run. The horses in the figure above run this way, and a step allocates nothing.
Declares states, ordered transitions and events for a state machine. Each state can run hooks
when entered or left. Use run on the CPU with plain functions, or create on the GPU with
shader functions that take row slots. Needs no root, so define it where the resources its hooks
read live.
name brands states as State<'Mood'> and labels WGSL functions and errors. It is not a lookup
key. Throws for undeclared transition targets or events, invalid delays, chances or rates,
chances that sum above 1, or a transition with both a chance and a rate. Also throws for missing
states, duplicate events, more than 31 events, numeric state names or reserved names such as
state and __proto__.
@param ― name a label for types and WGSL
@param ― spec the events, then the states; machines start in the first
@returns ― a definition that run runs on the CPU and create runs per row on the GPU
Transition<"walking"|"idling"|"waking"|"taunting"|"attacking", never>.after?: number |((i:number)=> number)|undefined
Sets the delay in seconds after entering the state. A function computes the delay for machine
i.
after:
constlasted:(i:number)=>number
lasted,
Transition<K extends string,E extends string>.chance?: number |undefined
Assigns the transition a share of one roll in [0, 1) per step. The state's chances and rates
take consecutive shares of that roll in order. Chances of 0.05, 0.15 and 0.3 receive 5,
15 and 30 % respectively. The chances must sum to at most 1.
Transition<"walking"|"idling"|"waking"|"taunting"|"attacking", never>.after?: number |((i:number)=> number)|undefined
Sets the delay in seconds after entering the state. A function computes the delay for machine
i.
after:
constlasted:(i:number)=>number
lasted,
Transition<K extends string,E extends string>.chance?: number |undefined
Assigns the transition a share of one roll in [0, 1) per step. The state's chances and rates
take consecutive shares of that roll in order. Chances of 0.05, 0.15 and 0.3 receive 5,
15 and 30 % respectively. The chances must sum to at most 1.
Runs a definition on the CPU with every machine in the first state. Runs that state's enter at
the first step. Throws unless count is an integer above 0.
Reports seconds since the previous submitted frame. The first frame has a dt of zero.
dt));
An event sent from a hook reaches the step after.
A delay matches at the first step that reaches it. The next state counts time from that step, so each timed transition can add up to one step of delay.
In React, subscribe drives a game’s flow: useSyncExternalStore(flow.subscribe, () => flow.state()).
random draws the rolls, Math.random by default. Pass a seeded one for tests that repeat.
No nesting A definition is flat, with no nested states, concurrent regions or history states.
One transition One transition a step, so a chain of three takes three steps.
Capacity A step runs a thread a slot, 64 to a workgroup, so create throws past 64 times the device’s maxComputeWorkgroupsPerDimension: 4 194 240 slots at WebGPU’s default.
31 events At most 31 events a definition; a row holds them as bits until its next step.
Step length On the GPU, after and since count steps of the step the rows were created with, compiled into the transitions. Steps recorded at another length read wrong.
Dead rows On the GPU, a slot keeps its row’s last state when the row dies. Start the slot again for the next row in it, from the CPU or a kernel.
Seeding On the GPU, rows started from the CPU begin their rolls at a tick random draws, Math.random by default, so two runs roll alike only with a seeded one.
One instance A definition’s functions, such as Gait.state(i), read one machines.create in a pipeline, the last piped in. Each instance’s gpu members read its own rows, so one kernel reads two.
Bindings The step pipeline uses 2 to 7 and at most one uniform. These hold the rows and the CPU’s starts and events, and as needed the kernels’ events and starts, the roll ticks, and the lists and their counts. Of the 8 storage WebGPU guarantees per stage, this leaves 1 to 6 for guards and hooks.
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
definitionA definition names a table's fields before any table exists, so shader code written over it works with every table made from it.Members and placeholders →
hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
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 →
memberA member is a function or accessor on what a factory returns that reads that instance's own resources, so a pipeline that uses it needs no fill.Members and placeholders →
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 →
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 →
slotA slot is a row's place in its buffers, which a new row can take once the first is removed.Row ids →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
threadA thread is one run of a kernel, and the GPU starts many at once, each with its own number.Slime mould →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.Words →
workgroupA workgroup is a block of threads that the GPU starts together, and a dispatch runs as many workgroups as cover the work.Slime mould →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
storage bufferA storage buffer is GPU memory that shaders read by index and kernels can write, which is where the kit keeps rows.Words →
bindingA binding is one buffer, texture or sampler in a bind group, which a shader reads by its place there.Words →
Draws a number in [0, 1) for row i at each step, for transitions with a chance or rate.Default randf.seed2(d.vec2f(d.f32(i), d.f32(tick))), then randf.sample().
step(pass) at each fixed step; it uploads the starts and sends made since the last with queue.writeBuffer, which flush() does sooner for a frame that reads them and records no step. With lists, dispatch work over listed after the step whose lists it reads.
3 to 5 buffers ·a uniform ·a pipeline ·liveLists with lists
The rows, the CPU's starts and events, the events kernels send when the definition has any, the starts kernels make with kernelStarts, the ticks that seed rolls, the step's length, the step and, with lists, the rows in those states.