Transient ReSTIR (online)

In online rendering, every frame is rendered once within a fixed time budget and shown, instead of being averaged with other frames. This tutorial moves the camera forward through a scene, by 0.005 per frame over 100 frames, and renders a 64-bin transient histogram of every frame with TransientHistogramPathTracerInline and with TransientHistogramReSTIRInline at equal frame time. Every 10th frame is compared with a reference.

TransientHistogramReSTIRInline uses temporal reuse here: every frame resamples the previous frame’s reservoirs, reprojected with motion vectors and shifted to the moved camera with the path-length-aware shift mapping, so each bin keeps improving while the camera moves. The path tracer starts from nothing in every frame. Temporal reuse assumes that only the camera moves; the scene and the laser stay fixed.

The script renders one of two scenes, chosen on the command line:

  • cornell-box (the default): the Cornell box of the other tutorials (see ToF rendering), at 256 x 256.

  • veach-ajar: Veach, Ajar by Benedikt Bitterli (CC0), at 480 x 270, with the laser at the camera’s starting position. Download veach-ajar.zip (14 MB) and unzip it next to the script. Its textures are converted to PNG; they are read as linear colors, as in the original scene.

$ python transient_restir_online.py              # Cornell box
$ python transient_restir_online.py veach-ajar

It needs ffmpeg to write the videos, which show four of the 64 bins. The errors are defined as in the offline comparison, over all bins. The numbers below were measured on an NVIDIA GeForce RTX 3090 with Vulkan; frame times and the matched sample counts depend on the GPU.

Cornell box

TransientHistogramPathTracerInline
TransientHistogramReSTIRInline

Method

Samples per pixel

Frame time

Mean relMSE

Mean MAPE

TransientHistogramPathTracerInline

534

44.0 ms

0.597

0.683

TransientHistogramReSTIRInline

32

44.2 ms

0.483

0.437

At the same frame time, ReSTIR’s mean relMSE over the compared frames is 19 % lower and its MAPE 36 % lower, with 17 times fewer initial samples.

Veach, Ajar

TransientHistogramPathTracerInline
TransientHistogramReSTIRInline

Method

Samples per pixel

Frame time

Mean relMSE

Mean MAPE

TransientHistogramPathTracerInline

277

122.6 ms

2.861

1.133

TransientHistogramReSTIRInline

32

127.8 ms

1.547

0.403

The path tracer’s frames stay noisy even with 277 samples per pixel. At the same frame time, ReSTIR’s mean relMSE is 46 % lower and its MAPE 64 % lower, and the room is clearly recognizable in every frame.

1. Load the scene and set up the camera path

SCENES holds each scene’s file, image size, histogram range and laser. The camera moves along its view direction, starting from the scene’s camera. The ReSTIR options add temporal reuse to those of the offline tutorial: useTemporalReuse with a temporalHistoryLength of 20 frames, and one round of spatial reuse, which is cheaper per frame than the three rounds used offline.

import csv
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from time import perf_counter

import numpy as np
from PIL import Image, ImageDraw, ImageFont
import falcorcomp as falcor

# Each scene: its file, image size, histogram range and laser (in Veach, Ajar, at the starting camera).
SCENES = {
    "cornell-box": {
        "file": "cornell-box/scene-v4-nolight.pbrt", "size": (256, 256), "range": (16.75, 18.03),
        "laser": {"laserPosition": [0.0, 1.7, 6.8], "laserDirection": [0.0, 0.0, -1.0],
                  "laserPower": [170.0, 120.0, 40.0], "laserAngle": 0.0},
    },
    "veach-ajar": {
        "file": "veach-ajar/scene-v4.pbrt", "size": (480, 270), "range": (19.0, 21.0),
        "laser": {"laserPosition": [4.054023, 1.616475, -2.306524],
                  "laserDirection": [-0.990015, -0.032298, -0.137213],
                  "laserPower": [1000.0, 1000.0, 1000.0], "laserAngle": 0.0},
    },
}
SCENE = sys.argv[1] if len(sys.argv) > 1 else "cornell-box"
WIDTH, HEIGHT = SCENES[SCENE]["size"]
LASER = SCENES[SCENE]["laser"]

testbed = falcor.Testbed(create_window=False)
testbed.load_scene(SCENES[SCENE]["file"])
testbed.resize_frame_buffer(WIDTH, HEIGHT)
camera = testbed.scene.camera
camera.aspectRatio = WIDTH / HEIGHT
camera.apertureRadius = 0.0  # no depth of field
testbed.clock.pause()

# The camera moves forward along its view direction by STEP per frame.
FRAMES, STEP = 100, 0.005
START_POSITION = np.array([camera.position.x, camera.position.y, camera.position.z])
START_TARGET = np.array([camera.target.x, camera.target.y, camera.target.z])
FORWARD = (START_TARGET - START_POSITION) / np.linalg.norm(START_TARGET - START_POSITION)

(T_MIN, T_MAX), BINS = SCENES[SCENE]["range"], 64
HISTOGRAM = {"timeMin": T_MIN, "timeMax": T_MAX, "timeBin": BINS, "histogramFilter": "box"}
PT = {"samplesPerPixel": 32, "maxBounces": 6, "computeDirect": False, "useAlphaTest": True, **HISTOGRAM}
RESTIR = {**PT,
          "spatialReuseIteration": 1, "spatialReuseNeighborCount": 5,
          "useTemporalReuse": True, "temporalHistoryLength": 20.0,
          "shiftMappingMethod": "local_tangent", "gaugeMode": "avg_grad",
          "reconnectionRoughnessThreshold": 0.05}
SKIP_FRAMES = 10          # frames left out of the timing: shader compilation, history warm-up
TOLERANCE = 0.05          # accepted frame-time difference between the two tracers
REFERENCE = Path(f"reference-{SCENE}")      # frame_0009.npy, frame_0019.npy, ...; rendered below if missing
REFERENCE_FRAMES = range(9, FRAMES, 10)     # every 10th frame is compared with a reference
REFERENCE_SPP, REFERENCE_PASSES = 1024, 16  # 16 x 1024 = 16384 spp per reference frame
SHOWN_BINS = [12, 24, 36, 48]               # the bins in the videos


def set_pose(frame):
    offset = FORWARD * STEP * frame
    camera.position = falcor.float3(*(START_POSITION + offset).tolist())
    camera.target = falcor.float3(*(START_TARGET + offset).tolist())


2. Build the render graph

Each frame is shown on its own, so the graph has no accumulation pass: the tracer’s histogram output is the frame. For ReSTIR, the motion vectors of VBufferRT are connected to its mvec input, which it uses to find each pixel’s history in the previous frame.

def create_graph(tracer, properties):
    graph = testbed.create_render_graph(tracer)
    graph.create_pass("VBuffer", "VBufferRT", {"samplePattern": "Center", "sampleCount": 1, "useAlphaTest": True})
    graph.create_pass("Laser", "LaserLight", LASER)
    graph.create_pass("Tracer", tracer, properties)
    graph.add_edge("VBuffer.vbuffer", "Tracer.vbuffer")
    graph.add_edge("VBuffer.viewW", "Tracer.viewW")
    graph.add_edge("Laser", "Tracer")
    if tracer == "TransientHistogramReSTIRInline":
        graph.add_edge("VBuffer.mvec", "Tracer.mvec")  # reprojects the history as the camera moves
    graph.mark_output("Tracer.histogram")  # one histogram per frame: no accumulation
    return graph


def read_histogram(graph):
    return graph.get_output("Tracer.histogram").to_numpy()[..., :3]  # (bins, height, width, RGB)


3. Render the sequence

The camera is moved before every frame. Each frame is timed with a wait for the GPU, and the first 10 frames, which include shader compilation and ReSTIR’s first frames without history, are left out of the mean frame time. Histograms are read back only when a callback asks for them, so the timing runs measure rendering alone.

def render_sequence(tracer, properties, on_frame=None):
    """Returns the mean frame time in ms. on_frame(frame, histogram) receives each frame's
    histogram; it is read back only when on_frame is given, so timing runs have no readback."""
    graph = create_graph(tracer, properties)  # a new graph starts with an empty ReSTIR history
    testbed.render_graph = graph
    times = []
    for frame in range(FRAMES):
        set_pose(frame)
        start = perf_counter()
        testbed.frame()
        testbed.device.wait()  # include the frame's GPU time
        times.append(perf_counter() - start)
        if on_frame is not None:
            on_frame(frame, read_histogram(graph))
    return 1000.0 * float(np.mean(times[SKIP_FRAMES:]))


4. Match the frame time

ReSTIR renders 32 initial samples per pixel. The path tracer starts at the same count and is then given the sample count that fits the same frame time: its sample count is scaled by the ratio of the frame times until they are within 5 %, with at most three adjustments.

restir_ms = render_sequence("TransientHistogramReSTIRInline", RESTIR)
print(f"TH ReSTIR: {RESTIR['samplesPerPixel']} spp, {restir_ms:.1f} ms/frame")
trials = {}
pt_spp = PT["samplesPerPixel"]
for attempt in range(4):  # the equal-spp run, then up to three adjustments
    trials[pt_spp] = render_sequence("TransientHistogramPathTracerInline", {**PT, "samplesPerPixel": pt_spp})
    print(f"THPT: {pt_spp} spp, {trials[pt_spp]:.1f} ms/frame")
    if abs(trials[pt_spp] / restir_ms - 1.0) <= TOLERANCE:
        break
    pt_spp = max(1, round(pt_spp * restir_ms / trials[pt_spp]))
    if pt_spp in trials:
        break
pt_spp = min(trials, key=lambda spp: abs(trials[spp] - restir_ms))
pt_ms = trials[pt_spp]

5. Compare with the reference

Both sequences are rendered again, this time reading every frame back, and every 10th frame is compared with the reference histogram at the same camera position. The reference is rendered by the path tracer with 16,384 samples per pixel, as 16 frames of 1,024 samples, so that no single frame runs for long. If the reference-<scene> folder does not exist, the script renders it first and saves it in half precision (about 250 MB for the Cornell box, 500 MB for Veach, Ajar).

if not REFERENCE.exists():
    print(f"Rendering the reference with THPT at {REFERENCE_SPP * REFERENCE_PASSES} spp per frame")
    REFERENCE.mkdir()
    graph = create_graph("TransientHistogramPathTracerInline", {**PT, "samplesPerPixel": REFERENCE_SPP})
    testbed.render_graph = graph
    for frame in REFERENCE_FRAMES:
        set_pose(frame)
        total = 0.0
        for _ in range(REFERENCE_PASSES):  # several frames, so that no single frame runs too long
            testbed.frame()
            total = total + read_histogram(graph)
        np.save(REFERENCE / f"frame_{frame:04d}.npy", (total / REFERENCE_PASSES).astype(np.float16))


def errors(histogram, reference):
    relative_mse = np.mean((histogram - reference) ** 2) / np.mean(reference ** 2)
    mape = np.mean(np.abs(histogram - reference) / (0.01 * np.mean(reference) + reference))
    return float(relative_mse), float(mape)


def to_display(histogram):
    """The shown bins in a 2 x 2 grid, each as bright as the image if all light arrived in it."""
    tiles = np.maximum(histogram[SHOWN_BINS], 0.0) * (T_MAX - T_MIN)
    tiles = tiles / (1.0 + tiles)  # Reinhard
    tiles = np.where(tiles <= 0.0031308, 12.92 * tiles, 1.055 * tiles ** (1 / 2.4) - 0.055)  # sRGB
    grid = tiles.reshape(2, 2, HEIGHT, WIDTH, 3).transpose(0, 2, 1, 3, 4).reshape(2 * HEIGHT, 2 * WIDTH, 3)
    return (np.clip(grid, 0, 1) * 255).astype(np.uint8)


def record(tracer, properties):
    """Renders the sequence and returns each frame's display image and the reference frames' errors."""
    frames, frame_errors = [], {}

    def on_frame(frame, histogram):
        if frame in REFERENCE_FRAMES:
            reference = np.load(REFERENCE / f"frame_{frame:04d}.npy").astype(np.float32)
            frame_errors[frame] = errors(histogram, reference)
        frames.append(to_display(histogram))

    render_sequence(tracer, properties, on_frame)
    return frames, frame_errors


pt_frames, pt_errors = record("TransientHistogramPathTracerInline", {**PT, "samplesPerPixel": pt_spp})
restir_frames, restir_errors = record("TransientHistogramReSTIRInline", RESTIR)
pt_mean = np.mean(list(pt_errors.values()), axis=0)
restir_mean = np.mean(list(restir_errors.values()), axis=0)
print(f"Mean relMSE: THPT {pt_mean[0]:.3f}, TH ReSTIR {restir_mean[0]:.3f}")
print(f"Mean MAPE: THPT {pt_mean[1]:.3f}, TH ReSTIR {restir_mean[1]:.3f}")
with open(f"errors-{SCENE}.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["frame", "thpt_relmse", "thpt_mape", "th_restir_relmse", "th_restir_mape"])
    for frame in REFERENCE_FRAMES:
        writer.writerow([frame, *pt_errors[frame], *restir_errors[frame]])


6. Save the videos

Every frame shows the same four bins, tone mapped the same way (Reinhard, then sRGB), labeled with the sample count, the frame time and the mean errors, and encoded at 15 frames per second.

def save_video(path, name, spp, frame_ms, frames, mean_errors, fps=15):
    font = ImageFont.load_default(size=20)
    with tempfile.TemporaryDirectory() as folder:
        for frame, image in enumerate(frames):
            canvas = Image.new("RGB", (2 * WIDTH, 2 * HEIGHT + 64), "black")
            canvas.paste(Image.fromarray(image), (0, 64))
            draw = ImageDraw.Draw(canvas)
            draw.text((10, 6), f"{name}: {spp} spp, {frame_ms:.1f} ms/frame", fill="white", font=font)
            draw.text((10, 34), f"frame {frame:3d}   mean relMSE {mean_errors[0]:.3f}   "
                                f"MAPE {mean_errors[1]:.3f}", fill="white", font=font)
            canvas.save(f"{folder}/frame_{frame:04d}.png")
        subprocess.run([shutil.which("ffmpeg"), "-y", "-loglevel", "error", "-framerate", str(fps),
                        "-i", f"{folder}/frame_%04d.png", "-c:v", "libx264", "-crf", "20",
                        "-pix_fmt", "yuv420p", path], check=True)


save_video(f"transient_thpt_online_{SCENE}.mp4", "THPT", pt_spp, pt_ms, pt_frames, pt_mean)
save_video(f"transient_restir_online_{SCENE}.mp4", "TH ReSTIR", RESTIR["samplesPerPixel"], restir_ms,
           restir_frames, restir_mean)

The full script: transient_restir_online.py. Including the reference, it takes about four minutes for the Cornell box and nine for Veach, Ajar. It also saves the compared frames’ errors to errors-<scene>.csv.