Copying a light loop into each fragment shader duplicates work. Lights compiled in as constants need a new pipeline whenever one moves or is added. Store the sun, sky, fog and point lights as data in a lighting. Fill it into each pipeline and call shading.shade(material, point).
Four material presets under one sun
matte
glossy
metal
glow
Try Lower roughness to shrink and brighten highlights. Select lambert to remove highlights and give even metals diffuse lighting.
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,
import lighting
lighting.
constPointLight:table.TableDef<"PointLight",{
position:d.Vec3f;
range:d.F32;
color:d.Vec3f;
intensity:d.F32;
},{}>
PointLight,{
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.
Sets values for fields omitted by add. Without defaults, every field starts at zero. Default
none.
defaults:{...
import lighting
lighting.
constWHITE:{
readonly intensity:number;
readonly color:d.v3f;
readonly range:number;
}
Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since
table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
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(
constroot:TgpuRoot
root,{
settings:{
readonly sunDirection:[0.4,1,0.3];
readonly sunIntensity:2;
}&(Partial<d.InferInput<d.WgslStruct<{
sunDirection:d.Vec3f;
sunIntensity:d.F32;
sunColor:d.Vec3f;
skyIntensity:d.F32;
skyTop:d.Vec3f;
fogDensity:d.F32;
skyBottom:d.Vec3f;
fogFalloff:d.F32;
fogColor:d.Vec3f;
skyReflection:d.F32;
fogStart:d.F32;
}>>>|undefined)
Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.
Enables point lights from a table or a function. Default none.
points:{
table:table.Table<table.TableDef<"PointLight",{
position:d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
},{}>>&lighting.LightTable
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
Computes the final surface colour. It combines ambient light, shadowed sunlight, live point
lights and emission, then applies fog. Every channel stays at or below 65 504, the largest half
float. Create the pipeline from root.pipe(light.inject()) after injecting the kit camera.
shade(
constbrick:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
brick,
import shading
shading.
constpointAt:(position:d.v3f,normal:d.v3f)=>{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
Creates a point at position with surface normal normal, viewed from the kit camera.
Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps
back, and stops while the surface is paused. Destroying the animation keeps the loop alive.
Another animation on the same loop continues from its recorded time. A frame error, or a run
that returns false because the loop was destroyed, stops the animation.
@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before
@returns ― an animation you destroy to stop the frames
Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before
the next submit. Call once per frame before passes that read the table. A HistoryTable takes
the frame or its encoder and throws without one.
flush();// uploads lamps changed since the last frame
// Record passes here
}),
);
What shade addsshade sums ambient sky light, sunlight past its shadow, live point lights and emission, and applies fog last. The result is linear and can exceed 1 for bloom and tone mapping. Every channel stays at or below 65 504, the largest half float.
The camerashading.pointAt reads the kit’s cameras.current to find the direction toward the eye. Fill the camera into the pipeline too.
Cost A lighting without a shadow or point lights holds only its settings uniform. Shading a surface of your own, such as a raymarched field, then takes one small buffer.
Other light Light from a panorama or a sky goes through the ambient as an environment. Supply other baked or changing light through it too. See Light from textures.
Units Intensity 1 lights a white matte surface facing the light to about 1, with no exposure, so daylight and lamps share units. The kit’s lights leave out the 1/π factor. Divide intensities taken from a that keeps it by π.
A material uses glTF’s metallic-roughness model, with , roughness, metallic factor, emission and occlusion. Presets run on the CPU as well as the GPU.
Preset
matte(color)
Diffuse reflection for chalk, clay and cloth.
glossy(color, roughness)
A dielectric with a highlight, such as paint, plastic or wet stone.
metal(color, roughness)
Tints its reflections and has no diffuse colour.
glow(color, strength)
Gives off strength times color, and reflects almost nothing.
Make a material with a preset, then assign the fields you change:
const
constember:(heat:number)=>{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
ember=(
heat: number
heat:number)=>{
'use gpu';
const
constlit:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
lit=
import materials
materials.
constmatte:(color:d.v3f)=>{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
Creates a diffuse material, such as chalk, clay or cloth.
matte(
import d
d.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(0.3,0.1,0.05));
constlit:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
lit.
emission:d.v3f
Sets the emitted light in linear colour space. Shading adds it after lighting.
emission=
import d
d.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(1,0.4,0.1)*
heat: number
heat;
return
constlit:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
lit;
};
Struct literals Build a shading.Material and a shading.Point this way, never with a struct literal such as shading.Material({ color, roughness, … }). Both structs gain fields only at their end, and each added field does nothing at zero. A literal stops compiling when a field is added. Copy one you were given with shading.Material(m) or shading.Point(p) before assigning to it.
Screen colours Convert screen colours to linear light first with srgbToLinear from @typegpu/color.
Occlusionocclusion is the share of ambient light that reaches the surface, from 0 in a crevice to 1 in the open. hemisphere and an environment’s ambient apply it; presets set 1.
The point A shading.Point gives the shading position in world space, unit normal and view toward the eye, and uv and uv1 coordinates, the second from a mesh’s uvs1. shading.pointAt(position, normal) normalizes the normal and sets uv and uv1 to zero, and shading.Point() is all zeros. An ’s material function receives mesh UV coordinates.
Model textures Apply model textures with materials.textured, mappedNormal and masked. textured reads occlusion from the red channel of glTF’s occlusion texture. See mesh-pool textures.
Small highlights A smooth surface’s highlight can be smaller than a pixel and sparkle as it moves. materials.antialiased(material, normal) widens roughness where the normal turns within a pixel. Kit renderers apply it unless their specularAntialiasing option is false; call it in your own fragment shaders.
Try Change range to set where light falls to zero. Each ball carries a row of a lighting.MovingPointLight table, and one kernel moves balls and lights without CPU position writes.
points reads lights from a table you own or from a function. Without points, the shader has no point-light loop. A ’s fields start at zero, so give it lighting.WHITE as defaults: white, intensity 1 and range 10.
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,
import lighting
lighting.
constPointLight:table.TableDef<"PointLight",{
position:Vec3f;
range:F32;
color:Vec3f;
intensity:F32;
},{}>
PointLight,{
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.
Sets values for fields omitted by add. Without defaults, every field starts at zero. Default
none.
defaults:{...
import lighting
lighting.
constWHITE:{
readonly intensity:number;
readonly color:v3f;
readonly range:number;
}
Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since
table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).
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
Enables point lights from a table or a function. Default none.
points:{
table:table.Table<table.TableDef<"PointLight",{
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
},{}>>&lighting.LightTable
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
Call lamps.flush() each before shading. and destroy the table yourself.
A light falls off with the inverse square of distance, eased to zero at range.
shading.falloff and shading.beam run on the CPU as well as in shaders. Code outside shaders then gets the same numbers as the GPU for how much of a light reaches a point, before shadows.
A table of lighting.MovingPointLight keeps positions on the GPU for to write. The balls in the figure use this. A kernel writes them through lamps.gpu, and the CPU finds with lamps.slotOf(id).
This point-light table stores positions in a device field. Kernels write positions through
MovingPointLight.device.$[slot].position.
MovingPointLight,{
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.
Sets values for fields omitted by add. Without defaults, every field starts at zero. Default
none.
defaults:{...
import lighting
lighting.
constWHITE:{
readonly intensity:number;
readonly color:d.v3f;
readonly range:number;
}
Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since
table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).
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
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
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.
gpu.
span: TgpuGenericFn
()=> number
Returns the highest live slot plus one.
span())return;
const
constangle:number
angle=
consttime:TgpuUniform<d.F32>
time.
TgpuUniform<F32>.$: number
$+
import d
d.
functionf32(v?:number|boolean):number
export f32
A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)
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.
gpu.
device: TgpuAccessor<table.Rows<{
position:d.Vec3f;
}>>
Provides GPU-written rows with read-write access in compute pipelines and read-only access
in render pipelines.
device.
TgpuAccessor<Rows<{ position: Vec3f;}>>.$: {
position:d.v3f;
}[]
$[
id:d.v3u
id.
v3u.x: number
x].
position:d.v3f
position=
import d
d.
constvec3f:d.Vec3f
(x:number,y:number,z:number)=>d.v3f(+5 overloads)
vec3f(
import std
std.
functioncos(value:number):number(+1overload)
export cos
cos(
constangle:number
angle)*4,2,
import std
std.
functionsin(value:number):number(+1overload)
export sin
sin(
constangle:number
angle)*4);
});
const
constcircling:TgpuComputePipeline
circling=
constroot:TgpuRoot
root.
WithBinding.createComputePipeline<{
id:d.BuiltinGlobalInvocationId;
}>(descriptor:TgpuComputePipeline.Descriptor<{
id:d.BuiltinGlobalInvocationId;
}>):TgpuComputePipeline
createComputePipeline({
compute:TgpuComputeFn<{
id:d.BuiltinGlobalInvocationId;
}>
compute:
constcircle:TgpuComputeFn<{
id:d.BuiltinGlobalInvocationId;
}>
circle});
A position supplied to add or write overwrites the kernel’s. Colour and intensity updates leave it unchanged.
The CPU can’t read a moving light’s position back.
Click the sky to launch a shell, change the rate, or lower burst light. Each flash lights the castle and the smoke, and the lake reflects it; the readout counts live lights.
If another buffer already stores lights, supply points.light, a 'use gpu' function that returns a lighting.Light per slot, and count, the slots to visit. A range of 0 disables a slot. Use pipe to fill its dependencies. These flashes read their particles directly without a table or copy:
A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)
Can also be called to cast a value to an f32.
@exampleconst value = f32(); // 0
@exampleconst value = f32(1.23); // 1.23
@exampleconst value = f32(true); // 1
f32(0),320,
constflashes: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;
}>>
flashes.
System.alive: (i:number)=> boolean
Returns whether slot i is alive, in any shader.
alive(
slot: number
slot)),
color:d.v3f
Sets the light colour in linear colour space.
color:
constflash:{
position:d.v3f;
age:number;
velocity:d.v3f;
life:number;
color:d.v4f;
size:number;
seed:number;
}
flash.
color:d.v4f
Holds linear colour with opacity in w.
color.
xyz:d.v3f
xyz,
intensity: number
Multiplies color.
intensity:
import std
std.
functionexp(value:number):number(+1overload)
export exp
exp(-
constflash:{
position:d.v3f;
age:number;
velocity:d.v3f;
life:number;
color:d.v4f;
size:number;
seed:number;
}
flash.
age: number
Holds particle age in seconds.
age*3)*
constflash:{
position:d.v3f;
age:number;
velocity:d.v3f;
life:number;
color:d.v4f;
size:number;
seed:number;
}
flash.
size: number
Sets the particle width in world units.
size*
constflash:{
position:d.v3f;
age:number;
velocity:d.v3f;
life:number;
color:d.v4f;
size:number;
seed:number;
}
flash.
size: number
Sets the particle width in world units.
size,
});
};
const
constlight:lighting.Lighting
light=
import lighting
lighting.
functioncreate<{
readonly points:{
readonlylight:(slot:number)=>{
position:d.v3f;
range:number;
color:d.v3f;
intensity:number;
};
readonly count:number;
};
}>(root:TgpuRoot,options?:({
readonly points:{
readonlylight:(slot:number)=>{
position:d.v3f;
range:number;
color:d.v3f;
intensity:number;
};
readonly count:number;
};
}&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(
constroot:TgpuRoot
root,{
points:{
readonly light:(slot:number)=>{
position:d.v3f;
range: number;
color:d.v3f;
intensity: number;
};
readonly count: number;
}&lighting.LightPoints
Enables point lights from a table or a function. Default none.
points:{
light:((slot:number)=>{
position:d.v3f;
range: number;
color:d.v3f;
intensity: number;
})&((slot:number)=>lighting.Light)
Returns the light at a slot. Default none, lights from table or spot.
@gpu
light:
constlightOf:(slot:number)=>{
position:d.v3f;
range:number;
color:d.v3f;
intensity:number;
}
lightOf,
count: number
Sets how many slots, from 0, every lit point visits. Required unless candidates names them.
A light with range 0 lights nothing. Default none, the slots candidates names.
count:
constflashes: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;
}>>
flashes.
System.span: number
Gives the dispatch range for kernels over the pool. It includes every slot because any slot
can hold a particle and the CPU does not track live slots.
span},
});
To light particles in a kernel, such as the smoke beside the flashes, call shading.incoming(position) in a pipeline filled with light.inject(). It returns the light arriving at the position from every direction. That light is the sun past its shadow, each point light through attenuation, and the mean sky. Multiply a colour by it.
To light them by the point lights without the sun, fill shading.sunShadow with 0 on their pipeline alone. The fireworks’ smoke shows only in the bursts’ light this way, while the moon still lights the lake:
const
constsunless:shading.SunShadowHook
sunless:
import shading
shading.
typeSunShadowHook=(point:shading.Point)=>number
Returns the share of sunlight that reaches a point, as sunShadowed does. A value of 0
means full shadow and 1 means full light. Values above 1 can model focused light.
SunShadowHook=()=>{
'use gpu';
return
import d
d.
functionf32(v?:number|boolean):number
export f32
A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)
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.
Returns the light arriving at position from every direction, for a particle or a volume lit
the same from all sides: the sun through sunShadow, each point light through attenuation,
and the mean of the sky and ground colours. Multiply a colour by it. Hooks receive a point with
a zero normal and view, so a lift along the normal does nothing. It runs in any stage, kernels
included, of a pipeline filled with light.inject(). Fill sunShadow with 0 on that pipeline to
leave the sun out.
Every lit pixel visits each light slot, up to a table’s highest live slot or the count slots of a function. Out-of-range lights still cost loads and a distance test, so size tables to the lights you use. If many lights each cover a small area, supply points.candidates to visit only slots that may reach the point.
A neighbour grid with sight at least the longest light range finds nearby lamps in 27 cells:
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,
import lighting
lighting.
constPointLight:table.TableDef<"PointLight",{
position:d.Vec3f;
range:d.F32;
color:d.Vec3f;
intensity:d.F32;
},{}>
PointLight,{
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.
Sets values for fields omitted by add. Without defaults, every field starts at zero. Default
none.
defaults:{...
import lighting
lighting.
constWHITE:{
readonly intensity:number;
readonly color:d.v3f;
readonly range:number;
}
Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since
table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).
Creates a grid that sorts items by cell so kernels can find nearby items. Walks visit the home
cell first and choose directions at random, for boids, crowds or collisions. Throws unless
sight is above 0, and when the capacity, 64 to a workgroup, needs more than the device's
maxComputeWorkgroupsPerDimension workgroups.
@injects ― member walk, around, range, neighbour, slot, slotAt, neighbourAt,
count, holds and block, which read its own buffers in any pipeline
@binds ― 1 uniform: walk or around, the box
@binds ― 2 storage: range and neighbour or neighbourAt, each cell's sorted range and each item's copy
@binds ― 1 storage: slot or slotAt, the sorted slots
@binds ― 1 storage: count, the sorted count
@binds ― 3 storage: holds and block, which blocks hold items, the sort count and their list
@owns ― buffers, a uniform, pipelines, bind groups, a sorter with radix: each cell's sorted
range, the blocks holding items, with item each item's copy in sorted order, the dispatches,
the box, the binning's resources
@records ― sort in a compute pass each step, before the kernels that walk
@param ― options.sight the cell side length. A walk finds every item within this distance
@param ― options.alive tests whether a slot holds an item. It, position and itemOf need fills for
the resources they read. Spread a table's rows.live() into the options to include its
live test, capacity and span
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.
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
Enables point lights from a table or a function. Default none.
points:{
table:table.Table<table.TableDef<"PointLight",{
position:d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
},{}>>&lighting.LightTable
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
Limits the loop to lights that may reach each shaded point, as grid.Candidates name them.
Default every live slot.
candidates:
constcells:grid.Grid<never>
cells.
Grid<never>.candidates(): grid.Candidates
Returns nearby ranges, for a lighting's
points.candidates when the items are lights and sight covers every light range.
candidates()},
});
Each frame Call lamps.flush() and then cells.sort(pass) in a compute pass before shading.
The candidatescells.candidates() returns nine ranges covering the surrounding cells. Its range and slot add two to each shading stage.
Beyond sight Lights beyond sight can be missed.
Repeated slots Repeating a slot in candidates adds its light twice.
Your own candidates Custom candidates are a grid.Candidates: ranges, a range(position, r) function returning first and count, and slot(index) to map indices to light slots. They also work with a light function. For a single list, return one range with lighting.Span({ first: 0, count }).
A spot light is a point light with a cone. A table of lighting.SpotLight gives every light an aim and a cone, so points and spots share one table, one loop and one candidate list:
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,
import lighting
lighting.
constSpotLight:table.TableDef<"SpotLight",{
aim:Vec3f;
cone:Vec2f;
position:Vec3f;
range:F32;
color:Vec3f;
intensity:F32;
},{}>
SpotLight,{
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 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
Enables point lights from a table or a function. Default none.
points:{
table:table.Table<table.TableDef<"SpotLight",{
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
},{}>>&lighting.LightTable
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
Holds the cone's scale and offset from lighting.cone(inner, outer). The default [0, 1]
lights every direction.
cone:
import lighting
lighting.
constcone:(inner:number,outer:number)=>v2f
Returns a cone's scale and offset for a spot light's cone, from its inner and outer
half-angles in radians. Light falls from full at inner to none at outer, as glTF's spot
lights do. It runs on the CPU and in shaders.
cone(0.18,0.24),// inner and outer half-angles in radians
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
The cone Light is full inside the inner half-angle and falls to none at the outer one, as in glTF. lighting.cone(inner, outer) stores glTF’s scale and offset, and runs on the CPU and in shaders.
The white spotlighting.WHITE_SPOT aims straight down with the cone [0, 1], which lights every direction.
Cost The loop reads a light’s aim and cone only once its range test passes.
Moving spots In a table of lighting.MovingSpotLight, only the position is in the device part, for kernels to write.
A light functionpoints.spot takes a function that returns a lighting.Spot, a Light with aim and cone, beside count or candidates.
The beamshading.beam(toLight, aim, cone) gives the share of a spot light along toLight, a unit direction from the point towards the light.
light.settings is a lighting.Settings uniform containing sun, sky and fog values. patch uploads supplied fields. A moving sun can update once per frame, and the shadow follows a new sunDirection at its next record:
const
constdirection:[number,number,number]
direction:[number,number,number]=[
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.cos(x: number): number
Returns the cosine of a number.
@param ― x A numeric expression that contains an angle measured in radians.
cos(
constt:0.6
t),
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.sin(x: number): number
Returns the sine of a number.
@param ― x A numeric expression that contains an angle measured in radians.
sin(
constt:0.6
t),0.3];
constlight:lighting.LightingOf<{
readonly shadow:{};
}>
light.
Lighting.settings: TgpuUniform<WgslStruct<{
sunDirection:Vec3f;
sunIntensity:F32;
sunColor:Vec3f;
skyIntensity:F32;
skyTop:Vec3f;
fogDensity:F32;
skyBottom:Vec3f;
fogFalloff:F32;
fogColor:Vec3f;
skyReflection:F32;
fogStart:F32;
}>>
Holds the sun, sky and fog values from defaults and the settings option. Use patch to
upload only the fields you supply. The shadow's next record follows a sunDirection written
here.
shade calls five functions, which the shading options replace:
Slot
Called
Type
Its arguments
Default
shading.reflect
For the sun and each point light
shading.ReflectHook
material, point, direction, radiance
shading.pbr
shading.ambient
Once, for the light from elsewhere
shading.AmbientHook
material, point
shading.hemisphere
shading.fog
Last, for the air before the eye
shading.FogHook
point
shading.heightFog
shading.sunShadow
Once, for how much sun reaches
shading.SunShadowHook
point
shading.sunShadowed
shading.attenuation
For each point light in range
shading.AttenuationHook
point, toLight, distance, range, slot
shading.reaching
reflect and ambient return linear d.v3f colours. direction is a unit vector toward the light. radiance is colour times intensity and attenuation, with the shadow also applied to the sun.
fog returns a shading.Air: added, the light the air between the eye and the point adds, and through, the share of the point’s light it lets through, per channel. shade returns color * through + added. Water that swallows red faster than blue lets less red through.
sunShadow returns 0 for shadow and 1 for full sunlight. Values above 1 can represent focused light. See your own sun shadow.
attenuation returns the share of a light’s intensity reaching the point. The loop reads the light’s colour and calls reflect only where it is above 0. reaching multiplies shading.falloff(distance, range), shading.beamOf(toLight, slot) and, where that is above 0, shading.lampShadowed(point, toLight, distance, slot). Use slot to read data of your own, such as a flicker per light or a cookie texture.
Returns how much of the view fog hides between the camera and the point, from 0 to 1, from the
lighting's fogDensity, fogFalloff and fogStart. Density falls by a factor of e every 1 / fogFalloff world units above y = 0, and the fog begins fogStart world units from the eye.
A custom fog adds a colour of its own by it and lets 1 - haze through.
haze(
point:{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
point);
return
import shading
shading.
constAir:d.WgslStruct
(props?:{
added:d.v3f;
through: d.v3f;
}|undefined)=>{
added:d.v3f;
through:d.v3f;
}
This schema holds what the air between the eye and a point does to the point's light: added
is the light the air adds, and through the share of the point's light it lets through, per
channel. A colour c seen through it is c * through + added.
Air({
added:d.v3f
added:
constair:d.v3f
air*
consthidden:number
hidden,
through:d.v3f
through:
import d
d.
constvec3f:d.Vec3f
(xyz:number)=>d.v3f(+5 overloads)
vec3f(1-
consthidden:number
hidden)});
};
const
constlight:lighting.Lighting
light=
import lighting
lighting.
functioncreate<{
readonly shading:{
readonly reflect:shading.ReflectHook;
readonly fog:shading.FogHook;
};
readonly settings:{
readonly fogDensity:0.02;
readonly fogFalloff:0.2;
};
}>(root:TgpuRoot,options?:({
readonly shading:{
readonly reflect:shading.ReflectHook;
readonly fog:shading.FogHook;
};
readonly settings:{
readonly fogDensity:0.02;
readonly fogFalloff:0.2;
};
}&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(
constroot:TgpuRoot
root,{
shading:{
readonly reflect:shading.ReflectHook;
readonly fog:shading.FogHook;
}&lighting.Shading
Sets the functions that shading.shade calls. Default pbr, hemisphere, heightFog,
sunShadowed and reaching.
shading:{
reflect:shading.ReflectHook
Computes how a surface reflects the sun and each point light. Default shading.pbr.
reflect:
consttoon:shading.ReflectHook
toon,
fog:shading.FogHook
Gives the light the air adds between the eye and a point, and the share of the point's light
it lets through. Default shading.heightFog.
fog:
consthorizon:shading.FogHook
horizon},
settings:{
readonly fogDensity:0.02;
readonly fogFalloff:0.2;
}&(Partial<d.InferInput<d.WgslStruct<{
sunDirection:d.Vec3f;
sunIntensity:d.F32;
sunColor:d.Vec3f;
skyIntensity:d.F32;
skyTop:d.Vec3f;
fogDensity:d.F32;
skyBottom:d.Vec3f;
fogFalloff:d.F32;
fogColor:d.Vec3f;
skyReflection:d.F32;
fogStart:d.F32;
}>>>|undefined)
Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.
settings:{
fogDensity:0.02
fogDensity:0.02,
fogFalloff:0.2
fogFalloff:0.2},
});
Hazeshading.haze(point) is how much the lighting’s height fog hides the point, from 0 to 1. heightFog adds fogColor by it and lets 1 - haze through; add a colour of your own, as above.
Settingsshading.settings() reads sun, sky and fog values from light.settings. Changing a value needs no new pipeline.
Matte shadingshading.lambert omits highlights for cheaper shading on phones and flat-shaded art. It tints all reflection with the surface colour, including metals.
Ambient lightshading.surrounded(material, point, irradiance, reflection) combines diffuse and reflected light for an ambient hook of your own. It applies the material’s occlusion to the reflected light only. See lightmaps.
Reflection directionshading.reflectionOf(point, roughness) returns the direction to sample reflected light along.
Ambient termsshading.reflectance and shading.specularOcclusion are the terms surrounded uses.
Parts of shadeshading.unfogged, direct, sun and towardsSun are the parts of shade, for shaders that combine them differently.
Every pipeline built from light.inject() binds the resources its hooks read. A hook passed to lighting.create reaches every lit renderer. A fog that reads a ground paint texture and its uniforms then adds those to every figure and prop pipeline too. Each stage has 8 storage and 12 uniform buffers to share, so give a hook that only some renderers need to those renderers alone:
Renderer pipe runs after the lighting, so replaces the lighting’s. Fill your own pipelines the same way, root.pipe(light.inject()).with(shading.reflect, shading.lambert). Pipelines lists what each pipeline binds.
Glass that hides only a tenth of its background can still show full-strength highlights and sky reflections. Use shading.shadeClear(material, point, opacity) for this behavior. It returns premultiplied colour for pipelines.blend.over:
const
constpane:(world:d.v3f,normal:d.v3f)=>d.v4f
pane=(
world:d.v3f
world:
import d
d.
export v3f
Interface representing its WGSL vector type counterpart: vec3f or vec3.
A vector with 3 elements of type f32
v3f,
normal:d.v3f
normal:
import d
d.
export v3f
Interface representing its WGSL vector type counterpart: vec3f or vec3.
A vector with 3 elements of type f32
v3f)=>{
'use gpu';
const
constglass:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
glass=
import materials
materials.
constglossy:(color:d.v3f,roughness:number)=>{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
Creates a dielectric with specular highlights, such as paint, plastic or wet stone.
Shades a clear surface such as glass or clear plastic. The result is premultiplied for
pipelines.blend.over. opacity scales diffuse light, emission and the light the fog adds.
Reflections, including highlights and sky light, contribute at full strength. A metal has only
reflected light, so opacity scales only its fog. Every channel stays at or below 65 504.
shadeClear(
constglass:{
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
glass,
import shading
shading.
constpointAt:(position:d.v3f,normal:d.v3f)=>{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
Creates a point at position with surface normal normal, viewed from the kit camera.
pointAt(
world:d.v3f
world,
normal:d.v3f
normal),0.1);
};
opacity scales the diffuse light, the emission and the light the fog adds; the reflected light is added whole. w is opacity.
A metal reflects all it shows, so opacity only fades its fog.
An instances renderer with blend: 'clear' shades through it.
One shadow map, read with one, four or nine comparisons
filter
size
Try Set 256 texels and compare one, four or nine shadow comparisons. The map spans 9 units around a 0.3-unit-wide pillar; extra comparisons soften its stepped shadow.
Without shadows, a floating block can appear to rest on the floor. A lighting with a shadow group creates light.shadow, which records depth from the sun. Add each caster to it as you add to the scene, and record it each frame before the passes that shade:
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(
constroot:TgpuRoot
root,{
settings:{
readonly sunDirection:[-0.6,1,-0.7];
}&(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.
settings:{
sunDirection:[-0.6,1,-0.7]
sunDirection:[-0.6,1,-0.7]},
shadow:{
readonly extent:9;
}&lighting.FixedShadowOptions
Enables and configures the shadow from the sun. Default none.
shadow:{
extent:9
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.
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
};
readonly depth:{
readonly format:"depth24plus";
};
}>>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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 settings:{
readonly sunDirection:[-0.6,1, -0.7];
};
readonly shadow:{
readonly extent:9;
};
}>
light.
Lighting.inject(): Inject
Fills the shading hooks and resources for pipelines created from the configuration you pipe
it into.
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.
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.
Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps
back, and stops while the surface is paused. Destroying the animation keeps the loop alive.
Another animation on the same loop continues from its recorded time. A frame error, or a run
that returns false because the loop was destroyed, stops the animation.
@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before
@returns ― an animation you destroy to stop the frames
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:frames.Frame
frame,
constdrawn:passes.Drawn
drawn);
}),
);
Casterslight.shadow.add(renderer) builds depth pipelines with bias against self-shadowing. cast.destroy() removes the caster and frees its per-view resources.
Compilingawait light.initAsync() while loading compiles every caster added to its shadows. Include the lighting in the list for pipelines.compile to compile it with the scene’s other pipelines.
Coverage The map covers a square extent world units wide, centred on center. Outside it, surfaces are lit. Wider coverage spreads each over more ground: Blockfall covers its well with 2048 texels across 16 units, about 1/128 of a block per texel.
Direction The shadow follows sunDirection. A direction written to light.settings turns it at its next record. Call aim(direction) to cast from elsewhere.
The typelight.shadow exists in the type only when the options give a shadow. A function of your own that takes such a lighting types it lighting.Shadowed, or lighting.PointShadowed for lamp shadows.
Timing Time the pass with a profiler as record(frame, casters, { timestampWrites: shadow.writes() }). A frame that draws no cascade writes the timer from an empty compute pass.
Memory A layer of the map takes size² × 2 bytes in depth16unorm and size² × 4 in the other formats.
Click a horse to ride beside it. Its legs cast sharp shadows from the nearest cascade while the trees on the far slopes cast theirs from the last.
One square sharp enough for a horse’s legs covers a few dozen metres. Give the shadow an eye and it splits the view into cascades, each a layer of one map. The nearest covers the first metres in front of the camera, and each later one covers more ground with the same texels. record fits them to the camera each frame:
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(
constroot:TgpuRoot
root,{
settings:{
readonly sunDirection:[0.6,0.35,0.3];
}&(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.
settings:{
sunDirection:[0.6,0.35,0.3]
sunDirection:[0.6,0.35,0.3]},
shadow:{
readonly eye:cameras.OrbitCamera;
readonly cascades:3;
readonly far:120;
}&lighting.FittedShadowOptions
Enables and configures the shadow from the sun. Default none.
shadow:{
eye:cameras.OrbitCamera&cameras.CpuView
Fits the map to this camera's view, in cascades layers that reach far from the eye. Each
record fits them again, so the map follows the camera without follow. Default none, a
fixed map.
eye:
constview:cameras.OrbitCamera
view,
cascades:3
Splits the view into 1 to 4 cascades, each a layer of the map drawn in a pass of its own.
Nearer cascades cover less ground, so their shadows are sharper. Needs an eye. Default 1.
cascades:3,
far:120
Sets how far from the eye the cascades reach, in world units. Change it with setFar. Needs an
eye. Default 50.
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
};
readonly depth:{
readonly format:"depth24plus";
};
}>>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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 settings:{
readonly sunDirection:[0.6,0.35,0.3];
};
readonly shadow:{
readonly eye:cameras.OrbitCamera;
readonly cascades:3;
readonly far:120;
};
}>
light.
Lighting.inject(): Inject
Fills the shading hooks and resources for pipelines created from the configuration you pipe
it into.
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.
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.
Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps
back, and stops while the surface is paused. Destroying the animation keeps the loop alive.
Another animation on the same loop continues from its recorded time. A frame error, or a run
that returns false because the loop was destroyed, stops the animation.
@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before
@returns ― an animation you destroy to stop the frames
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:frames.Frame
frame,
constdrawn:passes.Drawn
drawn);
}),
);
eye takes a camera with a CPU view: cameras.orbit, cameras.flat or cameras.custom. Update it before record.
The split after cascade k lies at far × (k / cascades)², 11% and 44% of far for three. splits: [0.08, 0.3] places them as fractions of far instead.
record fits a sphere around each slice of the view and snaps its centre to whole texels. The sphere keeps its size as the camera turns, so shadow edges hold still.
reach is how far each cascade reaches towards the sun beyond its slice. A caster farther towards the sun casts nothing.
cascades, far and splits need an eye, and extent and center work only without one. Type checking refuses the other combinations, and create throws for them. cascades: 1 fits one map to the view.
A view cut into shadow cascades, seen from a sun overhead
cascades
splits
Try Drag the point away from the camera. It takes the first square that holds it, so its texels grow at each edge it leaves. Every square is one layer of the map, ruled here 16 cells across.
Casters draw once per cascade through the pipelines a single map builds. An instances renderer with cull: true culls every cascade in one pair of . Shading picks the first cascade whose square holds the point and switches cascades without a blend, unless a hook of your own blends them. A finished look for model scenes sizes two cascades for a scene of glTF models.
record clears and draws every cascade each frame. Casters that hold still under a still sun draw the same depth again. Pass redraw to choose the cascades that draw this frame. The others keep the layer they drew last:
// Set when a caster moves, from your own game state
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.
Chooses which cascades draw their layer this frame, by index from the nearest. A cascade it
skips keeps the layer it drew last, so still casters under a still sun can skip. A cascade
still draws on the first record and when its place changes, as a fitted shadow's does when
the eye moves, after aim, follow, setExtent, setFar and resize, and after a frame
with enabled false, so () => false draws casters that never move once. A layer counts as
drawn once its frame submits, so a cascade recorded into an encoder alone draws on every
record until resize. Default every cascade.
@cpu
redraw:()=>
let stirred:boolean
stirred});
let stirred:boolean
stirred=false;
});
With a culling renderer, give redraw to prepare before renderer.cull instead, as for lamps, so culling skips the cascades that keep their layer.
A cascade draws the first time the shadow is recorded and whenever its placement changes, even if redraw would skip it. Moving the fitted eye, turning the sun or calling aim, follow, setExtent or setFar can change that placement. All cascades draw again after resize replaces the map and when the shadow comes back on. A skipped cascade shows casters where they stood when it last drew. A layer counts as drawn once its frame submits. If a frame throws before its submit, the layer draws again. A cascade recorded into an encoder alone draws on every record until resize replaces the map, since that encoder may submit after any later frame.
Casters that never move, such as terrain or a reef, need no state of their own. A redraw that always answers false draws the shadow once and again only when its place changes:
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.
record places the cascades with the shadow’s fit, a function on the CPU. The default, lighting.fitSlices, is the sphere around each slice described above. A fit of your own writes a cube for each cascade in the sun’s light space, whose axes are right, up and sun. It returns whether it placed them. Each cascade also reaches reach beyond its cube towards the sun.
The fit below widens each cube and snaps it to a coarse grid. Each cube then holds still while the view moves inside it. With redraw: () => false, a cascade then draws only when the view crosses a line of its grid:
Places each cascade, writing places[k] for cascade k, and returns whether it placed them.
When it returns false, as when the eye has no view yet, every point is sunlit until it places
them. lighting.fitSlices is the default.
Fits a sphere around each cascade's slice of the eye's view and snaps its centre to whole
texels across the sun's rays. The sphere keeps its size as the eye turns, so shadow edges hold
still. This is a fitted shadow's default fit; a fit of your own can call it and move what it
placed.
@param ― input the eye, the sun's light space and the shadow's settings
@param ― places the places it writes, one per cascade
@returns ― whether it placed them, false while the eye has no view
fitSlices(
input:lighting.CascadeFitInput
input,
places:lighting.CascadePlace[]
places))returnfalse;
for(const
constplace:lighting.CascadePlace
placeof
places:lighting.CascadePlace[]
places){
constplace:lighting.CascadePlace
place.
CascadePlace.radius: number
Sets the distance from the cube's centre to each face, above 0, in world units.
radius*=1.3;
// Whole texels, a tenth of the layer apart, so the slice stays inside the cube
const
conststep:number
step=((
constplace:lighting.CascadePlace
place.
CascadePlace.radius: number
Sets the distance from the cube's centre to each face, above 0, in world units.
radius*2)/
input:lighting.CascadeFitInput
input.
CascadeFitInput.size: number
Gives the width and height of each layer of the map in texels.
size)*
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.floor(x: number): number
Returns the greatest integer less than or equal to its numeric argument.
@param ― x A numeric expression.
floor(
input:lighting.CascadeFitInput
input.
CascadeFitInput.size: number
Gives the width and height of each layer of the map in texels.
size/10);
constplace:lighting.CascadePlace
place.
CascadePlace.x: number
Sets the cube's centre along right, in world units.
x=
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.round(x: number): number
Returns a supplied numeric expression rounded to the nearest integer.
@param ― x The value to be rounded to the nearest integer.
round(
constplace:lighting.CascadePlace
place.
CascadePlace.x: number
Sets the cube's centre along right, in world units.
x/
conststep:number
step)*
conststep:number
step;
constplace:lighting.CascadePlace
place.
CascadePlace.y: number
Sets the cube's centre along up, in world units.
y=
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.round(x: number): number
Returns a supplied numeric expression rounded to the nearest integer.
@param ― x The value to be rounded to the nearest integer.
round(
constplace:lighting.CascadePlace
place.
CascadePlace.y: number
Sets the cube's centre along up, in world units.
y/
conststep:number
step)*
conststep:number
step;
constplace:lighting.CascadePlace
place.
CascadePlace.z: number
Sets the cube's centre along sun, in world units.
z=
var Math:Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.
Math.round(x: number): number
Returns a supplied numeric expression rounded to the nearest integer.
@param ― x The value to be rounded to the nearest integer.
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(
constroot:TgpuRoot
root,{
shadow:{
readonly eye:cameras.OrbitCamera;
readonly cascades:3;
readonly fit:lighting.CascadeFit;
}&lighting.FittedShadowOptions
Enables and configures the shadow from the sun. Default none.
shadow:{
eye:cameras.OrbitCamera&cameras.CpuView
Fits the map to this camera's view, in cascades layers that reach far from the eye. Each
record fits them again, so the map follows the camera without follow. Default none, a
fixed map.
eye:
constview:cameras.OrbitCamera
view,
cascades:3
Splits the view into 1 to 4 cascades, each a layer of the map drawn in a pass of its own.
Nearer cascades cover less ground, so their shadows are sharper. Needs an eye. Default 1.
cascades:3,
fit:lighting.CascadeFit
Places the cascades in the sun's light space whenever the shadow fits them: on each record,
after aim and after setFar. Needs an eye. Default lighting.fitSlices, a sphere around
each slice of the view, snapped to whole texels.
@cpu
fit:
constheld:lighting.CascadeFit
held},
});
The fit runs on each record, after aim and after setFar, and writes into the same places each time.
Snap each centre across the sun to whole texels of its layer, as fitSlices does, or shadow edges crawl as the cascade moves.
A fit that returns false lights every point, as a shadow does before its eye has a view.
Add a custom caster as a drawing to light.shadow. Supply a Vertex with a clip-space position, an at function producing it and a draw function. The shadow fills the kit’s cameras.current with the sun’s view, so scene vertex functions cast without changes:
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.
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.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
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.
record(
constframe:Frame
frame,
constcast:Drawn
cast);// each frame
Depth only Depth-only drawings need neither pixelOf nor color, and build no fragment stage. With pixelOf and depthOf, a drawing can supply another point’s depth, as impostors do.
Cutouts A drawing with cutout, such as a sprite whose texture is clear around its figure, casts the figure’s shadow. The shadow pass runs cutout alone, so the same drawing goes into the shadow map even when its pixelOf reads the lighting.
Masked instances Instances cut out by masked meshes or by their kind’s coverage cast through it the same way, at their own depth.
Indices and fills Supply an index buffer as indices for drawIndexed and fill shader dependencies with inject().
shade takes the share of sunlight at a point from the sunShadow hook. The default, shading.sunShadowed, moves the point lift texels along its normal and compares it with the map. It makes 1, 4 or 9 comparisons, as filter sets, and returns their mean, from 0 in shadow to 1 in light. A hook of your own can change that share. The fishtank multiplies shading.sunShadowed(point) by its caustics. The hook below blends each cascade into the next near the edge of its square. At the last cascade’s edge it blends the shadow into sunlight, so the shadow fades out instead of ending at a line:
const
constblended:shading.SunShadowHook
blended:
import shading
shading.
typeSunShadowHook=(point:shading.Point)=>number
Returns the share of sunlight that reaches a point, as sunShadowed does. A value of 0
means full shadow and 1 means full light. Values above 1 can model focused light.
SunShadowHook=(
point:{
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point)=>{
'use gpu';
const
constat:{
index:number;
edge:number;
}
at=
import shading
shading.
constcascadeOf:(point:shading.Point)=>{
index:number;
edge:number;
}
Returns the first cascade of the sun's shadow whose square holds the point, inset by the
filter's half width and the shadow's lift, and how near its edge the point lies. Index -1
means no cascade holds it, or the shadow is off.
Returns the share of sunlight that passes the filter in cascade index of the sun's shadow. A
grid of depth comparisons gives 0 in full shadow and 1 in full light. For a point outside the
cascade's square or depth, an index without a cascade, or while the shadow is off, this returns
1.
cascadeShadowed(
point:{
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point,
constat:{
index:number;
edge:number;
}
at.
index: number
index);
if(
constat:{
index:number;
edge:number;
}
at.
edge: number
Rises from 0 to 1 over the outer 10% of the cascade's square.
Returns the share of sunlight that passes the filter in cascade index of the sun's shadow. A
grid of depth comparisons gives 0 in full shadow and 1 in full light. For a point outside the
cascade's square or depth, an index without a cascade, or while the shadow is off, this returns
1.
cascadeShadowed(
point:{
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point,
constat:{
index:number;
edge:number;
}
at.
index: number
index+1),
constat:{
index:number;
edge:number;
}
at.
edge: number
Rises from 0 to 1 over the outer 10% of the cascade's square.
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(
constroot:TgpuRoot
root,{
shadow:{
readonly eye:cameras.OrbitCamera;
readonly cascades:3;
}&lighting.FittedShadowOptions
Enables and configures the shadow from the sun. Default none.
shadow:{
eye:cameras.OrbitCamera&cameras.CpuView
Fits the map to this camera's view, in cascades layers that reach far from the eye. Each
record fits them again, so the map follows the camera without follow. Default none, a
fixed map.
eye:
constview:cameras.OrbitCamera
view,
cascades:3
Splits the view into 1 to 4 cascades, each a layer of the map drawn in a pass of its own.
Nearer cascades cover less ground, so their shadows are sharper. Needs an eye. Default 1.
cascades:3},
shading:{
readonly sunShadow:shading.SunShadowHook;
}&lighting.Shading
Sets the functions that shading.shade calls. Default pbr, hemisphere, heightFog,
sunShadowed and reaching.
shading:{
sunShadow:shading.SunShadowHook
Returns the share of sunlight that reaches a point. A value of 0 means full shadow and 1
means full light. Values above 1 can model focused light, such as light through moving
water. Default shading.sunShadowed, which reads the shadow map.
sunShadow:
constblended:shading.SunShadowHook
blended},
});
cascadeOf(point) returns the first cascade that holds the point within its depth range and within its square inset by the filter’s half width and lift. Its edge rises from 0 to 1 over the outer 10% of the inset square.
cascadeShadowed(point, index) filters cascade index. It returns 1 for a point outside that cascade and for an index outside the cascades, so the last cascade blends into sunlight.
shading.sunShare(point) returns what the hook gives, for shaders that don’t call shade. The domino run’s dust brightens in sunlight with it.
The shadow group’s enabled callback turns the shadow on and off each frame, as for other pass descriptions. A quality menu can change its value without a second 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(
constroot:TgpuRoot
root,{
shadow:{
readonly enabled:()=> boolean;
}&(lighting.ShadowOptions|undefined)
Enables and configures the shadow from the sun. Default none.
shadow:{
enabled:()=> boolean
enabled:()=>
constmenu:{
shadows:boolean;
}
menu.
shadows: boolean
shadows}});
While it is off, record records no pass, culling lists stay empty and shading.sunShadowed returns 1 without sampling the map.
The map and pipelines stay allocated, so shadows draw on the first frame after it turns on.
Give light.shadow.part to the lit as shared: { shadow: light.shadow.part }, which puts it in a shared layout. Create that description before any other pipeline that shades.
When a pass of your own also reads the map, share it once with bindings.share and give the result to the description.
The next frame then makes one and no pipelines. The shadow’s own passes don’t read the map, so they need no group.
Without a shared layout, shading pipelines bind the map as fixed resources, and resize throws before it changes anything.
Turn shadows off to let the lamps shine through the table onto the cobbles beneath it. The seller's lamp throws the potions' shadows along the table. Raise the wind to swing the lantern under the string of lights; its shadows swing with it.
Give lighting.create a pointShadow.define to get light.pointShadow. It gives a shadow each to up to count lights of the lighting’s table. The lighting makes, compiles and destroys it with its own resources. A lighting without one leaves the point-shadow code out of your bundle. cast picks the lights:
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,
import lighting
lighting.
constSpotLight:table.TableDef<"SpotLight",{
aim:Vec3f;
cone:Vec2f;
position:Vec3f;
range:F32;
color:Vec3f;
intensity:F32;
},{}>
SpotLight,{
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 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
Enables point lights from a table or a function. Default none.
points:{
table:table.Table<table.TableDef<"SpotLight",{
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
},{}>>&lighting.LightTable
Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or
MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE.
Flush and destroy it yourself. Default none, lights from light or spot.
Gives up to count point or spot lights a shadow each, as pointShadow.define describes
them, which light.pointShadow.cast assigns. Needs points.table of lights the CPU places,
not a moving one. Default none.
Describes point and spot shadows for lighting.create, which gives up to count lights of its
points.table a shadow each as light.pointShadow. The lighting checks count and size when
it makes them.
@param ― options the shadows' count, layer size, filter and depth format
@returns ― a definition to give lighting.create as pointShadow
define({
PointShadowOptions.count?: number |undefined
Sets how many lights can cast a shadow at once, each with six layers of the map. Shading
compares each in-range light with every shadow. Default 1.
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is
full, or when a value fails to write, which leaves the slot free.
Holds the cone's scale and offset from lighting.cone(inner, outer). The default [0, 1]
lights every direction.
cone:
import lighting
lighting.
constcone:(inner:number,outer:number)=>v2f
Returns a cone's scale and offset for a spot light's cone, from its inner and outer
half-angles in radians. Light falls from full at inner to none at outer, as glTF's spot
lights do. It runs on the CPU and in shaders.
cone(0.3,0.45),
intensity?: number |undefined
Multiplies color.
intensity:30,
range?: number |undefined
Sets the distance in world units where light intensity reaches zero.
Gives a shadow to each light in lights, ids in the lighting's table, at most count. A light
that already casts keeps its shadow, a light left out frees its own, and a new one takes a free
shadow, so casting the same lights again writes nothing. A spot whose outer half-angle is at
most 60° draws one layer along its aim, and a wider spot or a point light draws six faces. A
light of no range or with a cone of no width draws nothing and shadows nothing. Throws for
more lights than 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
create(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
};
readonly depth:{
readonly format:"depth24plus";
};
}>>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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().
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.
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.
Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps
back, and stops while the surface is paused. Destroying the animation keeps the loop alive.
Another animation on the same loop continues from its recorded time. A frame error, or a run
that returns false because the loop was destroyed, stops the animation.
@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before
@returns ― an animation you destroy to stop the frames
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.
Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before
the next submit. Call once per frame before passes that read the table. A HistoryTable takes
the frame or its encoder and throws without one.
Places each shadow at its light from the table's CPU rows, then clears and draws the layers of
each shadowed light that redraw picks with the casters built by add, a depth pass per
layer. Call this while recording each frame, before drawing shaded surfaces. A removed light
frees its shadow. A frame that draws no layer 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:frames.Frame
frame,
constdrawn:passes.Drawn
drawn);
}),
);
Layers Each shadow holds six layers of one texture_depth_2d_array.
Castingcast(lights) gives a shadow to each light in the list, at most count. A light that already casts keeps its shadow, a light left out frees its own, and a new one takes a free shadow. Casting the same lights again writes nothing, so you can cast from the lamps nearest the eye every frame.
Views A spot whose outer half-angle is at most 60° draws one layer, a perspective view along its aim. A wider spot or a point light draws six faces. Each face covers 90° plus the filter’s half width, so the filter at a face’s edge stays inside that face.
Placementrecord places each shadow at its light’s in the table, so a light moved on the CPU needs no other call. A removed light frees its shadow.
Near and far Near is 2% of the light’s range and far is range.
Shared optionsfilter, format, bias, enabled and resize work as the sun’s do. lift moves the shaded point along its normal by that many texels at its distance from the light. Give the lit description shared: { pointShadow: light.pointShadow.part } to resize without new pipelines.
Memory A layer takes size² × 2 bytes in depth16unorm and size² × 4 in the other formats.
The default attenuation, shading.reaching, multiplies in shading.lampShadowed(point, toLight, distance, slot), which a hook of your own can call too. For each light in range, shading compares its slot with each of the count shadows. A shadowed light picks a face from the direction to the point, takes one matrix product and makes the filter’s comparisons.
Each layer is a depth pass that draws every caster, so seven layers cost seven passes each frame. A lamp that holds still over casters that hold still draws the same layers again. Pass redraw to choose the lights that draw this frame. The others keep the layers they drew last:
// Lamps with a caster that moved within their range this frame, from your own game state
Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before
the next submit. Call once per frame before passes that read the table. A HistoryTable takes
the frame or its encoder and throws without one.
Places each shadow at its light from the table's CPU rows, then clears and draws the layers of
each shadowed light that redraw picks with the casters built by add, a depth pass per
layer. Call this while recording each frame, before drawing shaded surfaces. A removed light
frees its shadow. A frame that draws no layer writes a timer's timestamps from an empty
compute pass.
Chooses which cast lights draw their layers this frame. A light it skips keeps the layers it
drew last, so a still light over still casters can skip until something it sees moves. A
light still draws when it gains a shadow, when its row moves, turns or changes range, after
resize and after a frame with enabled false. Layers count as drawn once their frame
submits, so a light recorded into an encoder alone draws on every record until resize.
Default every light.
@cpu
redraw:(
lamp:table.RowId
lamp)=>
conststirred:Set<unknown>
stirred.
Set<unknown>.has(value: unknown): boolean
@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.
has(
lamp:table.RowId
lamp)});
conststirred:Set<unknown>
stirred.
Set<unknown>.clear(): void
Removes all elements from the Set.
clear();
});
A light draws even if redraw would skip it when it gains a shadow, moves or changes range, and when a narrow spot turns. It also draws after resize replaces the map and when the shadows come back on.
Like the sun’s, its layers count as drawn once their frame submits. A light of no range or with a cone of no width draws no layer.
A light whose flicker jitters its position draws every frame; flicker its intensity alone to keep its layers.
A frame that draws no layer writes a timer passed in timestampWrites from an empty compute pass, so a profiler timer can stay on record.
A culling renderer culls every layer of a shadow in renderer.cull, before record picks the lights that draw. Give redraw to prepare before culling instead. cull then culls only the layers that draw, one for a narrow spot, and record draws those:
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.
Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before
the next submit. Call once per frame before passes that read the table. A HistoryTable takes
the frame or its encoder and throws without one.
Chooses the layers that draw this frame before renderer.cull, which then culls only those:
the layers of each light redraw picks, and of a narrow spot only its one. The next record
draws exactly these and ignores its own redraw. Call it after cast, in the frame that
records: a change before that record, such as cast or resize, drops the choice. Without
it, culling covers every layer.
Chooses which cast lights draw their layers this frame. A light it skips keeps the layers it
drew last, so a still light over still casters can skip until something it sees moves. A
light still draws when it gains a shadow, when its row moves, turns or changes range, after
resize and after a frame with enabled false. Layers count as drawn once their frame
submits, so a light recorded into an encoder alone draws on every record until resize.
Default every light.
@cpu
redraw:(
lamp:table.RowId
lamp)=>
conststirred:Set<unknown>
stirred.
Set<unknown>.has(value: unknown): boolean
@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.
has(
lamp:table.RowId
lamp)});
const
constculling:TgpuComputePass
culling=
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.
Records visible-instance lists for each enabled description that contains this renderer, for
the layers it reports active, such as those a shadow's prepare picked. Call this after
flush() and any kernels that move instances, before drawing. Throws unless the renderer has
cull: true.
Places each shadow at its light from the table's CPU rows, then clears and draws the layers of
each shadowed light that redraw picks with the casters built by add, a depth pass per
layer. Call this while recording each frame, before drawing shaded surfaces. A removed light
frees its shadow. A frame that draws no layer writes a timer's timestamps from an empty
compute pass.
record(
frame:frames.Frame
frame,
constcasters:Drawn
casters);
conststirred:Set<unknown>
stirred.
Set<unknown>.clear(): void
Removes all elements from the Set.
clear();
});
Call prepare after cast and after moving lights, in the frame that records. That record ignores a redraw of its own.
A change between prepare and record, such as cast, aim or resize, drops the choice. record then picks again, and those layers draw again the next frame.
The sun’s shadow takes the same prepare, with its cascades’ redraw.
Without prepare, culling covers every layer of an enabled shadow.
Call light.destroy() when nothing draws with its resources. It frees the shadow maps and their drawing resources. A table of lights is yours to destroy.
Culling Without candidates, every shaded pixel visits each light slot. There is no tile or cluster culling.
Clear coatshadeClear is exact for dielectrics and metals. It approximates intermediate metallic values.
One lighting A pipeline reads one lighting, the one piped last. Two lightings in one frame, such as a lit room seen through a window, need two sets of pipelines.
Depth precision A fixed map’s depth spans twice reach. At an extent of 20, a depth16unorm step is about 0.001 world units. A cascade’s depth spans its sphere’s width plus reach.
Cascade reach Cascades fit the camera’s view, not the casters. A caster beyond reach towards the sun casts nothing, and nothing beyond far is shadowed.
Fixed filter The filter is fixed at creation. A menu offering different filters needs a separate lighting for each.
Shadow casters Only lights placed on the CPU cast. lighting.create throws for pointShadow without points.table, or with a table of lighting.MovingPointLight or MovingSpotLight.
Layer cost Each layer that draws draws all its casters: six passes for a point light and one for a narrow spot.
Shadow countcount is at most 42 at WebGPU’s minimum of 256 layers, and at most 157 in a uniform binding of 64 KiB. Shading compares every in-range light with every shadow, so its cost grows with count.
hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
linear lightLinear light is colour as amounts of light, the form in which lighting adds up correctly, before the final pass encodes it for the screen.Words →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
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 →
flushA flush uploads the rows the CPU changed since the last one.Rows →
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 →
slotA slot is a row's place in its buffers, which a new row can take once the first is removed.Row ids →
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 →
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 →
texelA texel is one cell of a texture, as a pixel is one cell of the screen.Words →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.Words →
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 →
bind groupA bind group is a set of buffers, textures and samplers that a pipeline reads, and a pipeline has room for four.Words →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
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
shadow?
the sun's shadow, with a depth pass per cascade
pointShadow?
shadows from pointShadow.define that cast gives to lights of points.table, with a depth pass per face
Places the splits between cascades as fractions of far, cascades - 1 rising values between 0 and 1.Default (k / cascades)² after cascade k, 0.11 and 0.44 for three.
Places the cascades in the sun's light space whenever the shadow fits them: on each record, after aim and after setFar.Default lighting.fitSlices, a sphere around each slice of the view, snapped to whole texels.
Sets how far the map reaches towards the sun in world units: from the point it follows, or beyond each cascade with an eye.Default twice the extent, or far with an eye.
Places each shadow at its light from the table's CPU rows, then clears and draws the layers of each shadowed light that redraw picks with the casters built by add, a depth pass per layer.
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.
Point and spot shadows for a lighting: define describes them, and lighting.create makes them for the lights of its table as light.pointShadow, compiles them in initAsync, fills their shading and destroys them.