Every class, option and default. New here? Start with Getting started, which explains each feature and when to use it; this page is for looking things up. The reasons behind the design, with measurements, are in SPEC.md.
- Setup
- Sources: one shape everywhere
- Downsampler: mip chains and Hi-Z
- Reducer: tile reductions for tools
- ScalarReduction: an image to one value
- three.js
- The core package: CPU references and planning
- Vendoring:
downsampler/mipmap - Not built (yet)
import { Downsampler, Reducer, ScalarReduction, requiredFeatures, requiredLimits } from 'downsampler/webgpu';
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice( {
requiredFeatures: requiredFeatures( adapter ), // optional features the library uses, where the adapter has them
requiredLimits: requiredLimits( adapter ),
} );requiredFeatures( adapter ) (also re-exported by downsampler/three) returns the optional features the library uses that the adapter has:
| Feature | What it changes |
|---|---|
float32-filterable |
'average' chains of r32float, rg32float and rgba32float sample instead of loading, like every other filterable format: 0.74–1.00× the time on an RTX 3060, 0.69–1.00× on Intel UHD (DIVERGES #13). Sampled results follow the GPU's sampler weights; averageAccess: 'load' keeps them identical everywhere |
texture-formats-tier1 |
storage for r8unorm, rg8unorm, r16float, rg16float, the 16-bit normalized formats and the small integer formats |
bgra8unorm-storage |
storage for bgra8unorm |
Everything works without them; add your own features to the list.
requiredLimits( adapter ) (also Downsampler.requiredLimits, and re-exported by downsampler/three) returns the limits worth requesting for all three classes:
| Limit | Requested | Why |
|---|---|---|
maxStorageTexturesPerShaderStage |
max( 4, min( 6, adapter's ) ) |
one storage texture per level written in a dispatch; 6 gives six levels per dispatch |
maxComputeInvocationsPerWorkgroup |
256, where the adapter has it | 5- and 6-level kernels and ScalarReduction use 16 × 16 workgroups; compatibility mode defaults to 128 |
maxComputeWorkgroupSizeX |
256, where the adapter has it | ScalarReduction's combine workgroup is 256 wide |
Without these limits everything still works, with fewer levels per dispatch; only ScalarReduction and 5- or 6-level Reducers require 256 invocations, and say so in their error. Not included: a 6-level Reducer with 8 channels needs maxComputeWorkgroupStorageSize: 32768, which you request yourself.
Generated WGSL identifiers start with ds_. Hook code should avoid that prefix, the entry point names (main, partials, combine) and the hook names.
Every class reads a source the same way: source is a GPUTexture (read at its level 0) or a TextureLevel, { texture, mipLevel? }.
| Where | Field | Extra |
|---|---|---|
Downsampler encode/encodePass/generate/prepare options |
source |
resample: 'area' (a SourceOptions: { texture, mipLevel?, resample? }) |
Reducer dispatch |
source (and each of outputs) |
|
ScalarReduction run |
source |
Each source passes the same checks, with the same messages: dimension '2d', textureBindingViewDimension (where defined) '2d' or '2d-array', sample count 1, TEXTURE_BINDING usage, a float-sampleable format (depth included, read through its depth aspect; not stencil8; an integer Downsampler destination takes an integer source of its own signedness instead), and mipLevel inside the texture.
The other shared names:
- Sizes are
widthandheightfields (Reducer dispatches, ScalarReduction runs). With a source they default to its level's size, and must match it if given. - Layer ranges are
layers: [ first, count ](Downsampler options, ScalarReduction runs,PreparedBatch.layers,BufferCopy.layers). A bare count islayerCount(Reducer dispatches, from layer 0;ReducerCopy.layerCount).
const downsampler = new Downsampler( device, options );
downsampler.generate( texture ); // encode + submit
downsampler.encode( encoder, texture, encodeOptions ); // into your encoder: a compute pass per batch (sRGB: a render pass per level)
downsampler.encodePass( pass, texture, encodeOptions ); // into a compute pass you own (storage path only)- Dimension
'2d', sample count 1,textureBindingViewDimension(where defined)'2d'or'2d-array'. Array layers are reduced together, one workgroup z per layer, so all layers take the same dispatches. Cube maps work as 6-layer'2d-array'textures (WGSL has no cube storage textures). - Usage
TEXTURE_BINDING, plusSTORAGE_BINDINGon the storage path,COPY_DSTon the buffer path orRENDER_ATTACHMENTon the render path (Output paths). - A supported format:
| Formats | Needs |
|---|---|
rgba8unorm, rgba8snorm, rgba16float, r32float, rg32float, rgba32float |
core |
r8unorm, rg8unorm, r8snorm, rg8snorm, r16float, rg16float, r16unorm, rg16unorm, rgba16unorm, r16snorm, rg16snorm, rgba16snorm |
texture-formats-tier1 |
bgra8unorm |
bgra8unorm-storage |
rg11b10ufloat, rgb10a2unorm |
storage with texture-formats-tier1; otherwise the buffer path |
rgb9e5ufloat |
always the buffer path (it is never a storage texture) |
rgba8unorm-srgb, bgra8unorm-srgb |
the render path with RENDER_ATTACHMENT, else the buffer path (WebGPU has no sRGB storage textures); reduced in linear light (sRGB color) |
rgba8uint, rgba8sint, rgba16uint, rgba16sint, r32uint, r32sint, rg32uint, rg32sint, rgba32uint, rgba32sint |
core (rg32uint/rg32sint: the buffer path in compatibility mode) |
r8uint, r8sint, rg8uint, rg8sint, r16uint, r16sint, rg16uint, rg16sint, rgb10a2uint |
texture-formats-tier1; without it the 4-byte ones (rg16uint, rg16sint, rgb10a2uint) take the buffer path |
Integer formats are reduced in exact integer arithmetic (SPEC §6.1 Integer formats). 'average' is the exact mean, rounded to the nearest integer with ties to even, at every width (32-bit sums don't overflow): the 2×2 mean at even sizes, the render-pass bilinear weights as exact fractions at odd sizes under 'exact', area weights under 'box'. Folds work as for any format; a custom fold is fn reduce(a: vec4u, b: vec4u) -> vec4u for uint formats (e.g. a | b for occupancy) and takes vec4i for sint formats. A separate source must be an integer format of the same signedness; values are clamped to the destination's range. oddSizes: 'spd', Reducer and ScalarReduction don't take integer formats (they accumulate floats).
Depth formats can't be destinations: use a separate source into r32float or rg32float.
supports( texture ) and unsupportedReason( texture ) (a string or null) say whether it can, and why not: a missing feature, usage or format. encode, generate and prepare throw with the same reason.
| Option | Values | Default | What it does |
|---|---|---|---|
levelsPerDispatch |
1 … 6 | storage path: min( 6, maxStorageTexturesPerShaderStage ); buffer path: 6; both 4 below 256 invocations per workgroup |
Output levels per dispatch. Above the storage texture limit only with output: 'buffer'. |
output |
'auto', 'storage', 'buffer', 'render' |
'auto' |
How levels are written (Output paths). |
averageAccess |
'sample', 'load' |
'sample' |
How 'average' reads each batch's source level: one hardware bilinear sample, or four loads with weights in the shader. 'load' is identical on every GPU; samplers round their 8-bit weights per vendor. Unfilterable formats and folds always load. |
f16Rounding |
'nearest', 'device' |
'nearest' |
float16 formats: round each level to nearest even in the shader (the same everywhere), or use the device's conversion, which truncates on D3D12 (float16 rounding). |
srgbRounding |
'exact', 'device' |
'exact' |
sRGB on the render path: round each level to its code in the shader (the same bits everywhere), or let the GPU encode, as plain render passes do: their speed, with codes up to 3 apart (sRGB color). |
renderPathMinTexels |
0 to Infinity |
1920 × 1080 | Under output: 'auto', the smallest sRGB chain (texels per layer of its first level) drawn by render passes; smaller ones take the buffer path. 0: always render; Infinity: never (sRGB color). |
compatibility |
'auto', true, false |
'auto' |
The compatibility-mode path (below). 'auto' takes it for textures of a device without 'core-features-and-limits'. |
tail |
boolean | true |
'exact' chains: once a level fits one workgroup (32 × 32; 8 × 8 below 256 invocations), finish the chain in one dispatch instead of a batch per odd size. Same rule; tail levels use shader weights (within one rgba8 step of the sampler's). |
halo |
boolean | false |
'exact' and 'box' chains of float formats: carry odd steps inside a batch with a halo (each workgroup also computes the few texels past its tile that the next odd steps read), so some render sizes take one dispatch fewer: 1920×1080 3 instead of 4. Same rule and results (odd steps inside a batch use shader weights, as the tail does). Measured 0.85–1.00× of the default on an RTX 3060, neutral on Intel UHD. Needs 256 invocations per workgroup; integer formats and 'spd' ignore it. haloMaxExtra and haloMaxOutput tune the planner. |
exactTile |
8, 16, 32 | 16 on Apple GPUs, 32 on other hardware with 256 invocations per workgroup, 8 on software adapters and in compatibility mode | Smallest first-output tile of an 'exact' batch. Same results; a speed knob measured per vendor. 16 and 32 need 256 invocations. |
maxResampleRatio |
a number ≥ 1 | 8 (the exported maxResampleRatio) |
The largest source ÷ destination size ratio per axis that source.resample: 'area' accepts. Only validation reads it: the kernel loops over each texel's span at run time, so it compiles nothing new. The taps per first-level texel grow with its square, (ratio + 1)² at most. |
The constructor validates every option and throws on an unknown value. The resolved values, defaults filled in, are readable as fields (downsampler.averageAccess is 'sample' by default; .tail, .exactTile, .levelsPerDispatch, .bufferLevelsPerDispatch, …).
| Option | Default | What it does |
|---|---|---|
baseMipLevel |
0 | In place: the level read; outputs start at baseMipLevel + 1. With source: the first level written. |
mipLevelCount |
the rest of the chain | Destination levels involved. In place this includes the source level, so { baseMipLevel: 2, mipLevelCount: 4 } reads 2 and writes 3, 4, 5. With source it counts written levels. |
oddSizes |
'exact' |
'exact', 'box' or 'spd' (Odd sizes). |
reduction |
'average' |
'average', 'min', 'max', 'minmax' or { wgsl } (Reductions). |
source |
none | A texture, or { texture, mipLevel = 0, resample? }: read the first level from another texture; resample: 'area' allows any destination size (Separate source). |
layers |
every layer | [ first, count ]: reduce only these array layers (Partial updates). |
rect |
the whole level | { x, y, width, height }: the texels that changed; rewrite only what depends on them. Empty (width or height 0): records nothing (Partial updates). |
scratch |
none | Buffer path only: a GPUBuffer (STORAGE | COPY_SRC, at least scratchSize( texture, options ) bytes) to write through instead of one the Downsampler allocates per texture. Share one across textures to bound memory (Output paths). Ignored on the storage path; never destroyed by the library. |
A 2:1 reduction is exact only when a dimension halves cleanly. At odd, non-unit sizes:
'exact'(default). The odd level ends a batch, and the next level is re-sampled with normalized-coordinate bilinear filtering. Results equal render-pass and WebGL mipmaps (thereduceReferenceoracle), and folds use the conservative2x … 2x+2footprint, so Hi-Z is correct. At render sizes this takes more dispatches than SPD; the tail kernel (tail, on by default) folds the small trailing levels into one dispatch (1920×1080: 4 dispatches).'spd'(opt-in). AMD SPD's semantics: clamped loads, ⌊n/2⌋ sizes with the last odd row or column dropped, no rounding between the levels of a dispatch,⌈levels / levelsPerDispatch⌉dispatches at any size (2 up to 4096²). 1.4–2.1× faster than'exact'at render sizes on an M5 Pro, but levels drift from their footprints at odd sizes.'average'only: min/max under these semantics are not a conservative Hi-Z, so folds are rejected with an error that points to'exact'or aReducerwith'zero-weight'edges.'box'(opt-in). Area-weighted odd sizes, as in nvpro_pyramid: each output texel covers[x·S/n, (x+1)·S/n)of the level it reads, and every texel it overlaps contributes in proportion to the overlap. Along an odd size2n+1that is three taps2x … 2x+2with weights(n−x, n, x+1)/(2n+1); even sizes are the usual 2×2 box. Every level keeps the base level's mean.- Same batches and dispatches as
'exact'(with or without the tail). Batches that read an odd level, and tail batches, load their texels and weight them in the shader; the others are the'exact'kernels, so at a power of two'box'is'exact'bit for bit. - Folds (
'min','max','minmax', custom) are accepted and give exactly the'exact'result: their footprint already covers every overlapping texel. - Works with the tail kernel, both output paths, compatibility mode,
encodePassand partial updates (rect,layers). - Recommended for GI, irradiance and roughness chains, and UI.
- Same batches and dispatches as
Like render-pass mipmaps, 'exact' 3 → 1 takes only the center texel, so a 31×31 texture can reduce to an unrepresentative 1×1. Under 'box' its 1×1 is the mean of all 961 texels.
downsampler.generate( irradiance, { oddSizes: 'box' } );reduction |
Result | Notes |
|---|---|---|
'average' |
bilinear average | matches render-pass mipmaps |
'min', 'max' |
per channel min / max over every texel the output covers | conservative at odd edges |
'minmax' |
even channels min, odd channels max | rg = (min, max) and ba a second pair; levels read pairs back as already reduced |
{ wgsl: 'fn reduce( a: vec4f, b: vec4f ) -> vec4f { … }' } |
a custom fold | must be associative, commutative and idempotent (like min, max, bitwise or); values are in normalized units |
Folds select existing values, so they match the CPU oracle exactly. Sums, per-channel op lists and custom kind: 'sum' reductions have no meaning under 'exact' odd sizes and are rejected: use a Reducer.
const hiZ = device.createTexture( {
format: 'rg32float', size: [ width, height ], mipLevelCount: Math.floor( Math.log2( Math.max( width, height ) ) ) + 1,
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.STORAGE_BINDING,
} );
downsampler.encode( encoder, hiZ, { source: depth, reduction: 'minmax' } ); // r = min, g = max- The source can be any float-sampleable 2D texture, including depth (read through its depth aspect), with
TEXTURE_BINDINGusage and the destination's layer count. It can't be the destination itself: usebaseMipLevelto reduce in place. - Destination level
baseMipLevelmust be the same size as the source level (a converting copy, which loads, so it is exact) or half of it (one reduction step), unlessresample: 'area'(below). Every destination level in range is written, includingbaseMipLevel. resample: 'area': any destination size, up to 8× smaller per axis (themaxResampleRatioconstructor option, default 8), up or down. The usual case is a power-of-two Hi-Z (1024×512 or 2048×1024 from 1920×1080) whose later levels halve cleanly: a 12-level 2048×1024 pyramid takes 2 dispatches. Destination texel x covers[x·S/n, (x+1)·S/n)of the source:'average'weights every source texel by its overlap, and folds combine every source texel with any overlap, so min/max stay conservative at every level. Later levels followoddSizes. Without the option another size is an error (a stale destination after a resize fails loudly), and the message names it.
// A power-of-two Hi-Z from a 1920×1080 depth buffer: 2048×1024, 12 levels.
downsampler.encode( encoder, hiZ, { source: { texture: depth, resample: 'area' }, reduction: 'max' } );- Single-channel sources (depth,
r*) are read as(v, v, v, v), so'minmax'of depth gives(d, d)at level 0. - Use
'max'(or thegof'minmax') for conventional depth, where an object is occluded if its nearest depth is behind the tile's farthest;'min'with reverse-Z. sourceUnsupportedReason( destination, source, baseMipLevel )checks a pairing without encoding. The source checks are the shared ones (Sources), plus: not the destination itself, the same layer count, and the size rule.- Plans are cached per destination and option set, holding only the most recent source texture: recreating a depth buffer on resize replaces the entry.
| Method | What it does |
|---|---|
generate( texture, options? ) |
Creates an encoder, encodes, submits. |
encode( encoder, texture, options? ) |
One compute pass per batch, plus the buffer path's copies after each; on the render path, one render pass per level and layer. |
encodePass( pass, texture, options? ) |
One dispatch per batch into your compute pass. Dispatches are separate usage scopes, so each batch sees the previous one's writes. Throws on the buffer path (a compute pass can't record copies) and the render path. |
prepare( texture, options? ) |
What encode records, for dispatching it yourself (or inspecting the plan): PreparedBatch[] with kernel ('exact', 'tail' or 'clamp'), sourceMipLevel (null for the separate source), firstMipLevel, count, outputWidth/outputHeight, groupsX/groupsY, layers ([ first, count ]), pipeline, bindGroup, output, and on the buffer path buffer and copies ({ mipLevel, offset, bytesPerRow, rowsPerImage, x, y, width, height, layers: [ first, count ] }). Dispatch them yourself with dispatchWorkgroups( groupsX, groupsY, layers[ 1 ] ). Validates and throws like encode, and on the render path (render passes aren't dispatches). |
release( texture ) |
Drops the texture's cached bind groups and destroys its buffer-path buffers, partial-update uniforms and compatibility scratch textures. Call it after the last submitted use. |
Pipelines are cached per Downsampler and compiled synchronously on first use of a format, reduction and batch shape; prepare() ahead of time to move that cost.
encode, encodePass, generate and prepare take:
| Option | Meaning |
|---|---|
layers: [ first, count ] |
Reduce only these array layers (2d-array, or a cube viewed as one). Other layers are untouched. |
rect: { x, y, width, height } |
The dirty texels of level baseMipLevel, or of the source level with a separate source. Integers, inside that level. An empty rect (width or height 0) is a no-op, as WebGPU's zero-size copies are: once the other options are validated, it records and creates nothing. |
Each later level rewrites exactly the texels whose footprint touches the previous level's rewritten ones (2x … 2x+2 under 'exact', 'box' and the tail kernel; each batch's clamped blocks under 'spd'; a resampled source's first level: every texel whose area span meets the rect). If the source changed only inside rect and the old chain was valid, the result is bit-identical to a full recompute, and every other texel and layer is untouched. This is tighter than SPD's rectInfo, which snaps to 64-texel tiles (DIVERGES #15).
It works on every path: the tail kernel, 'spd', the buffer output path, compatibility mode, separate sources and encodePass.
Cost and lifetime. Each distinct rect and layer range creates one small uniform buffer (a 256-byte slot per dispatch) and its bind groups. The 16 most recent are cached per texture. An evicted one is destroyed once the queue has finished the work submitted so far (device.queue.onSubmittedWorkDone()), so many partial updates can be recorded in one encoder, as long as you submit it before awaiting anything; release( texture ) destroys the rest at once. A rect that changes every frame creates a buffer per frame (a ring buffer with dynamic offsets is a possible later change).
// A decal was painted into level 0 at (128, 64), 32×32: refresh only what depends on it.
downsampler.encode( encoder, texture, { rect: { x: 128, y: 64, width: 32, height: 32 } } );
// One face of a cube baked into a 6-layer 2d-array texture.
downsampler.encode( encoder, faces, { layers: [ 2, 1 ] } );
// Nothing changed this frame: a no-op.
downsampler.encode( encoder, texture, { rect: { x: 0, y: 0, width: 0, height: 0 } } );prepare( texture, { rect } ) lists what each batch writes: regions (per level of the batch, a rect or null) and the workgroup offset groupX/groupY. See examples/partial-update.html, which paints into a texture and checks every update against a full recompute.
output |
Levels written | Texture needs |
|---|---|---|
'storage' |
one write-only storage texture per level | STORAGE_BINDING |
'buffer' |
packed texels into one storage buffer, then a copyBufferToTexture per level |
COPY_DST, a format of whole 32-bit words |
'render' |
a render pass per level and layer, its fragment shader the compute kernel's rule and rounding (the same bits; float32 within a few ulp). 'average' chains in place, 'exact' or 'box' |
RENDER_ATTACHMENT, a color-renderable float format |
'auto' (default) |
sRGB: the render path when the texture has RENDER_ATTACHMENT, the chain is one it covers and its first level has at least renderPathMinTexels texels (default 1920 × 1080), else the buffer path. Other formats: storage whenever the device can store the format; the buffer path only for formats it can't (rgb9e5ufloat, rg11b10ufloat without tier1, rg32float in compatibility mode) |
as above |
outputPath( texture ) returns 'storage', 'buffer', 'render' or null. A storable texture without STORAGE_BINDING is an error under 'auto', not a silent switch to the slower buffer path. The buffer path writes six levels per dispatch at any storage texture limit, and costs one extra write and read of the written levels (1.6–2.3× the storage path where both exist; SPEC §6.1). It can't record into a caller's compute pass (encodePass throws; use encode).
Each texture's plan keeps its own scratch buffer, sized for its largest batch (about a third of the base level), until release( texture ). With many textures, share one instead:
const scratch = device.createBuffer( { size: downsampler.scratchSize( largest ), usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC } );
for ( const texture of textures ) downsampler.encode( encoder, texture, { scratch } ); // one encoder is fine: each chain copies out before the next writesscratchSize( texture, options? ) is the size that fits any batch of that chain (every written level in the buffer layout), and 0 for storage-path textures. A smaller buffer is rejected with the size the chain needs.
rgba8unorm-srgb and bgra8unorm-srgb textures (most color textures in three.js) are reduced in linear light and stored sRGB-encoded, as render-pass mipmaps of an sRGB texture are:
- Each batch reads the sRGB view, so the hardware decodes every texel to linear (and filters in linear on the sample path). Black and white average to 0.5 linear, code 188, not 128.
- Each level is encoded to 8-bit codes in the shader with the exact sRGB curve, rounded to nearest (correctly rounded for the shader's f32 value: a
powestimate, corrected against the exact thresholds; a stored value is already an exact code, so the store skips the correction), and written by render passes or through the buffer path (below), since WebGPU has no sRGB storage textures, even through a view. Later levels in a batch read it back through the exact decode table, so a chain equals level-by-level generation. - Alpha is linear (these formats store it as plain unorm8): averaged in 0–255 units, ties to even, as
rgba8unorm. 'min','max'and'minmax'select stored codes exactly: the decode is monotonic and the encoder inverts it, so they equal folding the codes themselves.- Hardware decoding isn't exact everywhere: an Apple M5 Pro decodes to 12-bit linear values (254 of 256 codes inexact, up to 0.39 of a code step off).
averageAccess: 'load'snaps every loaded texel to the exact decode table, so results are the same on every GPU; the default'sample'keeps the hardware's decode and filtering, as render passes do (about a code from the exact result at most). - How levels are written. With
RENDER_ATTACHMENTusage, by render passes (the render path): one per level and layer, whose fragment shader rounds each level exactly as above and returns the exact decode of its code, so the attachment's encode writes that code: the compute path's rule and rounding per level (withaverageAccess: 'load', the oracle's codes on every GPU, as the compute path's; the two can still differ by a code where a value lies within float error of a rounding threshold, since a multi-level compute batch averages its in-tile levels with other float arithmetic: 2 values at 1920 × 1080 on an M5 Pro). It covers'average'in place under'exact'or'box', withrect,layersand sub-ranges; folds,'spd'and separate sources take the buffer path, which needsCOPY_DST. WithoutRENDER_ATTACHMENT, the buffer path.encodePasstakes neither. - Which path, by size:
renderPathMinTexels. Under'auto'a chain takes the render path only when its first level (the base level, or a partial update'srect) has at least this many texels per layer: default 1920 × 1080 (defaultRenderPathMinTexels). Smaller chains take the buffer path (or, withcolorSpace: 'srgb', the storage path), unless the texture lacks the usage for them (COPY_DST,STORAGE_BINDING), in which case they render at any size. The reason is Apple: a render pass costs about the same at any size there, so on an M5 Pro the render path is slower than the buffer path below 1080p and faster above; NVIDIA and Intel gain at every size, so they lose that gain below 1080p. Tune it for your hardware:new Downsampler( device, { renderPathMinTexels: 0 } )renders at any size (best on the RTX and Intel we measured),Infinitynever renders under'auto'.output: 'render'or'buffer'choose a path outright. - Cost (DIVERGES #16, srgb-renderpath.md). The render path takes 0.63–0.79× of the buffer path's time on an RTX 3060 and 0.74–0.92× on Intel UHD. Plain render passes (three.js's mipmaps) are still faster, 1.05–1.6× on the RTX and about 5× on Intel, because they skip the exact rounding: on Intel it is most of the chain's time.
'load'on the render path is slow (four snapped loads per fragment). On an Apple M5 Pro render passes cost about 0.01 ms each at any size, so the render path (at their speed there) is slower than the buffer path below 1080p (1.25–2.2×), ties at 1080p and is faster from 1440p (0.79–0.83×), hence the defaultrenderPathMinTexels;colorSpace: 'srgb'(below) is the fastest path there at every size (srgb-m5.md). srgbRounding: 'device'skips it: the attachment encodes, and the sampler's decode is used as is (no tables, so it also works in compatibility mode). That is plain render passes' speed (within 0–7 % on the RTX, 3–12 % on Intel), but about 16 % of the written bytes differ from the exact codes on the RTX (by up to 3), 6 % on Intel (up to 2) and under 1 % on the M5 Pro (up to 2), and they differ between GPUs. On the M5 it saves almost nothing (0.96–1.02× of the exact render path). Each level is still within the oracle's tolerance.
colorSpace: 'srgb' (recommended when you create the texture). It is the fastest way to mip sRGB color on an Apple M5 Pro (0.40–0.68× of the buffer path; 0.26–0.44× of the render path's time up to 1707×960, 0.56× at 1080p, 0.79–0.89× at 1440p and 4096²) and close to the render path elsewhere (RTX 3060: 0.73–0.83× of the buffer path, against the render path's 0.63–0.79×), with the same bytes. Create the color texture as rgba8unorm (or bgra8unorm) with its sRGB format as a view format, and tell the library it holds sRGB color:
const texture = device.createTexture( {
format: 'rgba8unorm', viewFormats: [ 'rgba8unorm-srgb' ], size, mipLevelCount,
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_DST
} );
downsampler.encode( encoder, texture, { colorSpace: 'srgb' } );
// Materials sample the sRGB view, so filtering decodes first, as with an sRGB texture.
const view = texture.createView( { format: 'rgba8unorm-srgb', usage: GPUTextureUsage.TEXTURE_BINDING } );- The levels are the same bytes an
rgba8unorm-srgbtexture gets. WithRENDER_ATTACHMENTit takes the render path through the sRGB view, as an sRGB texture does. Without it, it writes the levels directly as storage, with no buffer and no copies (20–30 % less time than the buffer path on an RTX 3060, 7–17 % on Intel, 32–60 % on the M5 Pro), andencodePassworks. The speed above is this storage write: for a texture that also renders,new Downsampler( device, { output: 'storage' } )keeps it. - The sRGB view must name its usage: an sRGB view can't have the texture's
STORAGE_BINDING. - Sampling the texture through that view costs the same as sampling an sRGB texture (RTX 3060: 1.000×; M5 Pro: 0.97–1.04×, median 1.00×).
- Not with
oddSizes: 'spd', and not in compatibility mode, which has noviewFormats.
In WebGPU compatibility mode (requestAdapter( { featureLevel: 'compatibility' } ) on a device without 'core-features-and-limits') a dispatch may bind only one view of a texture, so an in-place chain can't read level n and write n + 1 together. With compatibility: 'auto' the library detects such textures (usesCompatibility( texture )), has each batch write per-level scratch textures, and copies each level in with a dispatch. Results are bit-identical, it works with encodePass, and prepare() lists the copies with copy: true. Other compatibility-mode rules: views cover whole textures, view dimensions are fixed at creation (so cube textures can't be written; use 6-layer '2d-array'), and rg32float has no storage, so it takes the buffer path.
By default results may differ between GPUs by a hardware sampler's 8-bit weight step times the local contrast (render passes and GenerateMips do the same). For identical bits everywhere:
new Downsampler( device, { averageAccess: 'load' } ); // 2–13 % slower on an RTX 3060, 22–31 % on Intel UHD at render sizesf16Rounding: 'nearest' (the default) already makes float16 levels identical; 'device' opts out (below). On the render path, srgbRounding: 'device' opts sRGB levels out (sRGB color).
float16 formats (rgba16float, rg16float, r16float) are computed in f32 and rounded to a half once per level, before the level is stored and before the next one reads it. f16Rounding (on Downsampler and Reducer) chooses how:
| Value | How | Result |
|---|---|---|
'nearest' (default) |
Round to nearest even in the shader, with integer math on the float's bits (float16Wgsl), then store an exact half. |
The same bits on every GPU, matching the CPU oracles (toHalf). |
'device' |
The device's own conversion (pack2x16float, and the store). |
Truncates toward zero on D3D12 (NVIDIA and Intel; measured on an RTX 3060 and Intel UHD). On Apple GPUs it rounded to nearest even when measured (M5 Pro, Chrome 148: the suite's tie cases came out bit for bit as under 'nearest'), but no specification promises either behavior. |
What 'device' costs in accuracy. Where it truncates, every stored half is up to one f16 step (one unit in the last place, about 0.1 % of the value) closer to zero than the rounded one: positive values come out low by half a step on average, never high. Each level is computed from the previous, already truncated level, so the bias doesn't average out down the chain; the deepest levels of a large texture end up a few steps below the true mean. Images rarely show it. Anything that compares levels numerically does: exposure from a 1×1 mip, a half-precision Hi-Z compared against depth, an oracle-based test suite (it was 211 of 287 full-matrix failures on the RTX 3060 before the default changed).
When to use it. Only after measuring the in-shader rounding as a real cost on your target, for chains where a low bias of up to one f16 step per level is acceptable (display-only color mips, for instance). Measured on rgba16float chains at render sizes, 'nearest' costs 5 % on an RTX 3060 and 8.5 % on Intel UHD against 'device' (results/windows/round2/defaults.md). The default stays 'nearest'.
new Downsampler( device, { f16Rounding: 'device' } ); // the device's conversion: truncation on D3D12A Reducer is one compute kernel that reduces up to six levels inside a workgroup tile and stores only the levels you choose. It is the building block for the passes tools fuse around SPD: luminance pyramids, shading-change pyramids, block statistics, G-buffer downsamples. The kernel is compiled in the constructor; pipelines are shared between equal Reducers on a device.
const stats = new Reducer( device, {
reduction: [ 'average', 'average', 'max', 'sum' ],
levels: [ 3, 5 ], // 8×8 and 32×32 blocks
format: 'rgba32float', // output textures (or a store hook)
bindings: { wgsl: '@group(1) @binding(0) var image: texture_2d<f32>;', entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, texture: { sampleType: 'unfilterable-float' } } ] },
load: `fn load( texel: vec2i, layer: u32 ) -> vec4f {
let l = dot( textureLoad( image, texel, 0 ).rgb, vec3f( 0.2126, 0.7152, 0.0722 ) );
return vec4f( l, l * l, l, 1.0 );
}`,
} );
const bindGroup = device.createBindGroup( { layout: stats.bindGroupLayouts[ 1 ], entries: [ { binding: 0, resource: image.createView() } ] } );
const outputs = stats.levels.map( level => device.createTexture( { format: 'rgba32float', size: stats.levelSize( level, width, height ), usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING } ) );
stats.encode( encoder, { width, height, bindGroup, outputs } );| Option | Default | What it does |
|---|---|---|
levels |
required | Source-relative levels to emit, strictly increasing, 1 (half size) … 6. Every level up to the last is reduced; only these are stored and get bindings. The deepest sets the tile: 4 levels and fewer use 8 × 8 workgroups, 5 and 6 use 16 × 16 (256 invocations). |
reduction |
'average' |
Four (or eight) per-channel ops, a builtin ('average', 'min', 'max', 'minmax', 'sum') expanded to every channel, or a custom { wgsl, kind: 'fold' | 'sum' }. |
edges |
'zero-weight' |
'zero-weight': off-image texels count nothing, level sizes ⌈n/2ˡ⌉, every texel counted once. 'clamp': SPD/FSR, clamped coordinates, ⌊n/2ˡ⌋ sizes, the last odd row or column dropped. |
load |
none: read source |
WGSL fn load( texel: vec2i, layer: u32 ) -> vec4f. Coordinates are always in bounds. It may be called more than once for an edge texel, so it must not have side effects (exception: 'clamp' at a whole number of source tiles). |
store |
none: write outputs |
WGSL fn store( level: u32, texel: vec2i, layer: u32, value: vec4f ), called once per emitted texel with level counted from the source and value normalized. Levels are emitted shallow to deep with a barrier between them, so a store hook may keep var<workgroup> state from one level for a deeper one (SPEC §14.1). |
size |
a uniform the Reducer manages | WGSL fn size() -> vec2u, the source size, with a load hook (e.g. from your own uniforms under dynamic resolution). |
format |
none | Output texture format, without a store hook. Any Downsampler destination format. |
output |
'storage' if the device can store format, else 'buffer' |
'buffer' packs levels into a buffer the Reducer owns and copies them into the outputs (they need COPY_DST). Not allowed with a store hook. |
f16Rounding |
'nearest' |
As for Downsampler, for float16 output formats. |
dimension |
'2d' |
View dimension of source and outputs; '2d-array' reduces every layer. |
sourceFormat |
4 channels | The source texture's format, without a load hook, so single-channel formats (depth, r*) are splatted to (v, v, v, v). |
bindings |
none | { wgsl, entries }: your @group(1) declarations and their GPUBindGroupLayoutEntry[], used by the hooks. |
channels |
4 | 4 (a vec4f per texel) or 8 (DsWide { lo: vec4f, hi: vec4f }; needs both a load and a store hook). Eight channel ops imply 8. |
label |
downsampler reducer <edges> <levels> |
Debug label. |
| Op | Emitted value |
|---|---|
'sum' |
Σ v |
'average' |
Σ v / n, n the texels the edge policy counts (in-image texels under 'zero-weight', 4ˡ under 'clamp') |
'min', 'max' |
min / max |
'weight' |
Σ w: this channel weighs the 'weighted' channels (at most one) |
'weighted' |
Σ w·v / Σ w, and 0 where Σ w = 0 |
'argmin', 'argmax' |
the key of a payload fold: the texel with the smallest (largest) key wins |
'payload' |
carried from the winning texel; must follow a key or another payload. Ties on the key go to the smaller payload, so put a texel index first for row-major ties. |
Custom reductions: kind: 'fold' (default) must be idempotent; kind: 'sum' is combined exactly once per counted texel and emitted as is. Nothing is rounded between levels: each emitted level is the reduction of its own source block, rounded once by the store.
| Field | Default | What it is |
|---|---|---|
width, height |
the source level's size | Source size in texels. Required with a load hook; with a source, it must match if given. |
source |
— | A texture or { texture, mipLevel } (Sources), without a load hook. |
outputs |
— | One texture (or { texture, mipLevel }) per emitted level, in levels order, without a store hook. Each must be at least levelSize( level, width, height ). Under 'zero-weight' a mip of a source-sized texture is one texel short at odd sizes, so use separate textures; 'clamp' sizes equal mip sizes. |
layerCount |
the source's (or first output's) layers with '2d-array', else 1 |
Array layers to reduce, from layer 0 (workgroup z). A count, not [ first, count ]: the tile kernel has no layer offset, and hooks see the workgroup's layer. |
bindGroup |
— | Your group 1, created from reducer.bindGroupLayouts[ 1 ] or an equal layout. Required when the Reducer has bindings. |
| Member | What it does |
|---|---|
encode( encoder, dispatch ) |
Its own compute pass, then the buffer-output copies. |
encodePass( pass, dispatch ) |
Into your compute pass. With output: 'buffer', call encodeCopies( encoder, dispatch ) after the pass ends. |
encodeCopies( encoder, dispatch ) |
Buffer output only: copy each emitted level into its texture. Does nothing on the storage path. |
prepare( dispatch ) |
What encodePass records, for dispatching it yourself: { pipeline, bindGroup, toolBindGroup, workgroups }, plus buffer and copies ({ texture, mipLevel, offset, bytesPerRow, rowsPerImage, width, height, layerCount }) with output: 'buffer' (record those after the pass). Validates and throws like encode. |
bindGroup( dispatch ) |
Group 0 for a dispatch (cached per size and textures, the 16 most recent); prepare( dispatch ).bindGroup. |
workgroups( width, height, layerCount? ) |
[ x, y, layerCount ] for dispatchWorkgroups. |
levelSize( level, width, height ) |
Size of an emitted level under this Reducer's edges. |
release( texture? ) |
Drops cached bind groups (all, or those using texture) and destroys the buffers the Reducer created for them: size uniforms and buffer-output buffers. Call it after the last submitted use. Entries evicted from the 16-entry cache are destroyed once the queue has finished the work submitted so far. Your textures and buffers are never destroyed. |
wgsl, entryPoint, pipeline, layout, bindGroupLayouts |
The kernel, its entry point ('main'), compiled pipeline, pipeline layout and [ group 0, group 1 ] layouts. |
levels, edges, channels, output, label |
The resolved options. |
Errors are thrown with a reason: a missing hook or binding, an output that is too small or of the wrong format or usage, more output textures than maxStorageTexturesPerShaderStage, a tile larger than the workgroup memory limit (6 levels of 8 channels need 32 KiB), or, in compatibility mode, a source and output sharing a texture.
Reduces an image to one vec4f and a weight per layer in two dispatches at any size: 16 × 16 workgroups each reduce a 64 × 64 tile to a partial, then one 256-invocation workgroup per layer combines them. Every texel counts once. Needs 256 invocations per workgroup (Setup).
const range = new ScalarReduction( device, { reduction: 'minmax' } ); // min, max, min, max
range.encode( encoder, { source: depth, output: { buffer, offset: 0 } } ); // { value: vec4f, weight: f32 } per layer
const metering = new ScalarReduction( device, {
reduction: [ 'average', 'max', 'min', 'average' ],
bindings: { wgsl, entries }, // your @group(1)
load: 'fn load( texel: vec2i, layer: u32 ) -> vec4f { … }',
finish: 'fn finish( value: vec4f, weight: f32 ) { … store an exposure … }',
} );
metering.encodePass( pass, { width, height, bindGroup } );| Option | Default | What it does |
|---|---|---|
reduction |
'average' |
One op for every channel, 'minmax' (even channels min, odd max), or one op per channel: 'sum', 'average', 'min', 'max', 'weight', 'weighted', 'argmin', 'argmax', 'payload' (as for the Reducer). |
load |
none: read run.source |
WGSL fn load( texel: vec2i, layer: u32 ) -> vec4f for in-image texels, reading your @group(1). |
finish |
none: write run.output |
WGSL fn finish( value: vec4f, weight: f32 ), optionally with a third layer: u32, run once per layer by one invocation. value has averages and weighted means divided; weight is Σ w with a weight channel, else the texel count. |
bindings |
none | { wgsl, entries } of your @group(1). |
block |
4 | Texels per invocation per axis (1, 2, 4, 8): a tile of 16·block. 4 measured fastest on Apple. |
channels |
4 | 4 or 8 (DsWide). Without a load hook, an 8-channel reduction only takes combine-only runs. |
| Field | What it is |
|---|---|
source |
Without a load hook: a texture or { texture, mipLevel } (Sources); any float-sampleable 2D format, depth included (single-channel formats splat). |
width, height |
The image size in texels: required with a load hook; with a source, its level's size (must match if given). |
layers |
[ first, count ], each reduced to its own result. Default: all of the source's layers, or [ 0, 1 ] with a load hook. |
bindGroup |
Your group 1, required with bindings. |
output |
{ buffer, offset = 0 } without a finish hook. The buffer needs STORAGE usage; offset a multiple of the device's minStorageBufferOffsetAlignment (256 unless you requested less); 32 bytes per layer ({ value: vec4f, weight: f32 }), 48 with 8 channels (resultBytes). |
partials |
Combine only: { buffer, offset = 0, count } (offset aligned as for output), count accumulations per layer that your own dispatch wrote (one vec4f each), e.g. a Reducer's deepest level through its store hook. Records the combine dispatch alone. Sum-like channels must hold sums. Your group 1 must not bind this buffer too. |
texels |
Combine only: the texel count behind the partials, required for 'average' channels or without a 'weight' channel. |
unsupportedReason( run ) explains why a run can't be recorded; encode/encodePass/prepare throw with it. Runs with the keys used before 0.1, texture, mipLevel or size, are rejected with a message naming source, width and height.
| Member | What it does |
|---|---|
encode( encoder, run ) |
Each dispatch in its own compute pass. |
encodePass( pass, run ) |
Both dispatches (or the combine alone) into your pass. |
prepare( run ) |
What encodePass records, for dispatching it yourself: { partials, combine, bindGroup, toolBindGroup, workgroups, combineWorkgroups }; partials is null for a combine-only run. Validates and throws like encode. |
kernel( { dimension, splat } ) |
{ wgsl, layout, partials, combine } for a source shape. |
combineKernel() |
{ wgsl, layout, combine } for combine-only runs. |
workgroups( width, height, layerCount? ), partialsBytes( width, height, layerCount? ) |
Sizes of the partials dispatch and buffer. |
release( resource? ) |
Drops the cached plans of a source texture, partials buffer or output buffer (without one: every plan) and destroys the params and partials buffers the reduction created for them, never yours. Call it after the last submitted use. Plans are kept for 4 run shapes per resource; older ones are destroyed once the queue has finished the work submitted so far. |
bindGroupLayouts |
[ group 0, group 1 ] as on a Reducer: create your hooks' bind group from index 1 (with bindings). Group 0 is that of a '2d' source, a load hook or a combine-only run. |
ops, block, partialBytes, resultBytes, combinesOnly |
The resolved options. |
createScalarKernel( options ) and scalarLayoutEntries( … ) are the pure WGSL generator and its layout, for vendoring.
A Reducer whose deepest level is 6 emits one texel per 64 × 64 tile. Its store hook can write those as partials (use 'sum' channels, and form w·v in the load hook), and a combine-only ScalarReduction turns them into the scalar: 2 dispatches with one read of the source, which is how the FSR luma pyramid is rebuilt in test/tools/generator.js (generator/luma-pyramid-fused).
downsampler/three works with WebGPURenderer on the WebGPU backend. three is an optional peer and is typed structurally, so the adapter imports nothing from it.
import { generateMipmaps, getDownsampler, getGPUTexture, requiredLimits, unsupportedReason } from 'downsampler/three';
const renderer = new THREE.WebGPURenderer( { requiredLimits: requiredLimits( await navigator.gpu.requestAdapter() ) } );
await renderer.init();
const texture = new THREE.StorageTexture( width, height );
texture.generateMipmaps = true; // allocate the full chain
texture.mipmapsAutoUpdate = false; // stop three regenerating it with render passes after a compute write
texture.minFilter = THREE.LinearMipmapLinearFilter;
renderer.initTexture( texture ); // or render/compute into it first
// … write level 0 …
if ( ! generateMipmaps( renderer, texture, { reduction: 'max' } ) ) console.warn( unsupportedReason( renderer, texture ) ); // then fall back
// Into your own encoder (not submitted), with a Downsampler of other options:
generateMipmaps( renderer, texture, { encoder, downsampler: { averageAccess: 'load', f16Rounding: 'device' } } );| Export | What it does |
|---|---|
generateMipmaps( renderer, texture, options? ) |
Generates the chain with a shared Downsampler. options are EncodeOptions plus encoder (record into it and don't submit; default: submit at once) and downsampler (DownsamplerOptions of the shared instance, e.g. averageAccess, f16Rounding, output, tail). Returns false, doing nothing, if the texture isn't allocated, has one level (in place), isn't supported, or can't take options.source. |
unsupportedReason( renderer, texture, options? ) |
Why generateMipmaps would return false with these options, or null. |
getDownsampler( renderer, options? ) |
The shared Downsampler of the renderer's device for an option set (one per distinct set, any key order). Use it for encode, prepare, release, or Hi-Z with a separate source. |
getGPUTexture( renderer, texture ) |
The GPUTexture behind a three.js texture, or undefined. |
requiredLimits( adapter ) |
The same function as in downsampler/webgpu, for new WebGPURenderer( { requiredLimits } ). |
Downsampler |
Re-exported. |
The texture must have STORAGE_BINDING usage (in current three.js a StorageTexture or StorageArrayTexture), or COPY_DST for formats that take the buffer path. sRGB color textures (SRGBColorSpace, so rgba8unorm-srgb) always take the buffer path, so regular three.js color textures, which have COPY_DST, work today. Other regular textures don't get storage usage from three; native support for them is planned as an in-tree three.js option (SPEC §10). See examples/three.html.
import { … } from 'downsampler' is backend-neutral (no WebGPU types). It holds the CPU reference implementations the GPU kernels are tested against ("oracles"), useful for testing your own use of the library:
| Export | What it is |
|---|---|
reduceReference( values, width, height, layers, quantization, reduction?, options? ) |
One 'exact' step on the CPU: the oracle every backend is tested against. values are RGBA floats; it returns the next level and a per-value filterTolerance. That tolerance assumes weights computed in the shader; pass { weights: 'sampler' } for a level a hardware sampler filtered (the default averageAccess: 'sample', a batch's first output), which allows the samplers' 8-bit weights. |
tolerance( expected, quantization, filterTolerance?, reduction? ) |
The test tolerance for one value (folds: 0). |
spdReference(…), spdChainReference(…) |
oddSizes: 'spd' batches and chains. |
boxReference(…), boxChainReference(…), areaReference( values, width, height, layers, quantization, reduction, outWidth, outHeight, options? ) |
oddSizes: 'box' steps and chains, and an area step to any size (a resampled source). areaSpan, areaOverlap: the taps and their integer weights. |
reducePyramid( values, width, height, layers, { reduction, levels, edges, channels } ) |
The Reducer oracle (f64, with each value's term magnitude); pyramidTolerance( magnitude ). |
scalarReference(…), scalarCombineReference(…) |
ScalarReduction oracles: the GPU's pairing in f32, the exact f64 result and an error bound per channel. |
intReference( values, width, height, layers, quantization, reduction, { weights, width, height, source } ), roundedMean |
Integer-format steps, exact: weights: 'bilinear' ('exact') or 'area' ('box', a resampled source). |
maxViolations( base, width, height, level, w, h ) |
Counts max-pyramid texels below some base texel in their area: 0 for a conservative Hi-Z. |
planBatches( width, height, options ), mipSize, mipLevelCountFor, levelSize, footprint |
Planning and sizes. |
formats, quantize, quantizeTexel, toHalf, fromHalf, packRgb9e5, … |
Format table and encoders. |
srgbCode, srgbDecodeTable, quantizeSrgb, srgbThresholds, srgbBounds, srgbDecode, srgbEncode |
sRGB: the correctly rounded encoder, the exact decode table, the rounding thresholds and the f32 bounds the shader compares against. The oracles take the quantization 'srgb8'. |
The WGSL generators are exported from downsampler/webgpu for vendoring: createKernel, kernelLayoutEntries, float16Wgsl, packedFloatWgsl, srgbWgsl, bufferOutputWgsl, createIntKernel, intMeanWgsl, createScalarKernel. Kernels that read or write sRGB (usesSrgbTable( options )) take the exact tables from a storage buffer: bind srgbTable( device ) at srgbTableBinding (12); kernelLayoutEntries declares it. An exact kernel for an sRGB format with output: 'storage' writes the encoded bytes to storage textures of the linear alias format (srgbScratchFormat: rgba8unorm or bgra8unorm), for a self-dispatching tool that copies them into the sRGB level with copyTextureToTexture.
An engine that can't take a dependency (three.js's WebGPUTextureMipmapUtils) copies one file: dist/mipmap.js, built from src/mipmap.ts. It imports nothing, is plain ES2022 (about 19 KB, 350 lines with comments) and holds in-place 'average' chains only: the 'exact' and tail kernels, the planner, the default rules and the formats they write.
import { createMipmapKernel, kernelDefaults, mipmapAccess, mipmapFormats, planMipmapBatches } from 'downsampler/mipmap';
const defaults = kernelDefaults( device.limits, device.adapterInfo ); // { levelsPerDispatch, bufferLevelsPerDispatch, exactTile, tailMaxTile, tail }
const access = mipmapAccess( texture.format, device.features ); // 'sample', or 'load' for unfilterable formats
for ( const batch of planMipmapBatches( texture.width, texture.height, { mipLevelCount: texture.mipLevelCount, ...defaults } ) ) {
const code = createMipmapKernel( { format: texture.format, dimension, count: batch.count, access, tail: batch.kernel === 'tail', tile: batch.tile } );
// Bindings: 0 filtering sampler ('sample' only), 1 view of level batch.sourceMipLevel ('float' or 'unfilterable-float'),
// 2 … count + 1 write-only storage views of levels batch.firstMipLevel …; dispatch groupsX × groupsY × layers.
}| Export | What it is |
|---|---|
createMipmapKernel( { format, dimension?, count, access?, tail?, tile?, f16Rounding? } ) |
One batch's WGSL. Equal to createKernel( { ...options, f16Pack: false } ) of downsampler/webgpu: float16 kernels define ds_round_f16 alone, without the buffer path's ds_half_bits and ds_pack_f16. |
planMipmapBatches( width, height, { mipLevelCount?, levelsPerDispatch, tail?, tailMaxTile?, exactMinTile? } ) |
The batches, equal to core planBatches in place under 'exact'; the tail is on by default. Takes exactTile for exactMinTile, so kernelDefaults( … ) spreads in. |
kernelDefaults( limits, adapterInfo? ) |
The device defaults Downsampler resolves its options from: levels per dispatch (storage textures, and the buffer path's), the 'exact' tile (32, 16 on Apple, 8 below 256 invocations and on software adapters), the largest tail tile, and tail: true. Pure. |
mipmapFormats, mipmapAccess( format, features? ) |
The 19 storage formats with a float view (8- and 16-bit normalized, float16, float32), each with its quantization, filterability and storage feature. sRGB, packed, rgb10a2unorm and integer formats need the full library. |
A copy may be restyled and pruned, but its WGSL must stay byte for byte the library's: three's GPU suite doesn't cover what this repo's does, so equal WGSL is what makes this suite its oracle. Check it with
node scripts/check-vendored.mjs path/to/WebGPUTextureMipmapUtils.jswhich imports the file (its relative imports resolved), calls its generator (an exported createMipmapKernel, or a module-level createKernel taking options or three's positional ( format, dimension, count, access, tail, tile )) on the golden option sets in test/golden/mipmap/cases.json, and compares each result with its .wgsl file. It prints the matching count, the cases that differ with a line diff, and the changed lines across all of them; cases the copy rejects (formats it leaves out) are listed as not covered and don't fail it. Exit status 1 means drift.
When the library's kernels change on purpose, npm run golden:update rewrites the goldens (test/core/golden.test.js fails until then), and the diff of test/golden/mipmap/ is the change a vendored copy has to follow.
- Transform hooks around the average (premultiplied alpha, log-luminance; SPEC §5 Planned).
- Subgroup and fp16-arithmetic kernels: measured and not built, because they weren't faster enough or changed results (
results/windows/round2/m3.md).
The full list is in SPEC.md §11 and DIVERGES.md; How it compares is the short version.