2026-12-02 · devlog

Reversed-Z + Infinite Far: Planetary-Scale Depth in WebGPU

Reversed-Z + Infinite Far in WebGPU: flat 24-bit depth32float precision from 0.1 m to planetary orbit

Why Pinionfall ripped out manual frag_depth logarithmic depth for hardware Reversed-Z + Infinite Far (depth32float) in WebGPU: exact IEEE-754 precision math, Early-Z recovery, every pipeline flip, and five real compromises.

If you have ever built a 3D engine with large view distances (open worlds, flight sims, or seamless multi-planet games like Pinionfall where a single camera sees both a grass blade 15 cm from your boots and an asteroid belt 2,000 kilometers out in orbit), you eventually hit the same brick wall: the depth buffer runs out of precision and distant geometry turns into a flickering Z-fighting soup.

Pinionfall originally solved that with a classic trick: a logarithmic depth buffer written manually via @builtin(frag_depth). It kept planets and settlements Z-fighting-free, so we left it alone while building the rest of the game.

Now that all the pieces of Pinionfall are working together and we are doing our December top-to-bottom WebGPU overhaul (currently landing on our overhaul branch ahead of the next release), Reversed-Z + Infinite Far Plane (depth32float) is one of the very first foundational upgrades we landed.

Here is the complete, practical breakdown of how Reversed-Z actually works, why it feels like an IEEE-754 cheat code, what it improves and what it compromises, and every single flip and trap you need to watch for in WebGPU.

1. The Problem: Perspective Projection Wastes Almost All of Your Depth Buffer

In a standard perspective camera, clip-space depth is divided by view-space distance z. In WebGPU’s [0, 1] clip-space depth convention (the same as Direct3D 12, Metal, and Vulkan):

d_std(z) = f · (z - n) / (z · (f - n))

Plug in near = 0.1 m and far = 100,000 m:

Now look at what happens when you store that value in a 32-bit floating-point depth buffer (depth32float).

IEEE-754 floats are not evenly spaced. Every power-of-two band ([0.5, 1], [0.25, 0.5], [0.125, 0.25], and so on) holds the exact same 8,388,608 floats (2^23), so roughly 99.2% of all floats in [0, 1] (~1.06 billion values) sit below 0.5. They get exponentially denser toward 0.0 and are sparsest near 1.0.

In Standard-Z, you pack everything beyond 20 centimeters next to 1.0 (where float32 is sparsest) and hand over a billion (~1.06 billion) tiny float values below 0.5 to the ten centimeters right in front of your camera.

Depth buffer precision across 8 orders of magnitude: smallest resolvable depth step from 0.1 m to 10,000 km orbit

Look at the yellow and red curves above (computed from exact IEEE-754 adjacent-ULP math, near = 0.1 m, far = 100 km):

2. The Classic Band-Aid (What Pinionfall Used Before): Logarithmic Depth

To survive planetary distances (0.1 m up to 2,000 km), Pinionfall, like Outerra and many space engines before it, originally computed a logarithmic depth curve manually:

// Legacy log-depth: fixes per-vertex chord error, but disables Early-Z & Hi-Z!
@fragment
fn fs_main(in: VertOut) -> FragOut {
var out: FragOut;
let log_z = log(max(in.clip_w * frame.log_depth_fc + 1.0, 1.0))
/ log(frame.log_depth_far * frame.log_depth_fc + 1.0);
out.frag_depth = clamp(log_z, 0.0, 1.0);
// ... shade G-buffer / material ...
return out;
}

On the precision chart, log-depth looks great (purple dotted curve). So why did we rip it out?

Because logarithmic depth traps you in a catch-22 with four real costs:

  1. Per-vertex log depth causes chord error; fixing it per pixel kills Hardware Early-Z and Hi-Z. Computing log depth in the vertex shader lets hardware linearly interpolate a curved log(z) function across screen space, bending long triangles away from their true geometric plane (chord error). Moving log() into the fragment shader via @builtin(frag_depth) eliminates that chord error, at the cost of forcing the GPU into Late-Z: the hardware can no longer know a fragment’s depth before running the fragment shader, so occluded pixels behind buildings, hills, trees, and rocks still shade before getting discarded. In Pinionfall, 22+ mesh and transparent shaders were writing custom @builtin(frag_depth).
  2. We had to build a manual software Early-Z pass just to cope. Because rock meshes wrote @builtin(frag_depth) and lost hardware Early-Z, roughly 60% of every rock planted in the ground (plus rocks behind trunks and terrain) was shading only to fail the late depth test. We maintained a separate compute pass, ground-depth-pass (a half-resolution conservative depth snapshot costing +8.3 MB VRAM at 4K), solely so the rock shader could hand-cull hidden fragments in software.
  3. Expensive depth reconstruction everywhere. Every depth-reading pass (SSAO, SSR, contact shadows, water refraction, decals, clouds, TAA/TSR) had to decode log depth with exp() instead of a single division.
  4. No free hardware Hi-Z acceleration across standard opaque geometry until manual frag_depth is removed.

3. The Cheat Code: Reversed-Z + Infinite Far Plane

Flip the projection matrix so near maps to 1.0 and far maps to 0.0. Then take the limit as far -> ∞:

d_rev(z) = n / z

Look at what happens to the float32 mantissa bands:

Every single doubling of distance gets its own dedicated 23-bit mantissa.

Hyperbolic 1/z perspective compression and IEEE-754 floating-point spacing cancel each other out, giving you an almost perfectly flat ~24-bit quasi-logarithmic depth buffer completely in fixed-function hardware, with zero chord error (because clip.z / clip.w = near / z is affine in 1/w, so hardware interpolation is exact) and zero manual @builtin(frag_depth) writes on standard meshes.

How Reversed-Z cancels perspective nonlinearity by aligning 1/z with IEEE-754 float32 mantissa bands

Check the exact adjacent-ULP depth steps (near = 0.1 m, depth32float, with band worst-case z · 2^-23 in parentheses):

And because hardware Early-Z and Hi-Z turn back on across our standard opaque and translucent mesh shaders (keeping manual @builtin(frag_depth) strictly on ray-offset impostors and carved snow-contact recesses), fragments behind already-drawn foreground geometry are rejected before the fragment shader runs.

Before and after GPU pipeline diagram showing Early-Z and Hi-Z recovery with Reversed-Z

The immediate wins we landed on our overhaul branch:

4. How to Implement Reversed-Z + Infinite Far in WebGPU (5-Minute Checklist)

In a right-handed camera looking down -Z with WebGPU’s [0, 1] NDC depth range:

// Right-handed Infinite Reversed-Z projection matrix (column-major for WGSL)
export function perspectiveInfiniteReversedZ(
out: Float32Array,
fovYRad: number,
aspect: number,
near: number,
): Float32Array {
const f = 1.0 / Math.tan(fovYRad * 0.5);
out.fill(0);
out[0] = f / aspect;
out[5] = f;
out[10] = 0; // P[2][2] = 0 (far -> infinity maps to 0.0!)
out[11] = -1; // w_clip = -z_view
out[14] = near; // P[3][2] = near (z = -near maps to 1.0!)
return out;
}

Then flip your WebGPU render pipeline and shader conventions everywhere scene depth is touched:

  1. Depth attachment format: 'depth32float' (never depth24plus, see compromises below).
  2. Depth clear value: depthClearValue: 0.0 (sky/background is now 0.0).
  3. Depth test comparator: 'greater' or 'greater-equal' (closer objects have larger depth values).
  4. Polygon offset / depthBias: flip the sign (depthBias: -k, depthBiasSlopeScale: -s).
  5. Sky / miss test: if (d <= 0.0) { /* sky */ } instead of d >= 0.99999 (and if you guard division with a clamp, use a tiny floor like max(d, 1e-30), never 1e-7, which clamps everything past 1,000 km).
  6. Hi-Z pyramid & occlusion culling: in Reversed-Z, the conservative farthest depth in a 2x2 block is min(d00, d10, d01, d11) (not max), and an object’s bounding box is occluded only when its nearest corner satisfies box.maxZ < hizMinZ.
  7. Depth-offset impostors: only keep @builtin(frag_depth) on genuine ray-offset billboards/impostors (or carved snow-contact recesses), and write frame.near / max(linear_z, frame.near).
WebGPU Reversed-Z and Infinite Far developer cheat sheet with matrix, pipeline flips, and five traps

5. Honest Engineering: What Are the Compromises & Gotchas?

Every graphics technique has trade-offs. Reversed-Z is as close to a free lunch as rendering gets, provided you respect five real constraints:

  1. It requires depth32float. Do not pair Reversed-Z with depth24unorm or depth24plus. Integer depth formats have uniform precision from 0 to 1, so reversing them gives zero precision gain. Most GPUs already pad 24-bit depth to 32 bits in memory anyway, so depth32float usually uses the same 4 bytes/pixel (the real extra cost only shows up if you also require stencil via depth32float-stencil8, which commonly uses 8 bytes/pixel depending on hardware; skip stencil unless you truly need it).
  2. Orthographic shadow maps do not benefit. Orthographic projections (like directional sun CSM cascades) already distribute depth linearly. Reversing an orthographic map into depth32float does not improve worst-case precision: it simply piles unused float density at the far edge and shifts the coarser steps toward the light. Keep orthographic CSM cascades in standard [0, 1] (and note that perspective spot/point shadow maps are a separate case, where short-range standard [0, 1] or depth16unorm maps are typically plenty).
  3. It does not fix world-space float32 vertex jitter. Reversed-Z solves depth-buffer quantization, not world-coordinate rounding. If your camera is 800 km from the origin, you still need camera-relative / eye-relative coordinates (subtracting camera position on the CPU in float64 before uploading transforms to the GPU, which Pinionfall already does in eye-relative.ts).
  4. Watch out for division by zero on sky pixels (d == 0.0). With an infinite far plane, every sky texel stores exact 0.0. Every screen-space pass (ambient occlusion, SSR, volumetric effects, decals, temporal velocity dilation) must explicitly early-out on d <= 0.0 (or use a tiny floor like max(d, 1e-30)) before evaluating near / d so you never inject Inf/NaN into temporal history buffers.
  5. Replacing finite far-plane assumptions in legacy shaders. If any legacy shader assumed far was finite (for example, computing normalized [0, 1] fog distance from raw depth instead of linear view distance, or unprojecting frustum corners at ndc.z = 0.0 where infinity now lives), it needs to switch to linear_z = near / d and unproject at ndc.z = 1.0 instead.

Why We Implemented It Right at the Start of the Overhaul

Every major rendering upgrade we have planned on the roadmap (occlusion culling, ambient occlusion, lighting, atmosphere, reflections, water, and transparency) reads from the scene depth buffer.

Building any of those on top of legacy @builtin(frag_depth) logarithmic depth would mean baking exp() reconstructions, Late-Z stalls, and software Early-Z workarounds into every new shader, only to rewrite them all later. Starting the overhaul with Infinite Reversed-Z gives the entire renderer a clean foundation from Day 1:

If you are starting a new WebGPU, Vulkan, Metal, or DX12 renderer today, make Reversed-Z + Infinite Far (depth32float) your default from Line 1. You will never miss the far plane.

Primary References & Further Reading


Play Pinionfall free in your browser (WebGPU) at pinionfall.com, follow the overhaul on the roadmap, or inspect the full engine source licence.

← all posts