Algorithm Search⌘K

Algorithmadvanced

Screen-space reflections

Also called SSR.

March the reflected ray through the depth buffer in screen space, perspective correct, and reuse the shaded color at the hit. Off-screen and hidden surfaces fall back to an environment map.

Time
O(p n) worst
Space
O(p) extra
Where
n = the number of steps per ray; p = the number of pixels that reflect
Properties
deterministicnot in placeofflineiterative
Origin
Morgan McGuire, Michael Mara, 2014

Screen-space reflections find the reflected color of a pixel with the pictures that the renderer already has. These are the depth buffer and the shaded image of the current frame. From the visible point, the method follows the reflected ray across the screen and compares the depth of the ray with the depth buffer at each pixel. If the ray goes behind a surface there, that pixel is the hit, and its shaded color is the reflection. The method can only see what is on the screen. A ray that leaves the screen, or that passes behind a surface with no hit, uses a fallback, usually an environment map. McGuire and Mara (2014) gave the march that most renderers use. It projects both ends of the ray and steps one pixel at a time, and it gets the depth correct for perspective.

In plain words

A wet floor shows the room above it. To draw that, start at a floor pixel, bounce the view ray off the floor and follow the bounced ray. Do not follow it through the 3D scene. Follow its picture on the screen, from one pixel to the next. At each pixel, compare two depths: the depth of the ray at that point, and the depth stored in the depth buffer. When the ray goes a little behind what the camera sees there, the ray has hit that surface, so copy its color. When the ray leaves the picture, the screen has no answer, so take the color from a sky or room map.

The problem

The input is the depth buffer DD and the shaded color of a frame, and the normals of the reflecting pixels, for example from a G-buffer. The output is, for each reflecting pixel, the color seen along the mirror direction r=w−2(w⋅n) nr = w - 2 (w \cdot n)\, n of the view direction ww. The depth buffer stores one surface per pixel, so the scene is unknown behind it. The method takes every pixel as a slab of the thickness τ\tau behind its visible surface.

The camera looks along −z-z, and a point pp has the depth d=−pzd = -p_z. The pixel (i,j)(i, j) has its center at (i+12,j+12)(i + \tfrac12, j + \tfrac12) with jj counted from the bottom. The view ray through the screen point (sx,sy)(s_x, s_y) has the slopes u=(2sx/W−1) atan⁡θu = (2 s_x / W - 1)\, a \tan\theta and v=(2sy/H−1)tan⁡θv = (2 s_y / H - 1) \tan\theta, with the aspect ratio a=W/Ha = W/H. The visible point of a pixel is d (u,v,−1)d\,(u, v, -1).

The algorithm

  1. TRACE(D, o, r, ℓ, τ)
  2. 1if the end o + ℓ r is nearer than the near plane: shorten ℓ so that it is on it
  3. 2(x0, y0, k0) ← project(o); (x1, y1, k1) ← project(o + ℓ r); Q0 ← k0 o; Q1 ← k1 (o + ℓ r)
  4. 3if |y1 - y0| > |x1 - x0|: swap the roles of x and y
  5. 4each step: x ← x ± 1; y, Q, k ← y + dy, Q + dQ, k + dk
  6. 5if (x, y) is off the screen: return MISS
  7. 6if the depth range of the ray across this step overlaps [D(x, y), D(x, y) + τ]: return the pixel and Q / k
  8. 7if x is past x1: return MISS
  9. 8REFLECTION(q) = the color at TRACE(D, the point of q, r, ℓ, τ), or the environment in the direction r on a MISS

Project once, step in 2D (lines L2 to L4). Both ends of the ray are projected. The march then moves one pixel along the longer screen axis per step, and the other screen coordinate grows by a constant amount. The code does not step the depth. It steps k=1/dk = 1/d and Q=p/dQ = p/d, because these two are affine along the screen image of a 3D line, and the depth itself is not. So each step has the exact depth of the 3D point that projects there, and the point Q/kQ/k is on the ray.

The hit test (line L6). The depth of the ray across a step runs from its value half a step back to its value half a step on. A hit is a range that reaches the stored depth DD and is not more than τ\tau behind it. A small τ\tau lets rays pass behind thin objects. A large τ\tau makes thin objects into walls.

The near plane (line L1). A ray that points toward the camera would cross d=0d = 0, where the projection breaks. The ray is cut at the near plane first.

The fallback (line L8). A ray that misses reads an environment map in the direction rr. Renderers also fade the reflection near the edges of the screen and for rays that point toward the camera, so that the switch to the fallback is not seen. That fade is tuning.

Example

The camera has 64×4864 \times 48 pixels, tan⁡θ=0.5\tan\theta = 0.5 and the near plane at 0.1. The room has a floor at y=−1y = -1, a back wall at the depth 12 whose top edge is at y=3y = 3, and a plate that faces the camera at the depth 6 for −1.5≤x≤0-1.5 \le x \le 0 and −1≤y≤0.5-1 \le y \le 0.5. The floor is a mirror with n=(0,1,0)n = (0, 1, 0), and τ=0.3\tau = 0.3.

floor pixel its depth the code finds the exact reflected ray
(20, 5) 2.595 the plate at (-1.4375, 0.3125, -6) meets the plate at (-1.4375, 0.3125, -6)
(45, 8) 3.097 the wall at (3.375, 1.875, -12) meets the wall at (3.375, 1.875, -12)
(28, 3) 2.341 no hit, so the environment passes the wall plane at y=3.125y = 3.125, above the top edge

Of the 1232 floor pixels, 832 reflect the wall, 144 reflect the plate and 256 go to the environment. The points are exact to the rounding of the floating-point numbers, as the proof says. For the pixel (28, 3), screen space gets the correct answer for the wrong reason. The ray goes past the top of the wall, leaves the screen and falls back. If the room had a ceiling above the screen, the screen still could not show it.

Correctness

The proofs folder has the proofs. For a 3D segment with the ends oo and ee, put λ=t de/d(t)\lambda = t\, d_e / d(t). Then 1/d=(1−λ)/do+λ/de1/d = (1 - \lambda)/d_o + \lambda/d_e and p/d=(1−λ) o/do+λ e/dep/d = (1 - \lambda)\, o/d_o + \lambda\, e/d_e. The screen coordinates are affine in λ\lambda too. So kk and QQ are affine in the screen coordinate of the major axis, and constant increments give their exact values at every step. The depth is monotone along the step, so the range of a step is the range between its two half-step ends, and the steps follow one another with no gaps. The result is then the first visited pixel whose slab [D,D+τ][D, D + \tau] meets the ray. A miss means that the ray left the screen or reached its end first. The march tests one pixel per unit of the major axis, so it can be one pixel off from a march that tests every pixel the ray crosses. The tests check the identities at random points. They also compare 40 reflections with a fine 3D march: hit or miss agrees every time, and the hit pixels agree to within one pixel. That the hits are the scene's true reflections is not a theorem. It is true only where the slabs match the real objects and the reflected surface is on the screen.

Proof: The perspective-correct march of screen-space reflections and what its hits meanfull

Setting. The camera is at the origin and looks along −z-z. A point pp has the view depth d=−pzd = -p_z, and for d>0d > 0 it projects to sx=(pxk/(atan⁡θ)+1) W/2s_x = (p_x k / (a \tan\theta) + 1)\, W/2 and sy=(pyk/tan⁡θ+1) H/2s_y = (p_y k / \tan\theta + 1)\, H/2 with k=1/dk = 1/d, as in the code. The depth buffer DD gives one depth per pixel, or none for the background. The ray starts at the visible point oo of a pixel and has the direction rr and the length ℓ\ell. A pixel with the depth DD counts as a hit for a ray piece with the depths [rmin⁡,rmax⁡][r_{\min}, r_{\max}] if rmax⁡≥Dr_{\max} \ge D and rmin⁡≤D+τr_{\min} \le D + \tau. That is, every pixel is taken as a slab of thickness τ\tau behind its visible surface.

Lemma 1 (the near plane). After line L1, every point of the segment from oo to e=o+ℓre = o + \ell r has a depth of at least min⁡(do,n)\min(d_o, n), where nn is the near distance. So the projection is defined on the whole segment, and k>0k > 0 on it.

Proof. The depth is affine along the segment, so it is at least the smaller of its two end values. If ee would be nearer than nn, line L1 shortens the segment so that ee has the depth nn exactly. □\square

Without this clip, a ray that points toward the camera can pass through d=0d = 0. There kk changes sign, and the projected segment is not the image of the 3D segment.

Lemma 2 (homogeneous interpolation). Let p(t)=(1−t) o+t ep(t) = (1 - t)\, o + t\, e for t∈[0,1]t \in [0, 1], with the depths d(t)>0d(t) > 0, and put k0=1/dok_0 = 1/d_o, k1=1/dek_1 = 1/d_e, Q0=k0oQ_0 = k_0 o and Q1=k1eQ_1 = k_1 e. Put λ=t de/d(t)\lambda = t\, d_e / d(t). Then λ\lambda runs over [0,1][0, 1] increasingly with tt, and

1d(t)=(1−λ)k0+λk1,p(t)d(t)=(1−λ)Q0+λQ1.\frac{1}{d(t)} = (1 - \lambda) k_0 + \lambda k_1, \qquad \frac{p(t)}{d(t)} = (1 - \lambda) Q_0 + \lambda Q_1.

The screen coordinates sxs_x and sys_y of p(t)p(t) are also affine in λ\lambda.

Proof. Because d(t)=(1−t)do+tded(t) = (1 - t) d_o + t d_e, we have 1−λ=(1−t)do/d(t)1 - \lambda = (1 - t) d_o / d(t). Then (1−λ)Q0+λQ1=((1−t)o+te)/d(t)=p(t)/d(t)(1 - \lambda) Q_0 + \lambda Q_1 = ((1 - t) o + t e) / d(t) = p(t)/d(t), and (1−λ)k0+λk1=((1−t)+t)/d(t)=1/d(t)(1 - \lambda) k_0 + \lambda k_1 = ((1 - t) + t)/d(t) = 1/d(t). The derivative of λ\lambda in tt is dode/d(t)2>0d_o d_e / d(t)^2 > 0. Last, sxs_x is an affine function of the xx coordinate of p/dp/d, and sys_y of its yy coordinate, so both are affine in λ\lambda. □\square

This is the identity behind perspective-correct interpolation, used in the other direction. The tests check it at random points to 10−910^{-9}.

Theorem 1 (the march is exact). Let the projected segment not be a point, and let uu be its major screen axis (line L3). At every step, the values kk and QQ of the code are 1/d1/d and p/dp/d of the point pp of the 3D segment that projects to the current screen position (px,py)(p_x, p_y), apart from rounding. The reported point Q/kQ/k lies on the 3D ray.

Proof. By Lemma 2, sus_u is affine in λ\lambda and not constant, so λ\lambda is affine in sus_u. The other screen coordinate, kk and QQ are then affine in sus_u as well. An affine function grows by the same amount for every unit step of its argument. Line L4 adds these amounts (dydy, dQdQ and dkdk of the code) for each unit step of sus_u, starting from the exact values at oo, so by induction the values at step mm are the affine functions at su=x0+ms_u = x_0 + m. Then Q/k=(p/d) d=pQ/k = (p/d)\, d = p. □\square

A march that interpolates the depth dd itself in screen space, or a march that takes equal steps along the 3D ray, does not have this property. The first gets wrong depths. The second puts many steps in one pixel near the camera and skips pixels far away.

Lemma 3 (the depth ranges cover the march). The depth 1/k1/k is monotone in sus_u. Step mm tests the depth range of the ray over the part of the segment with sus_u between x0+m−1/2x_0 + m - 1/2 and x0+m+1/2x_0 + m + 1/2. For the first step, the lower end is x0x_0. These parts follow one another without gaps or overlaps.

Proof. kk is affine in sus_u and positive, so 1/k1/k is monotone. A monotone function takes its extreme values on an interval at the ends. The code keeps the depth at the end of the previous part as the start of the next one (prev_d). The end of a part is 1/(k+dk/2)1/(k + dk/2), which is exact by Theorem 1, because k+dk/2k + dk/2 is the affine value half a step on. □\square

Theorem 2 (what the result means). Let (im,jm)(i_m, j_m) be the pixel that holds the screen position of step mm. trace returns a hit at step mm exactly when these conditions are true:

  • Steps 11 to mm are on the screen.
  • Steps 11 to mm are not past the end of the projected segment.
  • Step mm is the first step at which the depth range of Lemma 3 overlaps the slab [D,D+τ][D, D + \tau] of the pixel (im,jm)(i_m, j_m).

The returned point is the point of the 3D ray at the center of the part. trace returns no hit when the march leaves the screen (line L5), reaches the end of the segment (line L7) or runs out of steps, and none of the earlier steps was a hit.

Proof. This follows from the order of the tests in the loop, Lemma 3 and Theorem 1. □\square

The march visits one pixel per unit of the major axis, the pixel of the center of the part. With a slope of up to 1 on the minor axis, the part can also touch the next pixel on that axis, and that pixel is not tested. So the hit pixel can differ by one pixel from a fine 3D march that tests every pixel the ray crosses. A conservative march that visits every pixel the line crosses would test both. That costs up to twice the steps. The tests compare the code with a fine 3D march on 40 reflections off the floor of a small room. Hit or miss agrees every time, and the hit pixels agree to within one pixel.

What is not a theorem. Theorem 2 describes the intersection of the ray with the depth buffer read as slabs of the thickness τ\tau. This is not the intersection with the scene.

  • The real objects can be thinner or thicker than τ\tau. A ray behind an object then gives a false hit or passes through it.
  • Surfaces that are hidden or off the screen are not in DD at all.
  • A ray that starts exactly on a flat surface overlaps the slab of the next pixel of the same surface. The caller must move the origin off the surface or skip the first pixels.

The tests show each case in a scene they can solve exactly. With τ=∞\tau = \infty, a ray at depth 9 behind a plate at depth 6 hits the plate. With τ=0.5\tau = 0.5 it misses. How good the reflections look in real scenes is a measurement.

Theorem 3 (cost). A call of trace takes at most min⁡(c,max⁡(W,H)+1)\min(c, \max(W, H) + 1) steps of O(1)O(1) work, where cc is the step limit. So an image of pp pixels with one ray each costs O(pn)O(p n), where nn is the number of steps per ray.

Proof. Each step moves the screen position by one unit along the major axis, and the march stops at the first position that is off the screen. The origin is a visible pixel, so this takes at most one more step than the length of the screen along that axis. □\square

Complexity

The model is the real RAM. Each step costs O(1)O(1), and a ray takes at most max⁡(W,H)+1\max(W, H) + 1 steps before it leaves the screen, or fewer with a step limit or a short ray. So pp reflecting pixels with nn steps each cost O(pn)O(p n). The extra memory is the reflection image, O(p)O(p). On a GPU the cost is the number of depth reads. Renderers lower nn with a stride of several pixels and a refinement near the hit, or with a hierarchical Z-buffer that skips empty regions.

Properties

  • Perspective correct. The depth along the march is exact, because 1/d1/d and p/dp/d are affine in screen space.
  • One pixel per step. The march takes no more than one step per pixel on the major axis, and it does not skip pixels on that axis.
  • Screen bound. The march has only what is on the screen and in front. Off-screen and hidden surfaces give misses or wrong hits.
  • Thickness is a guess. One depth layer does not say how thick an object is. The value τ\tau is tuning.
  • Reuses the frame. The reflected color is the color that was already shaded, with its lighting from the view of the camera.
  • No scene data. The method needs no acceleration structure and no geometry, only the buffers of the frame.

Variants and improvements

  • Stride and refinement. Step several pixels at a time, and on a hit, search back by bisection. This makes fewer reads, but the method can now jump over thin objects.
  • Hierarchical tracing. March a min-depth pyramid of the depth buffer, and move up a level where the ray is in front of the whole cell. This takes long steps over empty space.
  • Glossy reflections. Sample several directions from a microfacet BRDF per pixel, or blur the hit colors by the cone width. Then filter over time and space.
  • Back-face and thickness buffers. Render the back faces to a second depth buffer. Then each pixel has a real thickness in place of a constant τ\tau.
  • Blend with other sources. Fall back to local reflection probes or image-based lighting, and weight the result with the Fresnel equations.
  • Previous frame. Read the hit color from the last frame, reprojected. This adds one bounce and avoids a second shading pass.

When to use it

Use screen-space reflections for floors, water and other surfaces that reflect objects which are also on the screen, at a cost close to one depth march per pixel. It fits a deferred renderer, which has the depth and normals in buffers. Do not use it alone for mirrors that face the camera, because their reflected rays point back toward the camera, out of the screen. Do not use it alone where the reflected objects are off screen or hidden. Use ray traced reflections or planar reflection passes there, and keep an environment map as the fallback in any case.

Pitfalls

  • Self-hits. A ray that starts exactly on a flat surface overlaps the slab of the next pixel of the same surface. Move the origin a little off the surface, or skip the first steps.
  • Linear depth in screen space. Interpolating dd, not 1/d1/d, gives wrong depths that grow with the depth range of the ray.
  • No near-plane clip. A ray toward the camera crosses d=0d = 0, and its projection wraps around the screen.
  • A ray that projects to a point. A ray along the view ray of its own pixel has no screen length. Treat it as a miss or give it a small screen length.
  • Edges of the screen. Reflections stop abruptly where the rays leave the screen. Fade the result near the edges and near the camera direction.
  • Stretched hits. Behind thin objects, a large τ\tau gives streaks of the object's color, and a small one lets rays slip through gaps between steps.
  • Rough surfaces. One mirror ray per pixel on a rough surface gives noise, and the denoiser must respect depth edges.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

screen_space_reflections.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/screen-space-reflections/. The authors are listed in prov/4JP2C2.jsonl.

"""Screen-space reflections: a perspective-correct DDA through the depth buffer.

The camera is at the origin and looks along -z with a perspective projection.
The view depth of a point p is d = -p_z > 0. The screen has W x H pixels, the
pixel (i, j) has its center at (i + 1/2, j + 1/2) with j counted from the
bottom, and a point with depth d projects to

    s_x = (p_x / (d a tan(theta)) + 1) W / 2,   s_y = (p_y / (d tan(theta)) + 1) H / 2

with a = W / H. D[j][i] is the depth buffer, None for the background.

The march follows the method of McGuire and Mara (2014): project both ends of
the ray, step one pixel at a time along the major screen axis, and
interpolate k = 1/d and Q = p/d linearly in screen space, which is exact for a
3D line. A pixel is a hit if the depth range of the ray across that pixel
overlaps [D, D + thickness]. A ray that leaves the screen or reaches its end
is a miss, and the caller falls back to an environment map.
"""

import math
from typing import List, Optional, Sequence, Tuple

Vec = Tuple[float, float, float]
Grid = List[List[Optional[float]]]


class Camera:
    def __init__(self, width: int, height: int, tan_half: float, near: float) -> None:
        self.width, self.height = width, height
        self.tan_half = tan_half
        self.aspect = width / height
        self.near = near

    def project(self, p: Vec) -> Tuple[float, float, float]:
        """Screen position (s_x, s_y) and k = 1/d of a point in front of the camera."""
        k = -1.0 / p[2]
        sx = (p[0] * k / (self.aspect * self.tan_half) + 1) * self.width / 2
        sy = (p[1] * k / self.tan_half + 1) * self.height / 2
        return sx, sy, k

    def pixel_ray(self, sx: float, sy: float) -> Vec:
        """The point at depth 1 on the view ray through a screen position."""
        u = (2 * sx / self.width - 1) * self.aspect * self.tan_half
        v = (2 * sy / self.height - 1) * self.tan_half
        return (u, v, -1.0)


def reflect(dirn: Vec, n: Vec) -> Vec:
    dn = sum(a * b for a, b in zip(dirn, n))
    return tuple(a - 2 * dn * b for a, b in zip(dirn, n))


def trace(
    D: Grid,
    cam: Camera,
    origin: Vec,
    dirn: Vec,
    max_dist: float,
    thickness: float,
    max_steps: int = 10000,
):
    """Return (i, j, point) of the first hit, or None for a miss."""
    length = max_dist
    if origin[2] + dirn[2] * length > -cam.near:  # @line L1
        length = (-cam.near - origin[2]) / dirn[2]
    end = tuple(o + t * length for o, t in zip(origin, dirn))
    x0, y0, k0 = cam.project(origin)  # @line L2
    x1, y1, k1 = cam.project(end)
    Q0 = tuple(c * k0 for c in origin)
    Q1 = tuple(c * k1 for c in end)
    if (x1 - x0) ** 2 + (y1 - y0) ** 2 < 1e-8:
        x1 += 0.01
    steep = abs(y1 - y0) > abs(x1 - x0)  # @line L3
    if steep:
        x0, y0, x1, y1 = y0, x0, y1, x1
    sgn = 1.0 if x1 > x0 else -1.0
    inv = sgn / (x1 - x0)
    dy = (y1 - y0) * inv
    dQ = tuple((b - a) * inv for a, b in zip(Q0, Q1))
    dk = (k1 - k0) * inv
    px, py, Q, k = x0, y0, Q0, k0
    prev_d = 1.0 / k0
    for _ in range(max_steps):
        px, py = px + sgn, py + dy  # @line L4
        Q = tuple(a + b for a, b in zip(Q, dQ))
        k = k + dk
        if (px - x1) * sgn > 0:
            return None  # the end of the ray  # @line L7
        next_d = 1.0 / (k + 0.5 * dk)
        rmin, rmax = min(prev_d, next_d), max(prev_d, next_d)
        prev_d = next_d
        sx, sy = (py, px) if steep else (px, py)
        i, j = int(math.floor(sx)), int(math.floor(sy))
        if not (0 <= i < cam.width and 0 <= j < cam.height):  # @line L5
            return None
        scene = D[j][i]
        if scene is not None and rmax >= scene and rmin <= scene + thickness:  # @line L6
            return i, j, tuple(c / k for c in Q)
    return None


def reflection(D: Grid, color: Sequence[Sequence], cam: Camera, i: int, j: int, normal: Vec, environment, max_dist: float, thickness: float):
    """The reflected color of pixel (i, j): the color at the hit, or the
    environment in the reflected direction on a miss."""
    d = D[j][i]
    view = cam.pixel_ray(i + 0.5, j + 0.5)
    origin = tuple(c * d for c in view)
    L = math.sqrt(sum(c * c for c in view))
    r = reflect(tuple(c / L for c in view), normal)
    hit = trace(D, cam, origin, r, max_dist, thickness)
    if hit is None:
        return environment(r)  # @line L8
    return color[hit[1]][hit[0]]
test_screen_space_reflections.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/screen-space-reflections/. The authors are listed in prov/4JP2C2.jsonl.

"""Screen-space reflections in a small analytic room."""

import math
import random

from screen_space_reflections import Camera, reflect, reflection, trace

CAM = Camera(64, 48, 0.5, 0.1)
TAU = 0.3


def scene_hit(w):
    """Depth and label of the view ray through the depth-1 point w."""
    best = None
    if w[1] < 0:  # floor y = -1, up to the back wall
        d = -1.0 / w[1]
        if d <= 12.0:
            best = (d, "floor")
    if 12.0 * w[1] <= 3.0:  # back wall at depth 12, top at y = 3
        if best is None or 12.0 < best[0]:
            best = (12.0, "wall")
    if -1.5 <= 6.0 * w[0] <= 0.0 and -1.0 <= 6.0 * w[1] <= 0.5:  # box face at depth 6
        if best is None or 6.0 < best[0]:
            best = (6.0, "box")
    return best


def render():
    D, C = [], []
    for j in range(CAM.height):
        drow, crow = [], []
        for i in range(CAM.width):
            hit = scene_hit(CAM.pixel_ray(i + 0.5, j + 0.5))
            drow.append(None if hit is None else hit[0])
            crow.append("sky" if hit is None else (hit[1], i, j))
        D.append(drow)
        C.append(crow)
    return D, C


D, COLOR = render()


def normalize(v):
    L = math.sqrt(sum(c * c for c in v))
    return tuple(c / L for c in v)


def march_reference(origin, dirn, max_dist, thickness, h=0.004):
    """A fine march of the 3D ray, testing the point depth at each pixel."""
    length = max_dist
    if origin[2] + dirn[2] * length > -CAM.near:
        length = (-CAM.near - origin[2]) / dirn[2]
    sx0, sy0, _ = CAM.project(origin)
    start = (int(math.floor(sx0)), int(math.floor(sy0)))
    t = h
    while t <= length:
        p = tuple(o + t * r for o, r in zip(origin, dirn))
        sx, sy, k = CAM.project(p)
        i, j = int(math.floor(sx)), int(math.floor(sy))
        if not (0 <= i < CAM.width and 0 <= j < CAM.height):
            return None
        s = D[j][i]
        if (i, j) != start and s is not None and s <= 1.0 / k <= s + thickness:
            return i, j
        t += h
    return None


def floor_pixels():
    return [(i, j) for j in range(CAM.height) for i in range(CAM.width) if COLOR[j][i] != "sky" and COLOR[j][i][0] == "floor"]


def test_inverse_depth_and_q_are_linear_in_screen_space() -> None:
    rng = random.Random(91)
    for _ in range(200):
        a = (rng.uniform(-3, 3), rng.uniform(-3, 3), -rng.uniform(1, 20))
        b = (rng.uniform(-3, 3), rng.uniform(-3, 3), -rng.uniform(1, 20))
        x0, y0, k0 = CAM.project(a)
        x1, y1, k1 = CAM.project(b)
        if abs(x1 - x0) < 1e-3:
            continue
        for _ in range(5):
            t = rng.random()
            p = tuple(u + t * (v - u) for u, v in zip(a, b))
            sx, sy, k = CAM.project(p)
            lam = (sx - x0) / (x1 - x0)
            k_lin = k0 + lam * (k1 - k0)
            assert abs(k_lin - k) < 1e-12 * max(1.0, k)
            q = tuple(u * k0 + lam * (v * k1 - u * k0) for u, v in zip(a, b))
            assert all(abs(qc / k_lin - pc) < 1e-9 for qc, pc in zip(q, p))
            assert abs(y0 + lam * (y1 - y0) - sy) < 1e-9


def test_first_hit_agrees_with_a_fine_march() -> None:
    rng = random.Random(92)
    pixels = rng.sample(floor_pixels(), 40)
    hits = 0
    for i, j in pixels:
        d = D[j][i]
        view = CAM.pixel_ray(i + 0.5, j + 0.5)
        origin = tuple(c * d for c in view)
        r = reflect(normalize(view), (0.0, 1.0, 0.0))
        got = trace(D, CAM, origin, r, 40.0, TAU)
        ref = march_reference(origin, r, 40.0, TAU)
        assert (got is None) == (ref is None)
        if got is not None:
            hits += 1
            assert abs(got[0] - ref[0]) <= 1 and abs(got[1] - ref[1]) <= 1
            assert D[got[1]][got[0]] <= -got[2][2] + 1e-9 <= D[got[1]][got[0]] + TAU + 0.5
    assert hits >= 20


def test_hit_point_lies_on_the_ray() -> None:
    i, j = 20, 5
    d = D[j][i]
    view = CAM.pixel_ray(i + 0.5, j + 0.5)
    origin = tuple(c * d for c in view)
    r = reflect(normalize(view), (0.0, 1.0, 0.0))
    hit = trace(D, CAM, origin, r, 40.0, TAU)
    assert hit is not None
    p = hit[2]
    t = sum((pc - oc) * rc for pc, oc, rc in zip(p, origin, r))
    closest = tuple(oc + t * rc for oc, rc in zip(origin, r))
    assert all(abs(a - b) < 1e-9 for a, b in zip(p, closest))


def test_self_hit_on_a_flat_surface_and_the_offset() -> None:
    # A ray that starts exactly on the wall overlaps the wall at the next pixel.
    on_wall = (2.0, 0.0, -12.0)
    assert trace(D, CAM, on_wall, normalize((1.0, 0.2, 0.6)), 40.0, TAU) is not None
    # Moved off the surface, the same ray leaves the screen: a miss.
    origin = (2.0, 0.0, -11.9)
    assert trace(D, CAM, origin, normalize((1.0, 0.2, 0.6)), 40.0, TAU) is None
    # Straight toward the camera: clipped at the near plane, and it leaves
    # the screen before it gets there.
    assert trace(D, CAM, origin, (0.0, 0.0, 1.0), 40.0, TAU) is None


def test_thickness_decides_hits_behind_the_box() -> None:
    # A ray at depth 9 that passes behind the box face at depth 6.
    origin, side = (-4.0, -0.25, -9.0), (1.0, 0.0, 0.0)
    assert trace(D, CAM, origin, side, 8.0, 0.5) is None
    thick = trace(D, CAM, origin, side, 8.0, float("inf"))
    assert thick is not None and COLOR[thick[1]][thick[0]][0] == "box"
    assert abs(-thick[2][2] - 9.0) < 1e-9  # reported 3 units behind the face
    # A ray from the hidden wall toward the camera crosses the face.
    origin, toward_camera = (-0.6, -0.25, -12.0), (0.0, 0.0, 1.0)
    thick = trace(D, CAM, origin, toward_camera, 40.0, float("inf"))
    thin = trace(D, CAM, origin, toward_camera, 40.0, 0.5)
    assert thick is not None and -thick[2][2] > 8.0  # the first pixel behind the face
    assert thin is not None and 6.0 <= -thin[2][2] <= 6.7  # near the true crossing


def test_reflection_uses_the_hit_or_the_environment() -> None:
    env = lambda r: ("environment", r[1] > 0)
    outs = [reflection(D, COLOR, CAM, i, j, (0.0, 1.0, 0.0), env, 40.0, TAU) for i, j in floor_pixels()]
    assert any(o[0] == "wall" for o in outs)
    assert any(o[0] == "box" for o in outs)
    assert any(o[0] == "environment" for o in outs)
    assert all(o[0] in ("wall", "box", "environment") for o in outs)

History

Renderers marched the depth buffer for reflections before 2014, with equal steps along the ray in 3D or in screen space. McGuire and Mara (2014) published a march that projects both ends of the ray, interpolates 1/d1/d and p/dp/d linearly along the screen line, and steps one pixel at a time on the major axis as in a line digital differential analyzer. Later work kept the screen-space march and added hierarchical depth pyramids, stochastic glossy rays with temporal filtering, and hybrid schemes that fall back to ray tracing for the rays that leave the screen.

References

  1. Morgan McGuire and Michael Mara, Efficient GPU screen-space ray tracing, Journal of Computer Graphics Techniques 3(4), 73-85, 2014, the projection of both ends of the ray, the linear interpolation of the reciprocal depth and of the point divided by depth, the step along the major axis, and the thickness test against the depth buffer
  2. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 11, the part on screen-space reflections and their fallbacks

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example