Taos Explorer Technology Launch Taos ExplorerLaunch ↗

Technology / Rendering / 08

Rendering deep dive · 08

Motion, antialiasing and the lens

Chase view behind a small high-wing aircraft over Lower Manhattan, under an overcast cloud deck, with red and green wingtip lights glowing.
Everything after lighting. Chase view over Lower Manhattan. The aircraft is one of the few things in the frame that writes its own motion vectors; every other pixel is reprojected from depth. The glow around the wingtip lights is the lens bloom, the exposure is metered from the scene and the light, and the tone curve leaves the midtones alone.
16 × Halton(2,3)sub-pixel jitter sequence of the TAA resolve
rg16floatvelocity buffer, written only for things that move
64 bins · 16 EVauto-exposure histogram, log2 −10 … +6
knee 0.22linear tone curve, exponential shoulder above it
4 %share of the light the lens bloom scatters, no threshold
64 px / 16 tapsmotion blur reach and samples

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.

Overview

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.

RENDER RESOLUTION Lit HDR sky · clouds · SSR Heat haze only with jet plumes Lens bloom 6-level chain + dirt Rain · snow · glass see deep dive 07 Velocity movers only, rg16float TAA | TAAU resolve (+ upscale) DISPLAY RESOLUTION (WITH TAAU) Motion blur 16 taps, ≤ 64 px Depth of field off by default Auto exposure meter → 1 float Lens flare sun, depth-occluded Overlays wireframe · lines · labels Tonemap grade · curve · sharpen Canvas (SDR or HDR) auto exposure → one float → tonemap
Explorer's post chain in registration order. The dashed line marks where TAAU, when it is the selected antialiasing mode, changes the resolution: everything above it runs at the render size, everything below at the display size. The auto-exposure pass writes no image, only a one-float storage buffer that the tonemap multiplies in.

The order is not the textbook one, and most of its choices are explained by a comment next to the registration:

Motion

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.

Reprojection of one pixel
p = (V P)jit−1 · (2u − 1, 1 − 2v, d, 1)
c′ = (V P)prev · p,   uv′ = (½ + ½ c′x/c′w, ½ − ½ c′y/c′w)
  • (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:

explorer/main.tsTypeScript
// 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:

src/shaders/motion_blur.wgslWGSL
// 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:

src/engine/components/camera.tsTypeScript
// 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.

VP′ = prev VP · T(s), T(s) = pending origin shift (or remap), folded into last frame's matrix once, on the frame of the re-anchor pixel (u, v) depth d jit VP⁻¹ world point p homogeneous VP′ previous uv′ + expected depth history fetch / blur velocity ≠ 0 ? uv′ = uv − Δuv movers only; expected depth = own depth
Where the previous position comes from. Every consumer starts from the depth reprojection; a non-zero velocity sample overrides it for the few objects that move in the world.

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.

Antialiasing

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):

Per-frame jitter, in NDC
k = (n mod 16) + 1,   j = ( (H2(k) − ½)·2/W, (H3(k) − ½)·2/H )
  • Hb(k)radical inverse of k in base b; ±½ pixel after centering
  • W, Hrender-target size; NDC spans 2 units across it
1234 5678 9101112 13141516 one render pixel Halton(2, 3), indices 1–16 each prefix of the sequence is spread evenly over the pixel, so a pixel that loses its history converges again in a handful of frames temporalNoiseIndex = (n mod 64) + 1 shadow and AO noise varies per frame only while the TAA resolve runs
The jitter pattern. The same call that applies the offset also hands the camera a temporal noise index (1–64), so stochastic shading animates its noise only when something is there to integrate 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:

  1. 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.
  2. Pass through if there is no history. On the first frame, after a resize, or after resetHistory(), the current sample goes straight out.
  3. 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.
  4. Reproject. As above, from depth; with a non-zero velocity sample, from uv − Δuv instead. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.

Y (luma) Co min / max μ ± γσ center history clipped clip_aabb() move history toward the box center until it is inside (preserves hue, leaves converged pixels untouched) γ = 1.5 static γ = 0.75 moving the box is a 3D volume in (Y, Co, Cg); Cg not drawn
A two-axis slice of the clip. The outlier samples widen the min/max box; the variance box ignores them. History outside the box is pulled along the line to the center, not clamped per channel.
src/shaders/taa.wgslWGSL
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.

Motion-adaptive, luma-weighted blend
α = 0.03 + 0.22 · √min(1, m / 2)
wc = α / (1 + L(c)),   wh = (1 − α) / (1 + L(h)),   out = (wcc + whh) / (wc + wh)
  • 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
01234 px/frame 00.10.20.3 0.5 px → α ≈ 0.14 blendMoving 0.25 (≈ 4-frame memory) blendStatic 0.03 (≈ 33-frame memory) dashed: a linear ramp
The current-frame weight against motion. 1/α is roughly the number of frames the history remembers. The square-root ramp gets most of the way to the moving weight by half a pixel per frame.

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.

Resolution

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:

KnobWhat it changesWho upscalesDefault
Pixel ratioctx.maxPixelRatio: canvas backing-store pixels per CSS pixel (Auto, 1, 1.5, 2, 3, or the screen's own)browser compositorAuto: the screen's own, at most 1.2
Render scalectx.setPixelRatioScale(0.5…1): shrinks the backing store furtherbrowser compositor100 %
TAAUctx.setRenderScale(0.67): render targets below the canvas sizethe temporal upscaleronly 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:

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.

Pitfall

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.

Camera

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.

Blur vector
v = s · Δuv · (W, H),   v ← v · min(1, 64 / |v|),   out = ¹⁄₁₆ Σi=0..15 C(uv + (i/15 − ½)·v/(W,H))
  • 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.

Cockpit view from a twin-engine aircraft banking over the Hudson River, with the instrument panel below, the right propeller as a blurred disc and Manhattan beyond.
Riding with the camera. In the cockpit the panel is well under a meter from the eye and travels at the aircraft's speed. Its pixels carry recorded velocity, the origin re-anchors every 250 m with the previous model matrices carried across, and the world outside is reprojected from depth.

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.

Signed circle of confusion
c(z) = clamp( (z − zf) / r, −1, 1 ) · R
  • 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.

Before the resolve

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:

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.

HDR W × H ½ ¼ ⅛ 1/16 1/32 1/64 down: 13 taps (five 2×2 boxes); level 0 weights each box by 1/(1+luma) up: level i = tent(level i+1) + down i (×5) composite: mix(scene, halo/6, 0.04) + halo · dirt · excess over 4.0 procedural dirt 512 × 288 900 specks · 40 smudges · 12 streaks
Six half-size levels down, five tent-filtered steps back up, one composite. The rebuilt chain is the sum of all six levels, so the composite divides by the level count before mixing.

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:

src/shaders/lens_bloom.wgslWGSL
// 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."

A small aircraft seen from behind at high altitude over a hazy blue landscape, with the curved horizon and a dark blue sky above, wingtip lights glowing red and green.
High up. Half the frame is dark upper sky. Metered on the view alone, that would open the exposure up; the light anchor (below) keeps the sunlit airframe and ground where daylight puts them. The soft glow around the wingtip lights is the thresholdless bloom.
Metering

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.

Target exposure
ℓa = log2( 0.07 · (Sground + 0.3 S) + 10−4 ),   ℓ̄ = mix(ℓmeter, ℓa, w)
Et = 2c · clamp( 0.18 / 2ℓ̄, Emin, Emax )
E ← E + (Et − E) · (1 − e−k Δt),   k = 2.5 if Et < E, else 0.9
  • S, Sgroundthe sun's intensity, and its share on level ground (× sine of elevation)
  • wanchorWeight 0.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.

02468 s 00.40.81.2 stop down: k = 2.5 (τ 0.4 s) open up: k = 0.9 (τ 1.1 s) target
Simulated at 60 fps with the shader's update rule: the camera turns toward a scene 2.5× brighter, then back. Within a second it has stopped down most of the way; recovering takes about three.

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:

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.

After the meter

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:

Display

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:

  1. Exposure. TONEMAP_EXPOSURE 1.2 × the Studio look's exposure × the auto-exposure buffer.
  2. Color grade in linear HDR, skipped on pixels whose G-buffer mask carries the ungraded bit.
  3. Tone curve, 'linear-shoulder', then clamp to [0, 1].
  4. Contrast-adaptive sharpen (0.5), computed on the curve and applied as a delta.
  5. 3D LUT and vignette: bound but identity and off in Explorer.
  6. 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.

'linear-shoulder', per channel
f(x) = x   (x < k),    f(x) = k + (1 − k)(1 − e−(x − k)/(1 − k))   (x ≥ k),   k = 0.22
  • 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
01234 exposed scene value x 00.51 y = x (clamp only) knee k = 0.22 (≈ 0.18 × 1.2) linear-shoulder ACES fit (Narkowicz)
The curve, plotted from its equation. The ACES fit bends the midtones with its own toe and contrast (0.62 at x = 0.5, against 0.46). The shoulder is the identity below 0.22 and does all of its compressing above it, reaching 0.92 at x = 2 and 0.98 at x = 3.

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.

src/shaders/modules/tonemap_curves.wgslWGSL
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));
}
Interactive · the tone curve against ACES
scene 0.18 → shoulder 0.216 scene 0.18 → ACES 0.221 scene 4.0 → shoulder – scene 4.0 → ACES –
The x axis is scene luminance before exposure, log2 from −6 to +5; the y axis is the display value before sRGB encoding. The strips below the plot show a gray ramp through each curve, sRGB-encoded. With the checkbox on, ACES gets the exposure that puts its middle gray where the shoulder's is (0.85 instead of 1.2): the midtones match, and the difference is in the highlights.

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:

Contrast through gain and gamma
g = 0.18(1 − k)/k,   x′ = (g x)k = 0.18 · (x / 0.18)k
  • 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:

HDR extension
out = sdr · (1 + h · o / (o + h)),   h = peak − 1 = 3,   o = max(L(x) − 1, 0)

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.

Lower Manhattan from above in a cool, desaturated light, with deep shadows between the towers and dark water on both sides.
The grade carries the look. Lower Manhattan in a cool, low-saturation light. With no toe in the curve, the depth in the shadows comes from the grade's power-curve contrast about middle gray, which deepens the darks without clipping them.
Reference

Switches, presets and costs

explorer/main.ts (effects ~914–1000, GRAPHICS_PRESETS ~451–476, FlightXr ~36140) · explorer/lib/ui/flight_xr.ts

PassNew York, 700 mCape Town, clouds
TAAPass.resolve0.071 ms0.051 ms
TonemapPass0.059 ms0.058 ms
MotionBlurPass0.030 ms0.027 ms
AutoExposurePass0.027 ms0.028 ms
LensFlarePass0.024 ms0.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.

Further reading

References

  1. 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.
  2. M. Salvi, “An Excursion in Temporal Supersampling”, GDC 2016. Variance clipping: the μ ± γσ box and clipping toward its center.
  3. L. Pedersen, “Temporal Reprojection Anti-Aliasing in INSIDE”, GDC 2016. Clipping in YCoCg, closest-depth velocity dilation.
  4. J. Jimenez, “Filmic SMAA: Sharp Morphological and Temporal Antialiasing”, SIGGRAPH Advances in Real-Time Rendering, 2016. The 5-tap bilinear Catmull-Rom history fetch.
  5. 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.
  6. K. Narkowicz, “ACES Filmic Tone Mapping Curve”, 2016. The ACES fit that Explorer's tone curve is compared against.
  7. T. Lottes, “Advanced Techniques and Optimization of HDR Color Pipelines”, GDC 2016. Background on tone curves and display-referred output.
  8. 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.
  9. J. H. Halton, “On the efficiency of certain quasi-random sequences of points in evaluating multi-dimensional integrals”, Numerische Mathematik, 1960. The jitter sequence.
  10. 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.