By the time the deferred lighting, the sky and the clouds are done, Taos Explorer holds a
linear HDR image in rgba16float. Everything between that image and the canvas is the
subject of this page: removing aliasing without blurring a city that is mostly sub-pixel detail,
smearing motion the way a camera would, scattering a little light the way a lens does, choosing an
exposure for a scene that goes from a moonless field to the sunlit top of a cloud deck, and mapping
the result onto a display. Two things make this harder than in most games. The world is streamed
and static, while the thing the player cares about most, the aircraft, travels with the camera at
hundreds of meters per second. And the floating origin moves under everything every few kilometers.
Every temporal effect here has to tell real motion from those two kinds of fake motion.
The post chain
explorer/main.ts (feature registration ~4614–5428) · src/engine/engine.ts · src/engine/antialiasing.ts
Explorer builds its frame with the engine's render graph: each feature adds passes in the
order it was registered, and post-processing features read frame.hdr and write a new
handle back to it. The order of the engine.addFeature calls in explorer/main.ts
is therefore the order of the chain. Anatomy of a frame covers the
whole graph; this page starts where the volumetric clouds and the screen-space reflections end.
The order is not the textbook one, and most of its choices are explained by a comment next to the registration:
- Heat haze before bloom and AA. The exhaust shimmer displaces what is behind the plume, so it must see the lit scene and the clouds, and its result must be antialiased like any other pixel.
- Bloom before AA. The halo is computed at render resolution from the jittered frame and then resolved by TAA along with the scene, which antialiases the halo itself. (Bloom cannot simply move after TAA: TAAU has to stay the last resolution-changing stage.)
- Precipitation after bloom, before AA. Rain streaks are not bloomed, but they are resolved and tonemapped with the scene. That part of the chain belongs to Rain, snow and wet weather.
- Motion blur after AA. It convolves the resolved image; blurring first would hand TAA a smeared input whose neighborhood box is too wide to reject anything.
- Metering after the blur, before the flare and the overlays. A bright lens flare counted in the histogram would stop the whole picture down; labels and debug lines are not scene light.
- Overlays before the tonemap. The wireframe, collision lines and place labels are crisp (no blur, no DoF) but still go through exposure and the curve, so they sit in the picture rather than on it.
Motion vectors and reprojection
explorer/main.ts (PlaneVelocityFeature ~5236–5272, re-anchor ~32420–32530) · src/renderer/render_graph/passes/velocity_pass.ts · src/engine/components/camera.ts · explorer/lib/ground/ground_grass.ts
Every temporal stage in the chain (the TAA resolve, the upscaler, motion blur, and the cloud and SSR reprojections upstream) needs to know where each pixel was in the previous frame. There are two ways to find out. The cheap one reconstructs the pixel's world position from the depth buffer and projects it with last frame's view-projection matrix. That is exact for anything that did not move in the world during the frame. The expensive one re-rasterizes geometry with both this frame's and last frame's model matrices into a velocity buffer, which is right for anything.
Camera reprojection from depth
For a static world the first method is the whole answer, and almost everything Explorer draws is static:
photogrammetry tiles, terrain, buildings, roads, trees. The math is the same in the TAA, TAAU and motion
blur shaders. Explorer renders with reversed-Z (near maps to 1, far to 0, set by
reversedZ: true in the context options), which only changes the background test and the
depth comparisons; the unprojection itself is convention-agnostic.
- (VP)jitthis frame's jittered view-projection: the depth buffer was rasterized with it, so only its inverse lands each depth sample on the right world point
- (VP)prevlast frame's un-jittered view-projection: the history is a resolved, pixel-aligned image
- dthe non-linear depth at the pixel; p is kept homogeneous (not divided by w)
Keeping p homogeneous matters for the sky. A far-plane point has w near zero, a direction rather than a position; dividing would blow it up, but multiplying the un-divided vector by the previous matrix gives a correct rotation-only reprojection. The TAA resolve uses that so the sky side of a silhouette is antialiased too. Motion blur, by contrast, skips background pixels entirely: a sky "position" at the far plane would turn pure rotation into enormous screen-space vectors.
The jitter detail is easy to get wrong. A comment in taa_pass.ts spells out the failure: with the
un-jittered inverse, every reconstructed position would be offset by the sub-pixel jitter, history would be
fetched from the wrong texel, and dense foliage would jitter instead of converging.
Why most pixels have no velocity
Camera reprojection fails for one class of object, and in a flight simulator it is the important one: things that move with the camera. Reprojected by camera motion alone, a pixel of the aircraft's wing in the chase view asks the history for wherever the ground behind the wing was last frame. The comment on the feature puts it directly:
// Velocity buffer for the flyable aircraft only (see "Fly a plane"). TAA and motion blur
// otherwise assume a static world and reproject by camera motion alone — right for the
// streamed tiles, wrong for an aircraft that moves with the camera: its history comes
// from where the GROUND behind it was, so it ghosts and smears. The pass records
// per-object motion for just the aircraft's draws; every other pixel stays 0, which
// both consumers treat as "use camera reprojection".
const planeVelocityItems: DrawItem[] = [];
const planeVelocityPass = await VelocityPass.create(ctx);
engine.addFeature({
name: 'PlaneVelocityFeature',
…
addPasses(frame): void {
if ((planeVelocityItems.length > 0 || foxDrawItems.length > 0) && frame.depth) {
frame.velocity = planeVelocityPass.addToGraph(frame.graph, { depth: frame.depth }).velocity;
// The grass sways: its own motion too (else TAA smears it).
grassFeature.addVelocity(frame);
}
},
});
Despite the name and the comment, the list of draws pushed into planeVelocityItems holds
more than the flown aircraft: the flown aircraft and its glass-cockpit screens and tow
plane, the tanker, multiplayer aircraft, airport traffic and live ADS-B traffic, street cars, parked
vehicles, wrecks, and the satellites near enough to show a shape. The skinned fox walker and its board
are added as skinned and mesh items. Each item carries its modelMatrix and
previousModelMatrix; the photoreal tiles never enter the list. When the list is empty the
feature adds nothing to the graph, and frame.velocity stays undefined, which selects the
depth-only pipeline variants downstream.
The VelocityPass re-draws those items into an rg16float target holding a UV delta
(current − previous), depth-tested read-only against the G-buffer depth with
less-equal (flipped for reversed-Z), so only visible surfaces write and nothing needs its own
depth pre-pass. The target is cleared to exactly zero. Grass is a special case: its blades sway in a vertex
shader, so the grass feature appends its own velocity draw (same blades, same indirect arguments) with
loadOp: 'load'. It only does so on frames where the velocity pass exists, since otherwise there
is no buffer to add to. Each blade is placed twice, as this frame and last frame had it: the wind at both
times, and what touches it at both (the pushers are kept in stable slots, so slot i is the same
wheel or foot in both frames, and last frame's rotor downwash is kept as well). A blade a wheel is pressing
as it rolls through gets its true motion vector, not a smear.
The coverage rule
A covered pixel records the camera's motion plus the object's, and also this frame's jitter, because the current position comes from the jittered matrix and the previous from the un-jittered one. A covered pixel is therefore never exactly zero, and both consumers test exactly that:
// Same coverage rule as the TAA resolve: the buffer is cleared to exactly 0 and a
// covered pixel records at least the jitter, so any non-zero value means "this
// pixel was drawn into the velocity pass" …
if (any(sampled_vel != vec2<f32>(0.0))) {
velocity_uv = sampled_vel;
} else {
velocity_uv = camera_velocity_uv(in.uv, depth);
}
Any threshold above zero would be wrong. A 0.5 px cutoff, for instance, would treat slow covered pixels as uncovered and blur them by camera reprojection instead, so an object riding with the camera, such as a cockpit around it, would smear whenever the camera turned.
The floating origin
Explorer keeps world coordinates small by re-anchoring the origin under the camera: every 10 km in the free
camera, every 2 km in the chase view and every 250 m in the cockpit (REANCHOR_DIST*). The cockpit
distance comes from f32 precision: about a millimeter of rounding 10 km out is a whole pixel on an instrument
panel under a meter from the eye. When the axes have drifted more than a degree from local up, the re-anchor
also rotates the basis. Either way every world-space position jumps in one frame, and a temporal effect
that compared last frame's matrices with this frame's would see the whole world teleport. The comment
describes the symptom: "a gray smear, most visible over the dark Moon".
The answer is to carry history across the jump rather than discard it. The camera keeps a pending shift (or a full rigid remap when the basis turned) and folds it into the previous view-projection the next time it snapshots, so a static point reprojects onto itself:
// Fold the shift into the previous VP so a STATIC point reprojects to itself across the
// re-anchor (prevVP · translate(shift), since a point's new coords are its old minus shift).
if (this._pendingOriginShift) {
const s = this._pendingOriginShift;
if (this._prevViewProj) {
this._prevViewProj = this._prevViewProj.multiply(Mat4.translation(s.x, s.y, s.z));
}
this._pendingOriginShift = null;
}
if (this._pendingOriginRemap) {
… this._prevViewProj = this._prevViewProj.multiply(this._pendingOriginRemap);
}
So no, a re-anchor does not cause a history discontinuity. TAA never calls resetHistory() in
Explorer; it relies on this fold and on its own per-pixel rejection. The movers need the same treatment, since
their previous model matrices are also in the old origin. On a re-anchor the aircraft's per-part matrices
(and the glass cockpit's and the tow plane's) are translated by −shift, or multiplied by the whole turn.
Dropping them instead would read as the aircraft standing still in the world for a frame: a meter of motion
past a panel 0.7 m from the eye, which motion blur and TAA would turn into a one-frame smear of the whole
cockpit at every re-anchor. ADS-B traffic and satellites have their own shift helpers.
A related trick runs during the ISS ride, where the station and the camera move together at orbital
speed (about 120 m a frame, says the comment). Rather than give the station velocity, Explorer feeds the
station's own frame-to-frame ECEF motion to notifyOriginShift. To the temporal passes the station
then stands still, and the background is at infinity either way.
Temporal antialiasing
src/renderer/features/taa_feature.ts · src/renderer/render_graph/passes/taa_pass.ts · src/renderer/render_graph/passes/taa_jitter.ts · src/shaders/taa.wgsl
The antialiasing modes Explorer offers are PLANET_AA_MODES = ['taa', 'taau', 'off'], and TAA is
the default. The reasoning behind leaving out the spatial filters is in the constant's comment: without
TAA's history, the shadow filter's and the AO's noise stays fixed, and the streamed tiles' thin edges crawl.
A morphological filter costs about what TAA's single resolve pass does anyway (SMAA is three passes). SMAA is
still registered, for the headset.
Jitter
TAAFeature.earlyUpdate runs before any feature's regular update, so every geometry
pass that later reads camera.jitteredViewProjectionMatrix() rasterizes with the same sub-pixel
offset. The offset walks a Halton(2, 3) sequence of 16 samples, skipping index 0 (which is always the
origin and would waste a frame):
- Hb(k)radical inverse of k in base b; ±½ pixel after centering
- W, Hrender-target size; NDC spans 2 units across it
The noise index exists because the resolve reads history at the de-jittered position (below) and so adds no blur of its own. Nothing then hides the 16-tap dither of the soft-shadow filter, and a fixed dither would leave the penumbrae visibly stripy. So the shadow kernel's noise is animated per frame, but only when TAA runs; SMAA T2x and the upscaler pass 0, which means static noise. See Shadows.
The resolve, step by step
The resolve is one fullscreen triangle with three render targets: the resolved color, this frame's linear
depth (r16float) for next frame's disocclusion test, and the same color again into next frame's
history slot. The history slots ping-pong between two persistent textures, taa:history and
taa:history:1, so there is no copy pass. The third target exists because later passes may draw
into the resolved image in place, and the history must not see that. Code that wants last frame's resolved
image (SSGI, for instance) asks taaHistoryKey() for whichever slot was written last.
Per pixel, the shader does this:
- Store own depth. Linear view depth (clip w, from row 3 of the un-jittered VP), capped at 60,000 to stay a finite half-float. Background pixels store the cap.
- Pass through if there is no history. On the first frame, after a resize, or after
resetHistory(), the current sample goes straight out. - Dilate motion. Of the pixel and its four plus-shaped neighbors, take the closest depth (reversed-Z aware) and use that texel's position and velocity. A silhouette pixel that the jitter flips between foreground and background then always follows the foreground, so the antialiased edge travels with its object.
- Reproject. As above, from depth; with a non-zero velocity sample, from
uv − Δuvinstead. For a mover the expected previous depth is set to its own current depth: the buffer has no depth component, and assuming the cockpit stood still in the world would fail the disocclusion test for every panel pixel at 50 m/s, so fine detail would shimmer. - Remove the jitter from the motion. The motion metric is
(uv − jitter) − prev_uv. Counting the jitter as motion would make a static pixel read as moving by up to about 0.7 px, which would hold the blend high and narrow the clamp differently every frame. - Fetch history at the de-jittered position. A static pixel then samples its own texel center, with no resampling at all, and the jittered samples accumulate onto a fixed grid.
- Reject disocclusion. If no texel in the 3×3 window around the reprojected position held a surface within 10 % of the expected linear depth, the history is discarded. A window, not a single texel, so jitter-flipped silhouette pixels are not rejected every frame, which would switch antialiasing off exactly at the edges.
- Clip in YCoCg. Build a variance box from the 3×3 neighborhood, fetch history with a 5-tap Catmull-Rom filter, clip it toward the box center.
- Blend with a motion-adaptive, luma-weighted weight.
Neighborhood clipping in YCoCg
The neighborhood test is the core of any TAA: history that does not look like the current neighborhood is stale. The resolve accumulates the first and second moments of the nine samples in YCoCg, forms μ ± γσ, and intersects that with the true min/max. γ narrows from 1.5 when static to 0.75 when moving, so genuine sub-pixel detail accumulates on a still image while panning rejects ghosts. The clamp space is YCoCg because its luma/chroma split pins the chroma axes that RGB leaves loose on saturated foliage.
fn clip_aabb(aabb_min: vec3<f32>, aabb_max: vec3<f32>, hist: vec3<f32>) -> vec3<f32> {
let p_clip = 0.5 * (aabb_max + aabb_min);
let e_clip = max(0.5 * (aabb_max - aabb_min), vec3<f32>(1e-5));
let v_clip = hist - p_clip;
let a_unit = abs(v_clip / e_clip);
let ma_unit = max(a_unit.x, max(a_unit.y, a_unit.z));
if (ma_unit > 1.0) { return p_clip + v_clip / ma_unit; }
return hist;
}
…
let gamma = mix(GAMMA_STATIC, GAMMA_MOVING, motion);
let box_min = max(mean - gamma * sigma, c_min);
let box_max = min(mean + gamma * sigma, c_max);
var history = max(sample_history(prev_uv, vec2<f32>(dims)), vec3<f32>(0.0));
history = from_clip(clip_aabb(box_min, box_max, to_clip(history)));
Two details in the neighborhood loop guard against artifacts. Coordinates are clamped to the texture: an
unclamped textureLoad returns zero out of bounds, which would inject a black sample into the box
at the screen edges; the clip would pull history toward black and feed it back, and "the black corner grows
inward one texel per frame." And the history fetch is a 5-tap bilinear Catmull-Rom rather than one bilinear tap, because
bilinear resampling re-blurs the accumulated image a little every frame. Its negative lobes can ring below
zero, so the result is clamped before the clip.
The blend
The current-frame weight α depends on screen-space motion in pixels per frame. It runs from
blendStatic 0.03 to blendMoving 0.25, saturating at motionFull 2 px/frame,
through a square-root response so that slow pans of half a pixel to a pixel, "exactly the speed where a long
trail reads as sickening ghosting", already flush most of the history. The comments call the moving weight
the dominant lever against ghosting: on sub-pixel foliage the stale color already lies inside the box, so
the clip cannot reject it, and the only defense left is to trust history less.
- mde-jittered screen motion, px/frame
- LRec. 709 luma of the HDR sample; bright samples are down-weighted so one sky pixel leaking through a leaf edge cannot flicker the result
All this costs one pass: 0.071 ms over New York and 0.051 ms facing Cape Town in a per-pass profiler
capture (1280×720, desktop GPU). The persistent memory is
two rgba16float color slots plus two r16float depth slots, 20 bytes per render pixel,
about 41 MB at 1920×1080.
TAAU, render scale and pixel ratio
src/renderer/features/temporal_upscale_feature.ts · src/renderer/render_graph/passes/temporal_upscale_pass.ts · src/shaders/temporal_upscale.wgsl · src/renderer/render_context.ts · explorer/main.ts (~5273–5285)
Explorer has three independent ways to draw fewer pixels, and they compose:
| Knob | What it changes | Who upscales | Default |
|---|---|---|---|
| Pixel ratio | ctx.maxPixelRatio: canvas backing-store pixels per CSS pixel (Auto, 1, 1.5, 2, 3, or the screen's own) | browser compositor | Auto: the screen's own, at most 1.2 |
| Render scale | ctx.setPixelRatioScale(0.5…1): shrinks the backing store further | browser compositor | 100 % |
| TAAU | ctx.setRenderScale(0.67): render targets below the canvas size | the temporal upscaler | only in the Low preset |
The pixel-ratio cap is the most consequential of the three on a phone. The comment in
RenderContext explains: a native device pixel ratio of 3 is nine times the fragment work of 1×
for a deferred renderer. Explorer captures the context's cap at startup as AUTO_PIXEL_RATIO and restores it when the setting returns to Auto; "Screen's own" sets 0, which disables the cap. The "Render scale" slider is not TAAU's scale; it resizes the canvas backing store,
and the settings code notes that TAAU renders at two-thirds of that again.
The upscaler
TemporalUpscaleFeature calls ctx.setRenderScale in its earlyUpdate, so
every scene, lighting and post pass registered before it sizes its targets to the reduced
ctx.width × ctx.height. Its resolve shares the TAA's structure (closest-depth dilation, velocity
or camera reprojection, r16float depth-history rejection, a YCoCg variance box, motion-adaptive luma-weighted
blend), with three differences that make it an upscaler rather than a blurred upsample:
- A longer jitter period. The Halton period is
ceil(8 / renderScale²): 8 at native, 18 at 0.67, 32 at 0.5, so every display pixel sees enough distinct sub-pixel phases. - Sample confidence. Each display pixel weights the current frame by how close the nearest jittered
render sample landed to its center,
exp(−2 d²)with d in render pixels, renormalized by 1.36 so its mean over a uniform jitter is about 1. That weighting is what turns accumulation into super-resolution. - Sharpening outside the loop. A contrast-adaptive sharpen (RCAS style, amount 0.3) reads the un-sharpened history and writes the output; sharpening never feeds back into accumulation.
Its dials differ slightly from TAA's: blendMoving 0.2 and motionFull 2.5 display px.
The low moving weight is deliberate: a continuously moving camera must still accumulate, or the image falls
back to the aliased low-resolution current frame.
Passes after the upscaler see a display-size color
and a render-size depth and velocity. A pass that sized its output to ctx.width (the render
size) would, wherever a pixel did not blur, show the top-left corner of the upscaled image: a flashing
frame. So motion blur sizes its target from the color input and reads depth and velocity at their own texel
for each pixel.
Motion blur and depth of field
src/renderer/features/motion_blur_feature.ts · src/shaders/motion_blur.wgsl · src/renderer/features/dof_feature.ts · src/renderer/render_graph/passes/dof_pass.ts · src/shaders/dof.wgsl
Motion blur: a one-frame shutter
Motion blur is on by default (and in every preset but Low) with strength 1,
maxRadiusPx 64 and samples 16. It is registered after the antialiasing: it reads the
jittered view-projection, convolves the resolved image, and so never hands TAA a smeared neighborhood. The
feature is "camera-only" in the sense that it never draws its own velocity pass
(useVelocityBuffer stays false), but it picks up frame.velocity from the
PlaneVelocityFeature whenever that exists. The aircraft, cars and fox therefore blur by their own motion, and
the city by the camera's.
- sstrength; 1 blurs over one whole frame of motion, a full-frame shutter
- Δuvvelocity buffer sample, or the camera reprojection from depth
The sample line is centered on the pixel, so the streak is symmetric about the shading point rather than trailing it. The 64 px clamp keeps a camera cut from streaking the frame; 16 taps over 64 px puts the samples 4 px apart, the comment's rule for keeping the streak smooth. Below half a pixel of motion the shader returns the center sample, and background pixels are never blurred. In the profiler capture at 1280×720 it costs 0.030 ms over New York.
Depth of field
Depth of field is off and not in the settings. effects.dof = false is forced at startup with the
comment "Depth of field waits for a photo mode." The feature is still registered after motion blur, so the
blurred frame is what gets the bokeh, and its parameters are in meters because city scale runs from meters to
kilometers: focus at 1,500 m, a 1,000 m half-range, a 4 px bokeh radius.
- zlinear depth from near/far (reversed-Z normalized first); zf focus distance, r focus range, R bokeh radius in px
- c < 0near field; c > 0 far field
The pass runs in three stages: a half-resolution prefilter stores color plus the signed CoC in alpha; a tile
pass records the largest near-field CoC per 8×8 half-res tile; and a full-resolution composite gathers 48
taps on a Fibonacci spiral (golden-angle spacing, square-root radii, a per-pixel interleaved-gradient
rotation), far field over the sharp image, then the near field at the dilated tile CoC so foreground blur
spills over in-focus pixels behind it. Explorer sets skyInFocus. The sky, stars and Moon sit at
the far plane and would otherwise take the maximum CoC; with the flag their CoC is zero, but nearer
out-of-focus tiles still spread softly onto them.
Heat haze and lens bloom
explorer/lib/aircraft/heat_haze.ts · explorer/lib/aircraft/heat_haze.wgsl · src/renderer/features/lens_bloom_feature.ts · src/shaders/lens_bloom.wgsl
Heat haze
Hot exhaust bends light, so what is seen through it wavers. HeatHazeFeature is a fullscreen pass
that runs only when the host has given it plumes that frame: up to four cones, each from a nozzle position and
exhaust direction, set where the aircraft's lights are placed. jetPlume() sizes a cone from the
nozzle radius and engine power p:
- length2 rn · (10 + 30 p): about 40 nozzle diameters at full power, a quarter of that at idle
- radius / endRadius1.2 rn at the nozzle, rn · (2.6 + 2.2 p) at the far end
- strength / speed0.5 + 0.5 p; the noise is carried aft at 25 + 60 p m/s
- cutoffno plume below 2 % power
Per pixel the shader intersects the view ray with each cone, weights the effect by how deep the ray sits in the core and how far along the plume, and gains up to 4× when looking along the plume, where the ray stays in it longer. It offsets the scene lookup by two octaves of value noise advected with the exhaust. The offset is capped at 60 % of the plume's apparent width and never more than 2 % of the screen, because unbounded it would pull the image into spikes. Two refinements make it believable. Bending alone is invisible against open sky (a uniform background moved a little is the same background), so the plume also flickers in brightness by up to ±16 % and carries a thin soot-gray smoke. And a displaced lookup that would fetch something standing in front of the plume, such as the aircraft's own tail, is canceled. Afterburners add a marched flame with shock diamonds. Everything is camera-relative, with the camera subtracted on the CPU in f64.
Lens bloom
Every lens, and the eye, scatters a few percent of all the light it receives into a wide halo. The
LensBloomFeature models exactly that. There is no threshold: a fixed share of all the
light, 4 % in Explorer, is spread over every scale of blur at once. Bright things glow in proportion and
dim ones are not visibly changed. The engine's thresholded bloom is not used: it stays off, and its
settings exist only so saved ones still load. The lens bloom costs about 0.05 ms.
The first downsample uses the brightness-weighted ("Karis") average of the five boxes, so a single blazing
pixel, a sun glint or a lamp, adds its share without making the whole halo flicker as it appears and
disappears under the jitter. Taps are clamped at 6×10⁴ so one out-of-range value cannot spread across the
halo. The composite is energy-preserving, a mix rather than an add:
// Halo brightness (scene units, before exposure) under which the lens dirt stays dark:
// a few times a sunlit sky's.
const DIRT_KNEE : f32 = 4.0;
…
let halo = textureSampleLevel(bloom_tex, samp, in.uv, 0.0).rgb / max(comp._p0, 1.0);
let dirt = textureSampleLevel(dirt_tex, samp, in.uv, 0.0).r;
let s = clamp(comp.strength, 0.0, 1.0);
let hl = luma(halo);
let excess = max(hl - DIRT_KNEE, 0.0) / max(hl, 1e-4);
let rgb = mix(scene.rgb, halo, s) + halo * excess * dirt * comp.dirt;
The lens dirt (strength 0.5) is a procedural texture generated once on the CPU from a seeded LCG. It lights up only where the halo exceeds a level well above a sunlit sky, so it shows when looking toward the sun or past runway lights at night, and never across an ordinary daytime frame. Explorer turns it off in the cockpit view: "Lens dirt is on a camera's lens, not on the pilot's eye."
Auto exposure
src/renderer/features/auto_exposure_feature.ts · src/renderer/render_graph/passes/auto_exposure_pass.ts · src/shaders/auto_exposure.wgsl · explorer/main.ts (AE constants ~837–862, per-frame drive ~33208–33250)
The light in Explorer spans everything from a moonless field to the top of a sunlit cloud deck, and the scene's own content swings the average just as hard: a dark forest, a white glacier, half a frame of black space. A single exposure multiplier cannot cover that, so Explorer meters every frame. The meter's result is a single float in a persistent storage buffer, read by the tonemap pass; the image itself is not touched.
The histogram
Two compute dispatches. The first samples every fourth pixel in each direction (one in sixteen), takes Rec. 709 luminance, and bins its log2 into 64 bins spanning −10 to +6, a quarter of an EV per bin. Each 8×8 workgroup builds a workgroup-local histogram with atomics and flushes it to the global buffer with one atomic add per bin. The second, a single 64-thread workgroup, swaps the histogram out (clearing it for the next frame), skips the darkest 5 % and the brightest 2 % of samples, and averages the log luminance of the rest. Trimming the ends keeps a few black pixels or a sun disc from steering the result.
The light anchor
Metering alone would make the exposure depend on what the camera looks at rather than on the light. Explorer therefore blends the metered average with an anchor: its own estimate of how bright typical ground is under the current sun and sky, computed on the CPU each frame.
- S, Sgroundthe sun's intensity, and its share on level ground (× sine of elevation)
- w
anchorWeight0.5 on the ground, rising to 1 above the air - ccompensation: +0.5 EV in full daylight, eased to 0 at night
- Emin, Emax0.35; and 4.0 by day, eased to 0.5 at night
With the same midday sun and five different views, the anchor keeps the exposure within 0.51–0.94, where the meter alone would spread it over 0.40–1.37. A dark forest is not metered up to middle gray. The compensation keeps a clear midday from metering dim, and its constants are calibrated so a clear midday reads as the city and the sea do when metered alone.
Opening up slowly, stopping down fast
The smoothing is exponential with separate rates. When the scene brightens and the exposure must fall it
uses darkenSpeed 2.5 (a time constant of 0.4 s); when it must rise it uses adaptSpeed
0.9 (about 1.1 s). The constants are named in EV per second, but the shader blends the linear exposure value,
so they are rate constants of that exponential. An eye adapts the same way: a flash of brightness is hard to
look at for less time than it takes to see into a dark room.
Night, space and other worlds
The frame loop drives the limits from the light rather than leaving them fixed. Without a night cap, auto exposure would brighten a moonlit ground up to dusk, so the ceiling eases from 4.0 to 0.5 with day = smoothstep of the sun's current intensity over its full intensity, "so nights read as night and the ground's city lights stand out." The anchor falls with the sun as well, so at night the cap rules. Above the air the rules change, and the comments record each case:
- A spaceship above the atmosphere. The view is mostly black sky, and metered on it the exposure would open right up and burn the sunlit ship white. Out there the weight goes to the anchor alone (blended in over 30–100 km), and the anchor uses the full sun, because the sun's height over a floating frame's horizon means nothing in space: as the frame turns with the re-anchors, the exposure would pulse like a strobe.
- The Moon. No air means no sky to even the light out; metered on the view, the exposure would swing with the camera direction. The Moon always meters on the anchor.
- Mars from the free camera. Metered on the black around the planet, the day half would burn white.
- The ISS ride. The subject is a white station over cloud tops: the anchor is stopped down a further 1 EV, the daylight lift is removed, and the floor drops from 0.35 to 0.05 because the unfiltered sun wants an exposure below the ground's floor.
When Auto exposure is switched off the feature stays in the graph (the tonemap reads its buffer either way) and writes the fixed exposure 1.0, still multiplied by the compensation. The profiler capture puts the pass at 0.027 ms. More on where the sun and sky light come from is in Lighting.
Lens flare and overlays
src/renderer/features/lens_flare_feature.ts · src/shaders/lens_flare.wgsl · explorer/main.ts (~5329–5415, flare visibility ~33076–33094)
The lens flare is drawn from the real sun. The feature places a virtual sun 105 units along the toward-sun direction, projects it, and zeroes the intensity when it is behind the camera. The shader then adds a tight disc and a wide glow (Gaussian and exponential falloffs), an anamorphic horizontal streak, and six tinted ghosts along the line from the sun through the screen center at fixed fractions of that line.
Occlusion uses the depth buffer: a 3×3 grid of depth samples, two pixels apart, around the sun's pixel, each
counting 1 if it is background. The flare fades smoothly as a wing or a building edge crosses the sun, and fades
again as the sun leaves the frame. That test has a blind spot. The planet seen from orbit is painted by the sky
pass and has no depth, so from space the flare would shine straight through the globe. Explorer handles it on
the CPU: it finds the closest approach of the camera-to-sun ray to the body center and fades the flare with
smoothstep(r, r + 30 km, closest).
Registered after the meter and last before the tonemap, the flare is not smeared by motion blur or DoF and does not darken the exposure. Three overlays follow it into the HDR image:
- Wireframe debug. Re-draws the streamed tile and terrain triangle edges in a flat color, depth-tested against the G-buffer so only visible edges show. Off unless chosen in the debug-render menu.
- Collision debug lines. The cooked collision triangles near the aircraft or camera, with a faint x-ray (0.12) where they are hidden.
- Place labels. Screen-space SDF text at 16 px for curated places and area names, revealed in tiers by camera altitude (continents and oceans from deep space, then countries, regions, cities and landmarks on the way down). A tangent-plane horizon test keeps far-side labels off: the camera C is above anchor P's local horizon if C·P > |P|². No distance fade, which on a globe spanning space to ground "would dim every from-space label to nothing".
The tonemap pass
src/renderer/features/tonemap_feature.ts · src/renderer/render_graph/passes/tonemap_pass.ts · src/shaders/tonemap.wgsl · src/shaders/modules/tonemap_curves.wgsl · src/shaders/modules/color_grade.wgsl · explorer/main.ts (sceneGrade ~1530)
One fullscreen pass takes the HDR image to the canvas. In shader order:
- Exposure.
TONEMAP_EXPOSURE1.2 × the Studio look's exposure × the auto-exposure buffer. - Color grade in linear HDR, skipped on pixels whose G-buffer mask carries the ungraded bit.
- Tone curve,
'linear-shoulder', then clamp to [0, 1]. - Contrast-adaptive sharpen (0.5), computed on the curve and applied as a delta.
- 3D LUT and vignette: bound but identity and off in Explorer.
- Encode: sRGB with a triangular dither for an 8-bit canvas, or extended sRGB into the headroom of an HDR display.
The lens-and-film group (distortion, Panini projection, chromatic aberration, grain) shares the pass and is
always bound, but Explorer passes no postFx, so every effect's flag is clear and the shader takes the
plain sampling path.
A linear curve with a shoulder
Explorer does not use the common single-curve ACES fit. That curve has a strong toe and its own contrast and saturation, and it desaturates and hue-shifts bright skies and sunlit cloud tops. Explorer's curve is deliberately boring: slope 1 up to a knee, then an exponential shoulder that meets it with the same slope and approaches 1.
- f′(k)= 1 from both sides, so there is no visible kink; f → 1 as x → ∞
- per channelvery bright colors drift toward white, as film does
The exposure of 1.2 that goes with it is not arbitrary. A metered middle gray lands at 0.18 × 1.2 = 0.216, below the knee, where the curve is the identity: 0.216. That is where the ACES fit at an exposure of 0.85 puts middle gray (0.18 × 0.85 = 0.153 → 0.221), so midtones read the same either way, and auto exposure puts the metered average right at the bottom of the shoulder. The curve was chosen over the ACES fit, the fitted RRT/ODT, the Khronos PBR Neutral operator and AgX by comparing them on cumulus tops, low sun and forest. Because it has no toe, night takes more contrast from the grade.
const SHOULDER_KNEE: f32 = 0.22;
fn linear_shoulder(x: vec3<f32>) -> vec3<f32> {
let k = 1.0 - SHOULDER_KNEE;
let c = max(x, vec3<f32>(0.0));
let s = vec3<f32>(SHOULDER_KNEE) + k * (vec3<f32>(1.0) - exp(-(c - vec3<f32>(SHOULDER_KNEE)) / k));
return select(s, c, c < vec3<f32>(SHOULDER_KNEE));
}
The grade, and why contrast is a power curve
Without a toe the curve contributes no contrast or color, so the look comes from the grade, which runs in
linear HDR after exposure and before the curve. The grade is the engine's color-grading stack (white balance in
LMS, channel mixer, contrast, lift/gamma/gain, shadows/midtones/highlights, split toning, saturation, hue).
Explorer rebuilds its settings every frame in sceneGrade(low, overcast, rain, night), from the
real sun's elevation, the cloud cover between the sun and the camera, the rain, and night. A clear day gets
contrast 1.18, saturation 1.15 and a slight warmth, "a touch more than the scans carry". A low sun is warmer and
richer, with a split tone that cools the shadows. Overcast and rain are flatter, cooler and grayer. Night is
desaturated to 0.6 with contrast 1.2 and kept slightly warm, so sodium street lamps keep their color against
the cool ground; a cool grade on top of the cool night sky light would turn the whole scene navy.
Contrast is not the grade's built-in linear contrast. That scales the distance from middle gray, which drives anything darker than about a tenth of it (the whole night, deep shadows by day) through zero to black. Instead Explorer expresses contrast k as a power curve about middle gray, built from the grade's gain and gamma:
- kthe grade's contrast × the Studio look's contrast; gamma is passed as 1/k, and the shader applies gain then
pow(c, 1/gamma) - 0.18fixed point: middle gray is unchanged, darker values deepen but never clip
Screens that keep their colors
The glass cockpit's displays have colors of their own; graded with the scene, they would shift with the
warmth and saturation of the light of the moment. Each draw carries an 8-bit excludeMask that the G-buffer stores in the emissive
target's alpha; bit 64 (UNGRADED_MASK) marks display screens. The tonemap reads that alpha and skips
the grade where the bit is set. Exposure and the curve still apply, since the screens' brightness already
follows the day.
Sharpen, HDR output and dither
The sharpen (0.5, Effects > EXPOSURE) restores the crispness TAA's resampling softens. It is a contrast-adaptive four-neighbor unsharp mask evaluated on the tone-curved values: the weight per channel is √(min(mn, 1 − mx) / mx) × (−0.125 … −0.2), so it shrinks where local contrast is already high, and edges crispen without ringing. It is computed on the ungraded curve for all five taps and then applied as a delta to the graded center, which keeps the grade intact. The profiler capture puts the tonemap pass at 0.059 ms.
At startup the context tries to configure the canvas as rgba16float, display-p3,
toneMapping: {mode: 'extended'}, and keeps it only if the browser reports extended mode back. When it
does, and the window is on a display matching (dynamic-range: high) (checked every frame, since the
window can move), hdrPeak 4 takes effect. Rather than scale the curve's input, which would darken the
midtones, the SDR result is kept below the point where the curve reaches white, and brighter scene light lifts it
into the headroom:
The result is encoded with an unclamped sRGB curve and no dither. On an ordinary 8-bit canvas the output gets a piecewise sRGB encode (computed in half precision where available, since its input is already in [0, 1]) followed by a triangular-PDF dither of ±1 LSB built from two decorrelated interleaved-gradient-noise samples. The dither breaks up the banding of smooth gradients, most visibly the sky dome, without the noise modulation a uniform dither leaves behind.
Switches, presets and costs
explorer/main.ts (effects ~914–1000, GRAPHICS_PRESETS ~451–476, FlightXr ~36140) · explorer/lib/ui/flight_xr.ts
- aa'taa' (TAA / TAAU / Off). TAAU in the Low preset, TAA otherwise
- renderScale · pixelRatio1 · Auto (≤ 1.2)
- motionBluron, strength 1.0 (off in the Low preset)
- dofoff and hidden; 1,500 m focus, 1,000 m range, 4 px bokeh
- lensBloomon, strength 0.04, dirt 0.5 (0 in the cockpit); thresholded
bloomoff - autoExposureon; min 0.35, max 4.0 day / 0.5 night, anchor weight 0.5
- lensFlareon, intensity 1.0, faded behind a body seen from orbit
- sharpen · hdrPeak0.5 · 4 (used only on an HDR display)
- sceneGradeon; follows sun elevation, cover, rain and night
| Pass | New York, 700 m | Cape Town, clouds |
|---|---|---|
| TAAPass.resolve | 0.071 ms | 0.051 ms |
| TonemapPass | 0.059 ms | 0.058 ms |
| MotionBlurPass | 0.030 ms | 0.027 ms |
| AutoExposurePass | 0.027 ms | 0.028 ms |
| LensFlarePass | 0.024 ms | 0.023 ms |
The timings are from a per-pass timestamp profiler capture (Chrome, 1280×720, desktop GPU). The lens bloom is not in the table; it costs about 0.05 ms. Together the post chain costs a few tenths of a millisecond out of a 3.44 ms frame; the expensive parts of an Explorer frame are geometry, shadows and clouds.
Debug views
The debug-render channels (albedo, normals, AO and so on) set the tone curve to 'none', a clamp, so raw
channels are shown un-toned; only the lit scene uses the shoulder. The heat-haze feature has a debug
flag that tints the plumes red to show where they reach.
References
- B. Karis, “High-Quality Temporal Supersampling”, SIGGRAPH Advances in Real-Time Rendering, 2014. Jittered accumulation, neighborhood clamping, luma-weighted blending, and the brightness-weighted average used in the bloom's first downsample.
- M. Salvi, “An Excursion in Temporal Supersampling”, GDC 2016. Variance clipping: the μ ± γσ box and clipping toward its center.
- L. Pedersen, “Temporal Reprojection Anti-Aliasing in INSIDE”, GDC 2016. Clipping in YCoCg, closest-depth velocity dilation.
- J. Jimenez, “Filmic SMAA: Sharp Morphological and Temporal Antialiasing”, SIGGRAPH Advances in Real-Time Rendering, 2016. The 5-tap bilinear Catmull-Rom history fetch.
- J. Jimenez, “Next Generation Post Processing in Call of Duty: Advanced Warfare”, SIGGRAPH Advances in Real-Time Rendering, 2014. The 13-tap downsample and tent upsample of the bloom chain; interleaved gradient noise.
- K. Narkowicz, “ACES Filmic Tone Mapping Curve”, 2016. The ACES fit that Explorer's tone curve is compared against.
- T. Lottes, “Advanced Techniques and Optimization of HDR Color Pipelines”, GDC 2016. Background on tone curves and display-referred output.
- AMD FidelityFX, “Contrast Adaptive Sharpening (CAS)” and the RCAS pass of its upscaler, 2019–2021. The idea behind both sharpening filters: an unsharp mask whose strength falls with local contrast.
- J. H. Halton, “On the efficiency of certain quasi-random sequences of points in evaluating multi-dimensional integrals”, Numerische Mathematik, 1960. The jitter sequence.
- M. McGuire, P. Hennessy, M. Bukowski, B. Osman, “A Reconstruction Filter for Plausible Motion Blur”, I3D 2012. Background for velocity-buffer motion blur; Explorer's is the simple centered-line gather.