Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Live rendering settings and two reconstruction contracts: MetalFX, DLSS SR / RR, FSR (#189, supersedes #165)

Evan (Yifeng) Wangaf00e834aafb
diff --git a/README.md b/README.md
index 4c97a5c..737d0d3 100644
--- a/README.md
+++ b/README.md
@@ -156,6 +156,12 @@ node tools/three/open.ts scenes/bistro.ts # the same scene in three.js, in your
In the window: drag to orbit, right-drag to pan, wheel to zoom, WASD/QE to fly, `R` to reset, `P` for a snapshot.
+`play` and `live` take `--quality` (`auto`, `native`, `quality`, `balanced`, `performance`, `ultra-performance`),
+`--reconstruction` (`builtin`, `auto`, an upscaler: `fsr`, `metalfx`, `dlss`; a joint denoiser: `metalfx-denoised`,
+`dlss-rr`; or a list in order of preference) and `--latency`. FSR 1 also runs on WebGPU; DLSS requires an opt-in NVIDIA
+SDK build; MetalFX requires supported Apple hardware. See
+[live rendering settings and the TypeScript API](docs/RUNTIME.md#live-rendering-settings).
+
```bash
npm test && npm run typecheck && (cd renderer && cargo test --release) # scene API, gameplay, runtime and engine tests
npm run test:render # the render test suite, on the GPU
diff --git a/docs/RUNTIME.md b/docs/RUNTIME.md
index 171f3d6..6e065ae 100644
--- a/docs/RUNTIME.md
+++ b/docs/RUNTIME.md
@@ -1603,6 +1603,135 @@ none of them it traces its light there. Two limits are known and held by tests s
sunlit mirror wall 5 % bright), and a surface seen in a reflection takes the sky's light from it, unshadowed
below a voxel's size.
+## Live rendering settings
+
+The native `play` and `live` commands, `serve` live jobs and the browser take four settings, one for each gap
+between what a frame affords and what is shown (renderer/src/live/rendering.rs):
+
+| setting | the gap | ThreeRT's own | vendor technology it maps |
+|---|---|---|---|
+| `quality` | rays: the render resolution every later stage works from | dynamic resolution | (a budget, not a technique) |
+| `reconstruction` | noise, then pixels | denoiser + temporal upscaler | DLSS SR / RR, MetalFX, FSR, XeSS |
+| `frameGeneration` | frames shown per frame rendered | none | DLSS FG, FSR FG, XeSS FG, MetalFX frame interpolation (none integrated yet) |
+| `latency` | input to photon | one frame queued instead of two | Reflex, Anti-Lag 2, XeLL |
+
+Each is a request: the renderer runs what the device supports, and the status says what ran and why not the rest
+(nothing falls back silently). Neural techniques are not a setting of their own: a neural denoiser or upscaler is a
+reconstruction method, a neural radiance cache would be a lighting option, neural texture compression an asset format.
+
+```sh
+node tools/bundle-game.ts scenes/neon-reflections.ts
+renderer/target/release/threert-render play out/bundles/neon-reflections.js \
+ --quality performance --reconstruction metalfx-denoised,metalfx,builtin --latency on
+```
+
+### Reconstruction: two contracts
+
+A path tracer's frame needs two jobs before post: remove the samples' noise, then bring the image to the output size
+from the history of earlier frames. Vendor technology takes over the second job or both, so there are two kinds of
+provider, which read different signals:
+
+- an **upscaler** (`UpscaleProvider`) reads ThreeRT's *denoised* HDR image, depth, motion, a reactive mask and the
+ jitter, and replaces the upscaling;
+- a **joint denoiser** (`JointProvider`) reads the *noisy* traced lighting and the surface guides it needs to tell
+ lighting from texture (diffuse and specular albedo, normal, roughness, specular hit distance, an overlay of what has
+ no noise to remove), and replaces both. ThreeRT's denoiser does not run.
+
+| `--reconstruction` | denoise | upscale |
+|---|---|---|
+| `builtin` (default) | ThreeRT | ThreeRT (temporal) |
+| `fsr` | ThreeRT | AMD FidelityFX Super Resolution **1** (spatial EASU + RCAS; also on WebGPU) |
+| `metalfx` | ThreeRT | Apple's temporal scaler (macOS 13+) |
+| `dlss` | ThreeRT | NVIDIA DLSS Super Resolution; DLAA at scale 1 (x86-64 Windows/Linux, RTX on Vulkan, feature `dlss`) |
+| `metalfx-denoised` | Apple's temporal denoised scaler: both (macOS 26+, Apple silicon) | |
+| `dlss-rr` | NVIDIA DLSS Ray Reconstruction: both (as `dlss`) | |
+| `off` | none | none: each frame's samples as traced, without history (the joint denoisers' input; for comparison) |
+| `custom:<id>` | a provider an embedding host registered, of either kind | |
+| `auto` | the best this device runs: `metalfx-denoised`, `metalfx` on a Mac; `dlss-rr`, `dlss` with DLSS; else `builtin` | |
+
+A list (`dlss-rr,dlss,fsr`) is an order of preference; `builtin` ends every list. `quality` presets are the vendors'
+ratios exactly (`ultra-performance` is a third: 640 pixels across 1080p, the smallest input DLSS takes, where a typed
+`--scale 0.333` gives 639 and DLSS reports itself unsupported). Diagnostic views use `builtin`. A provider that
+fails while encoding a frame falls back to `builtin` from that frame on.
+
+### TypeScript
+
+```ts
+import { rendering, type RenderingStatus } from "@threert/scene";
+
+rendering.set({ quality: "performance", reconstruction: ["metalfx-denoised", "dlss-rr", "builtin"], latency: "auto" });
+const status: RenderingStatus | undefined = rendering.status();
+// status.reconstruction: { requested, active, denoise, upscale, fallback, skipped: [{ method, reason, detail }] }
+```
+
+`set` changes the settings it is given, from the next frame; it returns `true` when a renderer binding took the
+request (not a support check) and throws a `TypeError` for an unknown setting or value. `status()` is the last frame's:
+for each setting what was requested and what ran; for reconstruction also who denoised and who upscaled, and each
+method tried before the one that ran with its reason (`unavailable`: not in this build or platform; `unsupported`: the
+device, OS or size; `provider-error`; `diagnostic-view`) and a sentence of detail. `fallback` is the first method's
+reason (`null` when it ran, or for `auto`). These are device-local view settings, not scene state, and are not
+replicated. A runtime without the live renderer binding returns `false` from `set` and `undefined` from `status`.
+
+### NVIDIA DLSS setup
+
+Install [NVIDIA DLSS SDK 310.9.1](https://github.com/NVIDIA/DLSS/tree/v310.9.1), the Vulkan SDK, and Clang
+(including libclang for bindgen). Set `DLSS_SDK` and `VULKAN_SDK` to their SDK directories, then build:
+
+```sh
+cargo build --release --locked --manifest-path renderer/Cargo.toml --features dlss
+WGPU_BACKEND=vulkan THREERT_DLSS=1 renderer/target/release/threert-render \
+ play out/bundles/neon-reflections.js --quality performance --reconstruction dlss-rr,dlss
+```
+
+NVIDIA's matching runtime libraries (`nvngx_dlss`, and `nvngx_dlssd` for Ray Reconstruction) must be discoverable.
+For distribution, follow the
+[DLSS wrapper's deployment instructions](https://github.com/bevyengine/dlss_wgpu/tree/b35069de8640bfae383e65a46b7d16058b2994d2#distributing-your-app).
+The engine does not bundle NVIDIA's SDK or runtime.
+
+### Apple MetalFX
+
+The temporal scaler requires a supporting Metal device and macOS 13 or later. Build with the macOS 26 SDK
+or newer to include the denoised scaler, which also requires macOS 26 or newer at runtime. A plain temporal scaler
+can keep its history across dynamic resolution changes inside its supported range (its inputs are textures of the
+output's size); the denoised scaler starts a new history when input dimensions change.
+
+In the scene viewer, press `M` to switch between `builtin` and `auto` (on a Mac, MetalFX's joint denoiser) and `N`
+to step through every method this platform has. The title bar shows the method that ran and the render scale. Games
+that handle keyboard input keep their key bindings. `tools/denoise-demo/live.sh` opens Kaleido (a mirror hall lit
+only by hundreds of glowing orbs) for this comparison; `tools/denoise-demo/record.ts` and `video.ts` record it.
+
+For smooth mirrors and glass, secondary ray queries put the reflected and transmitted surfaces in the joint
+denoiser's guides (pathtrace.wgsl `surface_guides`). Directly visible sky and emission-dominated pixels are the
+overlay, with the bypass mask 1 on them. Exposure, bloom, depth of field and motion blur process the reconstructed
+HDR image on the GPU.
+
+### Native controls and custom providers
+
+Set `THREERT_RECONSTRUCTION` for a native process that embeds `LiveCore`, call `LiveCore::set_rendering` (or
+`set_reconstruction`), or send `{"cmd":"rendering","reconstruction":["metalfx-denoised","builtin"],"quality":"balanced"}`
+to a running `live` or `play` session (`{"cmd":"reconstruction","mode":"fsr"}` is the same with one setting). Launch
+flags (`--quality`, `--reconstruction`, `--frame-generation`, `--latency`) set the initial values. Viewer `stats` have
+the whole status under `rendering`, and `reconstruction`, `requested_reconstruction` and `reconstruction_fallback`;
+the `live --frame-log` records the method each frame ran and its fallback. Live `serve` jobs accept `reconstruction`
+(a method, a list or `auto`) and a numeric `scale`.
+
+An embedding host implements `UpscaleProvider` or `JointProvider` (renderer/src/live/reconstruction.rs documents
+every texture: format, units, conventions) and calls `LiveCore::register_upscaler("custom:my-scaler", provider)` or
+`register_joint_denoiser`, then selects it from Rust or TypeScript. IDs after `custom:` are 1–48 lowercase ASCII
+letters, digits, or hyphens. `prepare` answers `Prepared::Ready` (with the input textures' size, which may exceed the
+input for a provider that takes a varying input) or `Prepared::Unsupported(reason)`, which goes to the status. The
+provider writes full-output HDR on the live GPU, on the encoder or in a native command buffer it returns; the engine
+still owns packing the signals, post-processing and presentation.
+
+Run `node tools/bench-metalfx.ts` after building the release binary to compare the three MetalFX/built-in paths
+against 256-spp offline references for a still camera and a lateral move. It saves the frames, frame timings and
+image metrics under `out/metalfx/` and checks which implementation actually ran.
+Use `--scene glass` for the refraction workbench or `--scene cornell` for the Cornell box.
+On an Apple M1 running macOS 27.2.1, the glass camera move scored 0.909 SSIM with the built-in path,
+0.944 with MetalFX temporal and 0.940 with joint denoising. At the same 320 × 180 input and 640 × 360
+output, median GPU frame times with the camera held still were 9.69, 9.78 and 10.22 ms respectively.
+On the Cornell box the built-in path scored highest for both camera poses.
+
## Moving objects in the live view
The live view's histories (the irradiance and specular ones on the traced grid, the upscaler's colour on the output
diff --git a/games/kaleido/kaleido.game.ts b/games/kaleido/kaleido.game.ts
new file mode 100644
index 0000000..193b089
--- /dev/null
+++ b/games/kaleido/kaleido.game.ts
@@ -0,0 +1,189 @@
+// Kaleido on ThreeRT (games/kaleido/sim.ts): a hall of two facing mirrors, glass and chrome, lit by nothing but
+// hundreds of glowing orbs that pour from the ceiling, pile up and are blown apart. Every orb is a light with its own
+// shadows (the light tree picks among them per pixel), so a pile is dark inside and lights the floor around it; the
+// mirrors reflect each other and everything in the hall, the glass refracts it, the plaster and ceiling take the
+// orbs' colours bounced off the floor and each other, and a blast's flash lights the whole hall at once.
+// node tools/kaleido/bench.ts (both engines, measured)
+// node tools/bundle-game.ts games/kaleido/kaleido.game.ts -o out/bundles/kaleido.js
+// renderer/target/release/threert-render play out/bundles/kaleido.js --scale 0.5 --reconstruction metalfx-denoised
+// Options: `wait` (the bench: nothing moves until a "go" event, so frame k of a lockstep run is the show's frame k),
+// `record` (each frame's poses and glows on stdout, for the three.js page to replay), `still` (a recorded frame, held:
+// the offline reference's scene).
+import { BoxGeometry, Color, Mesh, MeshPhysicalMaterial, MeshStandardMaterial, PerspectiveCamera, Scene, SkyColor, SphereGeometry, Vector3 } from "@threert/scene";
+import { defineGame } from "@threert/gameplay";
+import { BALLS, BLAST, BODY, GLOW_NITS, HALL, LOOK, MONOLITHS, PALETTE, PARK, STATIC, Show, blastAt, cameraAt, flashOf, parkedAt, type Actuator } from "./sim.ts";
+
+const REPORT_EVERY = 60;
+
+export interface Still { t: number; poses: number[]; glows: number[] }
+
+/** Base64 of a float array's bytes (QuickJS has no btoa). */
+function b64(a: Float32Array): string {
+ const T = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ const u = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
+ let out = "";
+ let i = 0;
+ for (; i + 2 < u.length; i += 3) {
+ const n = (u[i] << 16) | (u[i + 1] << 8) | u[i + 2];
+ out += T[n >> 18] + T[(n >> 12) & 63] + T[(n >> 6) & 63] + T[n & 63];
+ }
+ if (i < u.length) {
+ const n = (u[i] << 16) | ((i + 1 < u.length ? u[i + 1] : 0) << 8);
+ out += T[n >> 18] + T[(n >> 12) & 63] + (i + 1 < u.length ? T[(n >> 6) & 63] : "=") + "=";
+ }
+ return out;
+}
+
+export function makeGame(count: number, o: { width?: number; height?: number; wait?: boolean; record?: boolean; still?: Still; logic?: boolean } = {}) {
+ let meshes: Mesh[] = [];
+ let show: Show | null = null;
+ let camera: PerspectiveCamera | null = null;
+ let blast: Mesh | null = null;
+ let live: Uint8Array = new Uint8Array(0);
+ const v = new Vector3(), zero = new Vector3();
+ let pos = new Float32Array(0), rec = new Float32Array(0), recGlow = new Float32Array(0);
+ const act: Actuator = {
+ teleport(i, p, vel) {
+ const m = meshes[i];
+ m.position.set(p[0], p[1], p[2]);
+ m.quaternion.set(0, 0, 0, 1);
+ m.setLinearVelocity(v.set(vel[0], vel[1], vel[2]));
+ m.setAngularVelocity(zero);
+ if (!live[i] && show!.orbs[i].kind === "glow") m.power = show!.orbs[i].gain * show!.glow[i];
+ live[i] = 1;
+ },
+ impulse(i, x, y, z) {
+ meshes[i].applyImpulse(v.set(x, y, z));
+ },
+ glow(i, g) {
+ if (live[i]) meshes[i].power = show!.orbs[i].gain * g;
+ },
+ };
+ const positions = () => {
+ for (let i = 0; i < meshes.length; i++) {
+ const p = meshes[i].position;
+ pos[i * 3] = p.x; pos[i * 3 + 1] = p.y; pos[i * 3 + 2] = p.z;
+ }
+ return pos;
+ };
+ /** The blast's fireball and the camera at time t. */
+ const place = (t: number) => {
+ const b = blastAt(t);
+ if (b) {
+ const f = flashOf(b);
+ blast!.position.set(...b.at);
+ blast!.scale.setScalar(f.radius);
+ blast!.power = f.power;
+ } else if (blast!.power !== 0) {
+ blast!.power = 0;
+ blast!.position.set(0, PARK.y - 5, PARK.z);
+ }
+ const c = cameraAt(t);
+ camera!.position.set(...c.pos);
+ camera!.lookAt(...c.target);
+ };
+ return defineGame({
+ state: { go: !o.wait },
+ handlers: { go(tx) { tx.state.go = true; } },
+ setup() {
+ const scene = new Scene();
+ scene.environment = new SkyColor(0x000000, 0);
+ const physical = !o.still;
+ const box = (w: number, h: number, d: number, x: number, y: number, z: number, m: MeshStandardMaterial, name: string, yaw = 0) => {
+ const mesh = new Mesh(new BoxGeometry(w, h, d), m);
+ mesh.name = name;
+ mesh.position.set(x, y, z);
+ mesh.rotation.y = yaw;
+ if (physical) mesh.physics = { type: "fixed", ...STATIC };
+ scene.add(mesh);
+ return mesh;
+ };
+ const { hx, z0, z1, hy } = HALL, len = z1 - z0, zc = (z0 + z1) / 2;
+ const floor = new MeshStandardMaterial({ name: "floor", color: LOOK.floor.color, roughness: LOOK.floor.roughness });
+ const mirror = new MeshStandardMaterial({ name: "mirror", color: LOOK.mirror.color, metalness: 1, roughness: LOOK.mirror.roughness });
+ const plaster = new MeshStandardMaterial({ name: "plaster", color: LOOK.plaster.color, roughness: LOOK.plaster.roughness });
+ const ceiling = new MeshStandardMaterial({ name: "ceiling", color: LOOK.ceiling.color, roughness: LOOK.ceiling.roughness });
+ const glass = new MeshPhysicalMaterial({ name: "glass", color: 0xffffff, roughness: 0, transmission: 1, ior: LOOK.glass.ior });
+ const chrome = new MeshStandardMaterial({ name: "chrome", color: LOOK.chrome.color, metalness: 1, roughness: LOOK.chrome.roughness });
+ box(2 * hx + 0.4, 0.2, len + 0.4, 0, -0.1, zc, floor, "floor");
+ box(2 * hx + 0.4, 0.2, len + 0.4, 0, hy + 0.1, zc, ceiling, "ceiling");
+ box(0.1, hy, len, -hx - 0.05, hy / 2, zc, mirror, "mirrorL");
+ box(0.1, hy, len, hx + 0.05, hy / 2, zc, mirror, "mirrorR");
+ box(2 * hx, hy, 0.2, 0, hy / 2, z0 - 0.1, plaster, "back");
+ box(2 * hx, hy, 0.2, 0, hy / 2, z1 + 0.1, plaster, "front");
+ MONOLITHS.forEach((m, k) => box(m.half[0] * 2, m.half[1] * 2, m.half[2] * 2, m.at[0], m.half[1], m.at[2], glass, `monolith${k}`, m.yaw));
+ BALLS.forEach((b, k) => {
+ const mesh = new Mesh(new SphereGeometry(b.r, 64, 32), b.kind === "glass" ? glass : chrome);
+ mesh.name = `ball${k}`;
+ mesh.position.set(...b.at);
+ if (physical) mesh.physics = { type: "fixed", ...STATIC };
+ scene.add(mesh);
+ });
+ // Where the orbs wait, far below.
+ box(2 * PARK.half, 0.5, 2 * PARK.half, 0, PARK.y, PARK.z, ceiling, "park");
+
+ show = new Show(count);
+ live = new Uint8Array(count);
+ pos = new Float32Array(count * 3);
+ const sphere = new SphereGeometry(1, 16, 8);
+ const team = PALETTE.map((c, k) => new MeshStandardMaterial({ name: `orb${k}`, color: new Color(c).multiplyScalar(0.2), roughness: 0.35, emissive: c, emissiveIntensity: GLOW_NITS }));
+ const orbChrome = new MeshStandardMaterial({ name: "orbChrome", color: LOOK.chrome.color, metalness: 1, roughness: LOOK.chrome.roughness });
+ meshes = show.orbs.map((orb, i) => {
+ const m = new Mesh(sphere, orb.kind === "glow" ? team[orb.team] : orb.kind === "chrome" ? orbChrome : glass);
+ m.name = `orb${i}`;
+ m.scale.setScalar(orb.r);
+ const p = parkedAt(i);
+ m.position.set(p[0], PARK.y + 0.25 + orb.r, p[2]);
+ if (orb.kind === "glow") m.power = 0; // dark until it pours
+ if (physical) m.physics = { type: "dynamic", density: BODY.density, friction: BODY.friction, restitution: BODY.restitution, linearDamping: BODY.linearDamping, angularDamping: BODY.angularDamping, ccd: true };
+ scene.add(m);
+ return m;
+ });
+ blast = new Mesh(new SphereGeometry(1, 24, 12), new MeshStandardMaterial({ name: "blast", color: 0x000000, emissive: 0xffe2c0, emissiveIntensity: BLAST.nits }));
+ blast.name = "blast";
+ blast.power = 0;
+ blast.position.set(0, PARK.y - 5, PARK.z);
+ scene.add(blast);
+
+ camera = new PerspectiveCamera(cameraAt(0).fov, (o.width ?? 1920) / (o.height ?? 1080), 0.05, 200);
+ camera.setManualExposure(LOOK.ev100);
+ scene.add(camera);
+ if (o.still) {
+ // A recorded frame: the orbs where they were, as bright as they were.
+ const s = o.still;
+ meshes.forEach((m, i) => {
+ m.position.set(s.poses[i * 7], s.poses[i * 7 + 1], s.poses[i * 7 + 2]);
+ m.quaternion.set(s.poses[i * 7 + 3], s.poses[i * 7 + 4], s.poses[i * 7 + 5], s.poses[i * 7 + 6]);
+ if (show!.orbs[i].kind === "glow") m.power = show!.orbs[i].gain * s.glows[i];
+ });
+ place(s.t);
+ } else place(0);
+ if (o.record) {
+ rec = new Float32Array(count * 7);
+ recGlow = new Float32Array(count);
+ }
+ return { scene, camera, options: { name: `kaleido-${count}`, width: o.width ?? 1920, height: o.height ?? 1080, preset: "preview" as const } };
+ },
+ frame(f) {
+ if (!show || o.still || !f.state.go || f.dt <= 0) return;
+ if (o.record) {
+ // Before this frame's step: the poses the physics left after the last one, the glows and blast of the last
+ // frame: what frame `show.frame` (the last one) showed.
+ for (let i = 0; i < meshes.length; i++) {
+ const m = meshes[i], k = i * 7;
+ rec[k] = m.position.x; rec[k + 1] = m.position.y; rec[k + 2] = m.position.z;
+ rec[k + 3] = m.quaternion.x; rec[k + 4] = m.quaternion.y; rec[k + 5] = m.quaternion.z; rec[k + 6] = m.quaternion.w;
+ recGlow[i] = live[i] && show.orbs[i].kind === "glow" ? show.glow[i] : 0;
+ }
+ console.log(`kpose ${show.frame} ${b64(rec)} ${b64(recGlow)}`);
+ }
+ if (o.logic !== false) show.step(1 / 60, positions, act);
+ else { show.t += 1 / 60; show.frame++; }
+ place(show.t);
+ const s = show.stats;
+ if (show.frame % REPORT_EVERY === 0) console.log(`kaleido ${JSON.stringify({ frame: show.frame, released: show.released, blasts: show.blasts, glowSends: s.glowSends })}`);
+ },
+ });
+}
+
+export default makeGame(600);
diff --git a/games/kaleido/sim.ts b/games/kaleido/sim.ts
new file mode 100644
index 0000000..9ca5ab5
--- /dev/null
+++ b/games/kaleido/sim.ts
@@ -0,0 +1,229 @@
+// Kaleido: a sealed hall at night whose two long walls are mirrors facing each other, a polished black floor, glass
+// monoliths and glass and chrome spheres standing in it. Hundreds of glowing, mirror and glass orbs pour from three
+// chutes in the ceiling, bounce off the glass and chrome, pile up on the floor, and every few seconds a pile blows
+// apart in a flash. The only light is the orbs' (and the blasts'). Everything here is plain data and arithmetic,
+// shared by the ThreeRT game (kaleido.game.ts) and the three.js page (tools/kaleido/three-page.ts); the physics is the
+// engine's Rapier in both (native in ThreeRT, wasm32 in the page).
+
+export type Vec3 = [number, number, number];
+
+/** The hall (metres): x in [-HX, HX] (the mirrors), z in [Z0, Z1], y in [0, HY]. The camera looks down -z. */
+export const HALL = { hx: 7, z0: -27, z1: 6, hy: 8 };
+
+/** Glass monoliths: upright slabs (centre on the floor, half extents, yaw). */
+export const MONOLITHS: { at: Vec3; half: Vec3; yaw: number }[] = [
+ { at: [-3.6, 0, -5.5], half: [0.8, 2.3, 0.18], yaw: 0.55 },
+ { at: [3.4, 0, -10], half: [0.8, 2.6, 0.18], yaw: -0.45 },
+ { at: [-1.2, 0, -14.5], half: [0.7, 2.0, 0.18], yaw: 0.2 },
+ { at: [2.0, 0, -20.5], half: [0.9, 2.9, 0.18], yaw: -0.65 },
+ { at: [-4.3, 0, -22.5], half: [0.8, 2.4, 0.18], yaw: 0.35 },
+];
+/** Spheres standing on the floor: glass and chrome. */
+export const BALLS: { at: Vec3; r: number; kind: "glass" | "chrome" }[] = [
+ { at: [-1.2, 1.0, -7.8], r: 1.0, kind: "glass" },
+ { at: [2.6, 1.25, -5.2], r: 1.25, kind: "chrome" },
+ { at: [-3.0, 1.35, -16.5], r: 1.35, kind: "chrome" },
+ { at: [4.2, 0.9, -15.6], r: 0.9, kind: "glass" },
+ { at: [0.3, 1.1, -24.3], r: 1.1, kind: "glass" },
+];
+
+/** The orbs' colours (sRGB) and the glow of a lit orb (cd/m²). */
+export const PALETTE = [0xff3b6b, 0xffa12b, 0xffe14a, 0x3bff9a, 0x38c8ff, 0x7a5bff, 0xff5bf0];
+export const GLOW_NITS = 1500;
+/** Exposure (EV100) and what the room is made of. */
+export const LOOK = {
+ ev100: 5.0,
+ floor: { color: 0x0c0c0e, roughness: 0.035 },
+ mirror: { color: 0xf2f3f5, roughness: 0.0 },
+ plaster: { color: 0x5e5a55, roughness: 0.9 },
+ ceiling: { color: 0x1c1b1a, roughness: 0.85 },
+ glass: { ior: 1.5 },
+ chrome: { color: 0xeeeff2, roughness: 0.02 },
+};
+
+export type OrbKind = "glow" | "chrome" | "glass";
+export interface Orb { kind: OrbKind; r: number; team: number; gain: number; mass: number }
+
+export function linear(hex: number): Vec3 {
+ const c = [(hex >> 16) & 255, (hex >> 8) & 255, hex & 255].map((v) => v / 255);
+ return c.map((v) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)) as Vec3;
+}
+
+/** mulberry32: integer arithmetic only, the same in every engine. */
+export function rng(seed: number) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+const TAU = 6.283185307179586;
+/** sin(x) from + - * and floor (the camera path is then the same in both engines to the bit). */
+export function ksin(x: number): number {
+ let y = x - TAU * Math.floor(x / TAU + 0.5); // [-pi, pi]
+ if (y > 1.5707963267948966) y = 3.141592653589793 - y;
+ else if (y < -1.5707963267948966) y = -3.141592653589793 - y;
+ const y2 = y * y;
+ return y * (1 + y2 * (-1 / 6 + y2 * (1 / 120 + y2 * (-1 / 5040 + y2 * (1 / 362880 + y2 * (-1 / 39916800 + y2 / 6227020800))))));
+}
+export const kcos = (x: number) => ksin(x + 1.5707963267948966);
+
+/** The physics: the orbs (dynamic, continuous collision for their speed) and the hall's fixed parts. */
+export const BODY = { density: 400, friction: 0.6, restitution: 0.3, linearDamping: 0.15, angularDamping: 2.0 };
+export const STATIC = { friction: 0.6, restitution: 0.4 };
+/** Where the orbs wait before they pour (far below the hall, out of sight, dark): a fixed slab, an orb a cell. */
+export const PARK = { y: -30, cell: 0.7, half: 16, z: -10 };
+export function parkedAt(i: number): Vec3 {
+ const row = 40;
+ return [-14 + (i % row) * PARK.cell, PARK.y + 0.5, PARK.z - 14 + Math.floor(i / row) * PARK.cell];
+}
+/** The three chutes in the ceiling (their mouths), and where what they pour lands. */
+export const CHUTES: Vec3[] = [[-3.0, 7.55, -9.5], [2.5, 7.55, -13.5], [-0.6, 7.55, -19.0]];
+
+/** The orbs of a show of `n`: mostly glowing, some mirrors, some glass. */
+export function orbs(n: number): Orb[] {
+ const r = rng(7);
+ return Array.from({ length: n }, (_, i) => {
+ const u = r();
+ const kind: OrbKind = u < 0.78 ? "glow" : u < 0.9 ? "chrome" : "glass";
+ const size = kind === "glow" ? 0.09 + 0.07 * r() : kind === "chrome" ? 0.15 + 0.07 * r() : 0.18 + 0.08 * r();
+ return { kind, r: size, team: i % PALETTE.length, gain: 0.6 + 0.8 * r(), mass: BODY.density * (4 / 3) * Math.PI * size * size * size };
+ });
+}
+
+/** The camera at time t (s): a slow drift. */
+export function cameraAt(t: number): { pos: Vec3; target: Vec3; fov: number } {
+ return {
+ pos: [-3.6 + 0.8 * ksin(0.11 * t), 1.9 + 0.3 * ksin(0.19 * t + 1), 3.6 - 1.4 * (1 - kcos(0.07 * t))],
+ target: [4.5 + 1.0 * ksin(0.08 * t + 0.6), 2.7, -12],
+ fov: 60,
+ };
+}
+
+/**
+ * The show's timeline (seconds):
+ * 0 - 2 the first pour: 70 % of the orbs, from the three chutes in turn
+ * 3.5 a blast in the pile under chute 0
+ * 4.5 - 5.7 the rest pour
+ * 7.5, 11.5 … a blast every 4 s, under the next chute in turn; 1 s after each, 40 % of the orbs (the longest
+ * poured) are taken back up and pour again over 1.2 s
+ */
+export const SHOW = { firstPour: [0, 2] as const, firstShare: 0.7, secondPour: [4.5, 5.7] as const, firstBlast: 3.5, blastEvery: 4, rePourAfter: 1, rePourFor: 1.2, rePourShare: 0.4 };
+/** A blast: what it reaches (m), the speed it gives (m/s, at its centre), how long its flash lasts (s). */
+export const BLAST = { radius: 3.6, speed: 11, lift: 5, flash: 0.5, nits: 60000, glow: 6 };
+
+export interface Blast { at: Vec3; age: number; index: number }
+/** The blast whose flash is on at time t, if any. */
+export function blastAt(t: number): Blast | null {
+ if (t < SHOW.firstBlast) return null;
+ const index = Math.floor((t - SHOW.firstBlast) / SHOW.blastEvery);
+ const age = t - (SHOW.firstBlast + index * SHOW.blastEvery);
+ if (age > BLAST.flash) return null;
+ const c = CHUTES[index % CHUTES.length];
+ return { at: [c[0], 0.35, c[2]], age, index };
+}
+/** The flash: its fireball's radius (m) and brightness (relative to BLAST.nits). */
+export function flashOf(b: Blast): { radius: number; power: number } {
+ const grow = b.age < 0.08 ? b.age / 0.08 : 1;
+ // exp(-age / 0.12) from + - * / only: (1 - x/n)^n with n = 16.
+ let k = 1 - b.age / 0.12 / 16;
+ k = k < 0 ? 0 : k;
+ for (let i = 0; i < 4; i++) k *= k;
+ // The fireball grows for 80 ms, then shrinks as it fades.
+ return { radius: (0.15 + 0.9 * grow) * (0.35 + 0.65 * Math.sqrt(Math.sqrt(k))), power: k };
+}
+
+/** What a show asks of the engine it runs in. */
+export interface Actuator {
+ /** Puts orb i at p with velocity v (no spin), waking it. */
+ teleport(i: number, p: Vec3, v: Vec3): void;
+ /** A push (N s) through orb i's centre. */
+ impulse(i: number, x: number, y: number, z: number): void;
+ /** Orb i's brightness (1 = resting). */
+ glow(i: number, g: number): void;
+}
+
+/** The show's logic, a frame at a time: releases (teleports) orbs into the chutes, blasts the piles, flashes and
+ * fades the orbs a blast reached. The orbs' positions come from the engine's physics (`positions()`, x y z an orb;
+ * asked for only on a blast's frame). */
+export class Show {
+ readonly n: number;
+ readonly orbs: Orb[];
+ t = 0;
+ frame = 0;
+ /** Orbs released so far (the next to pour is released % n). */
+ released = 0;
+ blasts = 0;
+ glow: Float64Array;
+ private sent: Float64Array;
+ private rand = rng(23);
+ stats = { released: 0, blasted: 0, glowSends: 0 };
+
+ constructor(n: number) {
+ this.n = n;
+ this.orbs = orbs(n);
+ this.glow = new Float64Array(n).fill(1);
+ this.sent = new Float64Array(n).fill(1);
+ }
+
+ /** How many orbs should have been released by time t. */
+ private due(t: number): number {
+ const n = this.n, S = SHOW;
+ const ramp = (a: number, b: number, count: number) => (t <= a ? 0 : t >= b ? count : Math.floor((count * (t - a)) / (b - a)));
+ const first = Math.round(n * S.firstShare);
+ let due = ramp(S.firstPour[0], S.firstPour[1], first) + ramp(S.secondPour[0], S.secondPour[1], n - first);
+ // Every blast after the first, a re-pour.
+ for (let k = 0; ; k++) {
+ const a = S.firstBlast + k * S.blastEvery + S.rePourAfter;
+ if (k === 0 || a > t) { if (a > t) break; else continue; }
+ due += ramp(a, a + S.rePourFor, Math.round(n * S.rePourShare));
+ }
+ return due;
+ }
+
+ step(dt: number, positions: () => ArrayLike<number>, act: Actuator): void {
+ this.t += dt;
+ this.frame++;
+ const t = this.t;
+ let released = 0, blasted = 0;
+ // Releases: into the chutes in turn, a little spread, falling.
+ for (const due = this.due(t); this.released < due; this.released++) {
+ const i = this.released % this.n, c = CHUTES[this.released % CHUTES.length], r = this.rand;
+ const a = r() * TAU, d = 0.35 * Math.sqrt(r());
+ act.teleport(i, [c[0] + d * kcos(a), c[1] - this.orbs[i].r, c[2] + d * ksin(a)], [0.6 * (r() - 0.5), -2 - 1.5 * r(), 0.6 * (r() - 0.5)]);
+ released++;
+ }
+ // A blast: every orb in reach is pushed out and up, and flashes.
+ const due = t < SHOW.firstBlast ? 0 : Math.floor((t - SHOW.firstBlast) / SHOW.blastEvery) + 1;
+ if (due > this.blasts) {
+ const pos = positions();
+ const c = CHUTES[this.blasts % CHUTES.length], R = BLAST.radius;
+ for (let i = 0; i < this.n; i++) {
+ const dx = pos[i * 3] - c[0], dy = pos[i * 3 + 1] - 0.35, dz = pos[i * 3 + 2] - c[2];
+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz);
+ if (d > R) continue;
+ const f = 1 - d / R, m = this.orbs[i].mass, inv = 1 / (d + 1e-3);
+ act.impulse(i, m * BLAST.speed * f * dx * inv, m * (BLAST.speed * f * (dy > 0 ? dy : 0) * inv + BLAST.lift * f), m * BLAST.speed * f * dz * inv);
+ if (this.orbs[i].kind === "glow") this.glow[i] = 1 + (BLAST.glow - 1) * f;
+ blasted++;
+ }
+ this.blasts = due;
+ }
+ // Flashes fade back to the resting glow.
+ let sends = 0;
+ for (let i = 0; i < this.n; i++) {
+ if (this.glow[i] > 1) this.glow[i] = this.glow[i] - 1 < 0.01 ? 1 : 1 + (this.glow[i] - 1) * 0.9;
+ const g = this.glow[i], s = this.sent[i];
+ if (this.orbs[i].kind === "glow" && (g > s * 1.03 || g < s / 1.03 || (g === 1 && s !== 1))) {
+ act.glow(i, g);
+ this.sent[i] = g;
+ sends++;
+ }
+ }
+ this.stats = { released, blasted, glowSends: sends };
+ }
+}
diff --git a/packages/scene/README.md b/packages/scene/README.md
index cb1d0c9..eefb1ea 100644
--- a/packages/scene/README.md
+++ b/packages/scene/README.md
@@ -66,6 +66,7 @@ This package builds the scene. A ThreeRT client draws it:
- **Models and environments**: `GLTFModel`, `HDRIEnvironment`, `SkyAtmosphere` (a physical sky lit by the sun), height fog.
- **What a path tracer adds**: emissive surfaces that light the room, `RectAreaLight`, volumes (`FogVolume`, `Fireball`, smoke), water, material functions (a WGSL body run at every hit) and procedural geometry.
- **Physics**: `mesh.physics = "dynamic"`, joints as objects, `Raycaster.intersectPhysics`, `Shapecaster`.
+- **Live rendering settings**: `rendering.set({ quality: "performance", reconstruction: ["dlss-rr", "metalfx-denoised", "builtin"] })` requests a render resolution and a denoiser / upscaler on this device; `rendering.status()` reports what actually ran and why not the rest. See [settings and SDK support](https://github.com/meshy-dev/ThreeRT/blob/main/docs/RUNTIME.md#live-rendering-settings).
Games add state and input with [`@threert/gameplay`](https://www.npmjs.com/package/@threert/gameplay); destructible voxel worlds use [`@threert/voxel`](https://www.npmjs.com/package/@threert/voxel).
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 3edcf94..60b55fa 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -17,6 +17,7 @@ import {
import { BoxGeometry, BufferGeometry, CapsuleGeometry, SphereGeometry } from "./geometry.ts";
import { Matrix4, Quaternion, Vector3 } from "./math.ts";
import { ENGINE_IDS, engineColliders } from "./raycaster.ts";
+import type { RenderingBinding } from "./rendering.ts";
/** A joint's state in the binding once the engine let go of it (`Joint.broken`). */
const BROKEN = "broken";
@@ -195,7 +196,7 @@ export interface SettingsDesc {
}
/** The engine API. Ids are chosen by the caller (`SceneBinding`); every call takes effect at the engine's next commit. */
-export interface Engine {
+export interface Engine extends RenderingBinding {
/** `groups`: (first index, index count, material index) per group, for meshes with several materials. */
/** `colors`: the vertex colours (three.js's `color` attribute), linear RGB per vertex. */
geometry(id: number, positions: Float32Array, normals: Float32Array, uvs: Float32Array, indices: Uint32Array, groups?: Uint32Array | null, colors?: Float32Array | null): void;
diff --git a/packages/scene/src/index.ts b/packages/scene/src/index.ts
index b6d994d..2c2c9c5 100644
--- a/packages/scene/src/index.ts
+++ b/packages/scene/src/index.ts
@@ -2,6 +2,7 @@ export * from "./math.ts";
export * from "./geometry.ts";
export * from "./core.ts";
export * from "./engine.ts";
+export { rendering, type RenderingRequest, type RenderingStatus, type ReconstructionMethod, type ReconstructionRequest, type QualityRequest, type FrameGenerationRequest, type LatencyRequest, type SkipReason } from "./rendering.ts";
export * from "./materials.ts";
export { PyRandom } from "./pyrandom.ts";
export { encodePNG, contentHash, packGLB } from "./encode.ts";
diff --git a/packages/scene/src/rendering.ts b/packages/scene/src/rendering.ts
new file mode 100644
index 0000000..06893d1
--- /dev/null
+++ b/packages/scene/src/rendering.ts
@@ -0,0 +1,82 @@
+/**
+ * The live view's rendering settings, one per gap between what a frame affords and what is shown (the renderer's
+ * src/live/rendering.rs has the whole table):
+ *
+ * - `quality`: how many rays, as the render resolution (`"auto"`: dynamic resolution).
+ * - `reconstruction`: the noise and the missing pixels. ThreeRT's own denoiser and upscaler (`"builtin"`), an upscaler
+ * that replaces only the upscaling (`"dlss"`, `"metalfx"`, `"fsr"`), or a joint denoiser that replaces both and
+ * reads the noisy signal itself (`"dlss-rr"`, `"metalfx-denoised"`). A list is an order of preference.
+ * - `frameGeneration`: frames shown per frame rendered (none is integrated yet: it reports itself unavailable).
+ * - `latency`: how far the CPU may run ahead of the GPU.
+ *
+ * Each is a request: the renderer runs what the device supports and `status()` says what ran and why not the rest.
+ * They are device-local view settings (a player's graphics options), not scene state, and are not replicated.
+ */
+
+/** One way of reconstructing the frame. `custom:<id>` names a provider the embedding renderer registered. */
+export type ReconstructionMethod = "builtin" | "off" | "fsr" | "metalfx" | "metalfx-denoised" | "dlss" | "dlss-rr" | `custom:${string}`;
+export type ReconstructionRequest = "auto" | ReconstructionMethod | readonly ReconstructionMethod[];
+export type QualityRequest = "auto" | "native" | "quality" | "balanced" | "performance" | "ultra-performance" | number;
+export type FrameGenerationRequest = "off" | "auto" | "2x" | "3x" | "4x";
+export type LatencyRequest = "off" | "auto" | "on";
+
+/** The settings to change; those left out stay as they are. */
+export interface RenderingRequest {
+ quality?: QualityRequest;
+ reconstruction?: ReconstructionRequest;
+ frameGeneration?: FrameGenerationRequest;
+ latency?: LatencyRequest;
+}
+
+export type SkipReason = "unavailable" | "unsupported" | "provider-error" | "diagnostic-view";
+
+export interface RenderingStatus {
+ readonly quality: { readonly requested: string; readonly scale: number; readonly dynamic: boolean };
+ readonly reconstruction: {
+ /** The request, as a comma-separated list or "auto". */
+ readonly requested: string;
+ /** The method the last frame ran; null before the first frame. */
+ readonly active: ReconstructionMethod | null;
+ /** Who removed the noise and who upscaled: "builtin", "none" or a method. */
+ readonly denoise: string;
+ readonly upscale: string;
+ /** Why the first method asked for did not run (null when it did, or for "auto"). */
+ readonly fallback: SkipReason | null;
+ /** Every method tried before the one that ran, and why it did not. */
+ readonly skipped: readonly { readonly method: string; readonly reason: SkipReason; readonly detail: string }[];
+ };
+ readonly frameGeneration: { readonly requested: FrameGenerationRequest; readonly active: "off"; readonly fallback: "unavailable" | null };
+ readonly latency: { readonly requested: LatencyRequest; readonly active: "on" | "off"; readonly framesInFlight: number };
+}
+
+/** Wire methods on the scene's engine binding (native QuickJS or browser WASM): the request and status as JSON. */
+export interface RenderingBinding {
+ setRendering?(json: string): void;
+ renderingStatus?(): string;
+}
+
+function binding(): RenderingBinding | undefined {
+ const runtime: typeof globalThis & { __engine?: RenderingBinding } = globalThis;
+ return runtime.__engine;
+}
+
+/** Device-local live-view settings; they do not edit scene settings or replicated game state. */
+export const rendering = {
+ /**
+ * Queue a change for the next frame. False if there is no renderer binding (not a support check: read `status()`).
+ * Throws a TypeError for an unknown setting or value.
+ */
+ set(request: RenderingRequest): boolean {
+ const engine = binding();
+ if (!engine?.setRendering) return false;
+ engine.setRendering(JSON.stringify(request));
+ return true;
+ },
+ /** What the last frame ran, with requests not yet applied shown as requested; undefined without a renderer. */
+ status(): RenderingStatus | undefined {
+ const text = binding()?.renderingStatus?.();
+ if (text === undefined) return undefined;
+ const status = JSON.parse(text) as RenderingStatus | null;
+ return status ?? undefined;
+ },
+};
diff --git a/renderer/Cargo.lock b/renderer/Cargo.lock
index 5a3c6f3..e5c1b83 100644
--- a/renderer/Cargo.lock
+++ b/renderer/Cargo.lock
@@ -235,6 +235,25 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "bindgen"
+version = "0.73.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
+dependencies = [
+ "bitflags 2.13.2",
+ "cexpr",
+ "clang-sys",
+ "log",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash 2.1.3",
+ "shlex",
+ "syn 3.0.9",
+]
+
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -392,6 +411,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.5"
@@ -415,6 +443,17 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "clang-sys"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading",
+]
+
[[package]]
name = "codespan-reporting"
version = "0.13.1"
@@ -720,6 +759,20 @@ dependencies = [
"libloading",
]
+[[package]]
+name = "dlss_wgpu"
+version = "6.0.1"
+source = "git+https://github.com/bevyengine/dlss_wgpu.git?rev=b35069de8640bfae383e65a46b7d16058b2994d2#b35069de8640bfae383e65a46b7d16058b2994d2"
+dependencies = [
+ "ash",
+ "bindgen",
+ "bitflags 2.13.2",
+ "cc",
+ "thiserror 2.0.21",
+ "uuid",
+ "wgpu",
+]
+
[[package]]
name = "document-features"
version = "0.2.12"
@@ -1563,6 +1616,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -1619,7 +1678,7 @@ dependencies = [
"naga-types",
"num-traits",
"once_cell",
- "rustc-hash",
+ "rustc-hash 1.1.0",
"spirv",
"thiserror 2.0.21",
"unicode-ident",
@@ -1633,7 +1692,7 @@ checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
dependencies = [
"hashbrown 0.17.1",
"indexmap",
- "rustc-hash",
+ "rustc-hash 1.1.0",
"thiserror 2.0.21",
]
@@ -1698,6 +1757,16 @@ dependencies = [
"jni-sys 0.3.1",
]
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
[[package]]
name = "num-bigint"
version = "0.4.8"
@@ -2342,6 +2411,16 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+[[package]]
+name = "prettyplease"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
+dependencies = [
+ "proc-macro2",
+ "syn 3.0.9",
+]
+
[[package]]
name = "proc-macro-crate"
version = "3.5.0"
@@ -2570,6 +2649,18 @@ dependencies = [
"bitflags 2.13.2",
]
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
[[package]]
name = "regex-automata"
version = "0.4.18"
@@ -2668,6 +2759,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -3207,7 +3304,9 @@ dependencies = [
"anyhow",
"base64 0.23.1",
"bytemuck",
+ "cc",
"cpal",
+ "dlss_wgpu",
"glam 0.30.10",
"gltf",
"half",
@@ -3227,6 +3326,7 @@ dependencies = [
"symphonia",
"tungstenite",
"ureq",
+ "uuid",
"voxel-core",
"web-time",
"wesl",
@@ -3443,6 +3543,16 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+[[package]]
+name = "uuid"
+version = "1.29.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
@@ -3773,7 +3883,7 @@ dependencies = [
"portable-atomic",
"profiling",
"raw-window-handle",
- "rustc-hash",
+ "rustc-hash 1.1.0",
"smallvec",
"thiserror 2.0.21",
"wgpu-core-deps-apple",
diff --git a/renderer/Cargo.toml b/renderer/Cargo.toml
index 72df7ab..081bf64 100644
--- a/renderer/Cargo.toml
+++ b/renderer/Cargo.toml
@@ -63,12 +63,18 @@ cpal = { version = "0.17", optional = true }
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
libloading = { version = "0.8", optional = true }
+# DLSS Super Resolution (Vulkan). This wgpu 30 release is not published on crates.io.
+[target.'cfg(all(target_arch = "x86_64", any(target_os = "linux", target_os = "windows")))'.dependencies]
+dlss_wgpu = { git = "https://github.com/bevyengine/dlss_wgpu.git", rev = "b35069de8640bfae383e65a46b7d16058b2994d2", optional = true }
+uuid = { version = "1", optional = true }
+
# The performance cores' count (src/physics.rs: the physics' threads).
[target.'cfg(target_os = "macos")'.dependencies]
libc = "0.2"
# build.rs reads shaders/live.wgsl's bindings with the compiler wgpu uses (its version: 30), when the crate is built.
[build-dependencies]
+cc = "1"
naga = { version = "30", features = ["wgsl-in"] }
# src/merged.rs's tests read the generated shaders with the compiler wgpu uses: they are valid, and no stage binds more
@@ -97,6 +103,8 @@ audio = ["dep:symphonia", "dep:cpal", "dep:libloading"]
net = ["dep:tungstenite", "dep:ureq", "dep:rustls"]
# Intel Open Image Denoise (needs OIDN_DIR at build time and the shared libs at runtime).
oidn = ["dep:oidn"]
+# NVIDIA DLSS Super Resolution (needs DLSS_SDK and VULKAN_SDK at build time).
+dlss = ["dep:dlss_wgpu", "dep:uuid"]
[profile.release]
opt-level = 3
diff --git a/renderer/build.rs b/renderer/build.rs
index 0168ab6..4332376 100644
--- a/renderer/build.rs
+++ b/renderer/build.rs
@@ -9,6 +9,18 @@ use naga::{AddressSpace, ImageClass, ImageDimension, ScalarKind, StorageAccess,
use std::fmt::Write;
fn main() {
+ // `cfg(dlss)`: the `dlss` feature on a target NGX supports (x86-64 Windows or Linux); elsewhere it builds nothing.
+ println!("cargo:rustc-check-cfg=cfg(dlss)");
+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
+ if std::env::var_os("CARGO_FEATURE_DLSS").is_some() && std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64") && (os == "windows" || os == "linux") {
+ println!("cargo:rustc-cfg=dlss");
+ }
+ if os == "macos" {
+ println!("cargo:rerun-if-changed=src/live/metalfx.m");
+ cc::Build::new().file("src/live/metalfx.m").flag("-fobjc-arc").compile("threert_metalfx");
+ println!("cargo:rustc-link-lib=framework=Foundation");
+ println!("cargo:rustc-link-lib=framework=Metal");
+ }
let files = ["shaders/records.wgsl", "shaders/live.wgsl"];
for path in files {
println!("cargo:rerun-if-changed={path}");
diff --git a/renderer/shaders/fsr.wgsl b/renderer/shaders/fsr.wgsl
new file mode 100644
index 0000000..ee7be6e
--- /dev/null
+++ b/renderer/shaders/fsr.wgsl
@@ -0,0 +1,185 @@
+// WGSL port of the FP32 EASU, RCAS, and SRTM math in AMD FidelityFX Super Resolution 1:
+// https://github.com/GPUOpen-Effects/FidelityFX-FSR/blob/master/ffx-fsr/ffx_fsr1.h
+//
+// FidelityFX Super Resolution Sample
+// Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files(the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions :
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+@group(1) @binding(0) var fsr_easu_out: texture_storage_2d<rgba32float, write>;
+@group(1) @binding(1) var fsr_easu_in: texture_2d<f32>;
+
+// In one axis, 8 output lanes span at most 8 input centers (input <= output), plus EASU's
+// border at -1/+2. Reserve one extra slot for rounding. Cache perceptual RGB and luma together.
+var<workgroup> fsr_input_tile: array<vec4<f32>, 144>;
+const FSR_HEADROOM: f32 = 1.0 / 1048576.0;
+
+fn fsr_max3(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)); }
+fn fsr_luma(c: vec3<f32>) -> f32 { return c.g + 0.5 * (c.r + c.b); }
+
+fn fsr_exposure() -> f32 { return clamp(L.misc.x, 0.00001, 64.0); }
+
+// SRTM divides by (1 + max(rgb)). Apply that curve to the gamma-2 proxy instead of taking
+// gamma after the curve: the shoulder keeps much more floating-point headroom for HDR highlights.
+// The manual exposure sets the knee; auto exposure and display tonemapping still run after RCAS.
+fn fsr_pack_hdr(rgb: vec3<f32>, gamma_knee: f32) -> vec4<f32> {
+ let gamma = sqrt(rgb); // compose already guarantees finite nonnegative RGB
+ let peak = fsr_max3(gamma);
+ let c = gamma / max(gamma_knee + peak, (1.0 + FSR_HEADROOM) * peak);
+ return vec4<f32>(c, fsr_luma(c));
+}
+
+fn fsr_unpack_hdr(c: vec3<f32>) -> vec3<f32> {
+ let gamma = c / max(1.0 - fsr_max3(c), FSR_HEADROOM);
+ return (gamma * gamma) / fsr_exposure();
+}
+
+fn fsr_input_position(p: vec2<u32>, scale: vec2<f32>) -> vec2<f32> {
+ // FsrEasuCon: output center in input texel coordinates; the trace samples at (0.5, 0.5).
+ return (vec2<f32>(p) + 0.5) * scale - 0.5;
+}
+
+// FsrEasuSetF: direction and gradient reversal for one of the four surrounding centers.
+fn fsr_edge(a: f32, b: f32, c: f32, d: f32, e: f32) -> vec3<f32> {
+ let dir = vec2<f32>(d - b, e - a);
+ let slope = max(abs(vec2<f32>(d, e) - c), abs(c - vec2<f32>(b, a)));
+ let span = min(abs(dir) / max(slope, vec2<f32>(1.0e-12)), vec2<f32>(1.0));
+ return vec3<f32>(dir, dot(span, span));
+}
+
+// FsrEasuTapF: rotated and stretched polynomial Lanczos-2 with an adaptive window.
+fn fsr_tap(offset: vec2<f32>, dir: vec2<f32>, axis: vec2<f32>, lobe: f32, clip: f32, delta: vec3<f32>) -> vec4<f32> {
+ let v = axis * vec2<f32>(dot(offset, dir), dot(offset, vec2<f32>(-dir.y, dir.x)));
+ let d2 = min(dot(v, v), clip);
+ let base = 0.4 * d2 - 1.0;
+ let window = lobe * d2 - 1.0;
+ let weight = (1.5625 * base * base - 0.5625) * (window * window);
+ return vec4<f32>(delta, 1.0) * weight;
+}
+
+@compute @workgroup_size(8, 8)
+fn fsr_easu(@builtin(global_invocation_id) id: vec3<u32>, @builtin(workgroup_id) group: vec3<u32>, @builtin(local_invocation_index) lane: u32) {
+ let input = L.isz.xy;
+ let output = L.size.xy;
+ let scale = vec2<f32>(input) / vec2<f32>(output);
+ let first = group.xy * 8u;
+ let last = min(first + 7u, output - 1u);
+ let origin = vec2<i32>(floor(fsr_input_position(first, scale))) - 1;
+ let extent = vec2<u32>(vec2<i32>(floor(fsr_input_position(last, scale))) + 3 - origin);
+ let gamma_knee = inverseSqrt(fsr_exposure());
+ for (var i = lane; i < extent.x * extent.y; i += 64u) {
+ let p = origin + vec2<i32>(i32(i % extent.x), i32(i / extent.x));
+ let q = vec2<u32>(clamp(p, vec2<i32>(0), vec2<i32>(input) - 1));
+ fsr_input_tile[i] = fsr_pack_hdr(fb[q.y * input.x + q.x].rgb, gamma_knee);
+ }
+ workgroupBarrier();
+ if (any(id.xy >= output)) { return; }
+
+ // FsrEasuF's 12 input taps, gathered from the tile rather than a filtered texture:
+ // b c
+ // e f g h
+ // i j k l
+ // n o
+ let position = fsr_input_position(id.xy, scale);
+ let pixel = floor(position);
+ let pp = position - pixel;
+ let q = vec2<u32>(vec2<i32>(pixel) - origin);
+ let w = extent.x;
+ let at = q.y * w + q.x;
+ let b = fsr_input_tile[at - w];
+ let c = fsr_input_tile[at - w + 1u];
+ let e = fsr_input_tile[at - 1u];
+ let f = fsr_input_tile[at];
+ let g = fsr_input_tile[at + 1u];
+ let h = fsr_input_tile[at + 2u];
+ let i = fsr_input_tile[at + w - 1u];
+ let j = fsr_input_tile[at + w];
+ let k = fsr_input_tile[at + w + 1u];
+ let l = fsr_input_tile[at + w + 2u];
+ let n = fsr_input_tile[at + 2u * w];
+ let o = fsr_input_tile[at + 2u * w + 1u];
+
+ let edge = mix(mix(fsr_edge(b.w, e.w, f.w, g.w, j.w), fsr_edge(c.w, f.w, g.w, h.w, k.w), pp.x),
+ mix(fsr_edge(f.w, i.w, j.w, k.w, n.w), fsr_edge(g.w, j.w, k.w, l.w, o.w), pp.x), pp.y);
+ let d2 = dot(edge.xy, edge.xy);
+ var dir = vec2<f32>(1.0, 0.0);
+ if (d2 >= 1.0 / 32768.0) { dir = edge.xy * inverseSqrt(d2); }
+ let edge_len = (0.5 * edge.z) * (0.5 * edge.z);
+ let stretch = dot(dir, dir) / max(abs(dir.x), abs(dir.y));
+ let axis = vec2<f32>(1.0 + (stretch - 1.0) * edge_len, 1.0 - 0.5 * edge_len);
+ let lobe = 0.5 - 0.29 * edge_len;
+ let clip = 1.0 / lobe;
+
+ // Center the sum at f so flat HDR colors survive without weight-normalization error.
+ var acc = fsr_tap(vec2<f32>(0.0, -1.0) - pp, dir, axis, lobe, clip, b.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 1.0, -1.0) - pp, dir, axis, lobe, clip, c.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>(-1.0, 1.0) - pp, dir, axis, lobe, clip, i.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 0.0, 1.0) - pp, dir, axis, lobe, clip, j.rgb - f.rgb);
+ acc += fsr_tap(-pp, dir, axis, lobe, clip, vec3<f32>(0.0));
+ acc += fsr_tap(vec2<f32>(-1.0, 0.0) - pp, dir, axis, lobe, clip, e.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 1.0, 1.0) - pp, dir, axis, lobe, clip, k.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 2.0, 1.0) - pp, dir, axis, lobe, clip, l.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 2.0, 0.0) - pp, dir, axis, lobe, clip, h.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 1.0, 0.0) - pp, dir, axis, lobe, clip, g.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 1.0, 2.0) - pp, dir, axis, lobe, clip, o.rgb - f.rgb);
+ acc += fsr_tap(vec2<f32>( 0.0, 2.0) - pp, dir, axis, lobe, clip, n.rgb - f.rgb);
+ let lo = min(min(f.rgb, g.rgb), min(j.rgb, k.rgb));
+ let hi = max(max(f.rgb, g.rgb), max(j.rgb, k.rgb));
+ let rgb = clamp(f.rgb + acc.rgb / acc.a, lo, hi);
+ textureStore(fsr_easu_out, vec2<i32>(id.xy), vec4<f32>(rgb, 1.0));
+}
+
+fn fsr_rcas_load(p: vec2<i32>, high: vec2<i32>) -> vec3<f32> {
+ return textureLoad(fsr_easu_in, clamp(p, vec2<i32>(0), high), 0).rgb;
+}
+
+@compute @workgroup_size(8, 8)
+fn fsr_rcas_to_post(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (any(id.xy >= L.size.xy)) { return; }
+ let p = vec2<i32>(id.xy);
+ let high = vec2<i32>(L.size.xy) - 1;
+ let b = fsr_rcas_load(p + vec2<i32>( 0, -1), high);
+ let d = fsr_rcas_load(p + vec2<i32>(-1, 0), high);
+ let e = textureLoad(fsr_easu_in, p, 0).rgb;
+ let f = fsr_rcas_load(p + vec2<i32>( 1, 0), high);
+ let h = fsr_rcas_load(p + vec2<i32>( 0, 1), high);
+
+ // FsrRcasF's per-channel clipping constraints. An empty ring channel cannot ring below black.
+ let mn4 = min(min(b, d), min(f, h));
+ let mx4 = max(max(b, d), max(f, h));
+ let lo = min(mn4, e);
+ let hi = max(mx4, e);
+ let hit_min = select(vec3<f32>(0.25), lo / max(4.0 * mx4, vec3<f32>(1.0e-12)), mx4 > vec3<f32>(0.0));
+ let hit_max = (hi - 1.0) / (4.0 * max(1.0 - mn4, vec3<f32>(FSR_HEADROOM)));
+ let limit = clamp(fsr_max3(max(-hit_min, hit_max)), -(0.25 - 1.0 / 16.0), 0.0);
+ // One stop of sharpening and the reference RCAS noise suppression for residual trace noise.
+ let lb = fsr_luma(b); let ld = fsr_luma(d); let le = fsr_luma(e); let lf = fsr_luma(f); let lh = fsr_luma(h);
+ let lr = max(max(max(lb, ld), max(lf, lh)), le) - min(min(min(lb, ld), min(lf, lh)), le);
+ let nz = clamp(abs(0.25 * ((lb - le) + (ld - le) + (lf - le) + (lh - le))) / max(lr, 1.0e-12), 0.0, 1.0);
+ let lobe = 0.5 * limit * (1.0 - 0.5 * nz);
+ let delta = (b - e) + (d - e) + (f - e) + (h - e);
+ var rgb = max(e + delta * (lobe / (1.0 + 4.0 * lobe)), vec3<f32>(0.0));
+
+ // A small overshoot near the SRTM asymptote can create a huge linear highlight. Preserve
+ // hue and retain at least 75% of the brightest neighbor's headroom there.
+ let ceiling = max(0.975, 1.0 - 0.75 * (1.0 - fsr_max3(hi)));
+ let peak = fsr_max3(rgb);
+ if (peak > ceiling) { rgb *= ceiling / peak; }
+ let color = fsr_unpack_hdr(rgb);
+ let i = id.y * L.size.x + id.x;
+ let img = vec4<f32>(color, dof_coc(sample_vel[sample_under(id.x, id.y)].z));
+ if (L.misc2.z > 0.0 || L.dof.x > 0.0) { sb[i] = img; } else { fa[i] = img; }
+}
diff --git a/renderer/shaders/live.wgsl b/renderer/shaders/live.wgsl
index 8b2f334..0e60c86 100644
--- a/renderer/shaders/live.wgsl
+++ b/renderer/shaders/live.wgsl
@@ -1003,7 +1003,19 @@ fn compose(@builtin(global_invocation_id) gid: vec3<u32>) {
let q = gid.y * iw + gid.x;
let px = sample_px[q];
let t = px.color.w;
- let c = (fa[q].rgb * max(px.albedo.rgb, vec3<f32>(0.02)) + spec_load(1u, q).rgb) * medium_tr(q) + sample_emission(q) + direct_in[q].rgb;
+ var lighting: vec3<f32>;
+ if (L.mode.w == 1u) {
+ // The trace kept the whole specular path, including deferred-cache lighting. No irradiance
+ // demodulation or temporal/spatial filter here. Keep the pre-reconstruction signals for snapshots.
+ var spec = finite_or_zero(px.spec.rgb / L.misc2.w);
+ let ceiling = sample_clamp();
+ spec *= min(1.0, ceiling / max(lum(spec), 1e-8));
+ spec_store(1u, q, vec4<f32>(spec, 1.0));
+ lighting = sample_diffuse(q) + spec;
+ } else {
+ lighting = fa[q].rgb * max(px.albedo.rgb, vec3<f32>(0.02)) + spec_load(1u, q).rgb;
+ }
+ let c = lighting * medium_tr(q) + sample_emission(q) + direct_in[q].rgb;
let sp = sample_pos(i32(gid.x), i32(gid.y));
let dir = ray_dir(L.cur, sp.x, sp.y);
var p = L.cur.pos.xyz + dir * 1.0e6;
diff --git a/renderer/shaders/pathtrace.wgsl b/renderer/shaders/pathtrace.wgsl
index 07776d8..197d9a7 100644
--- a/renderer/shaders/pathtrace.wgsl
+++ b/renderer/shaders/pathtrace.wgsl
@@ -1476,6 +1476,9 @@ struct Lobes {
// Not here: the radiance scaling by the indices' ratio squared (as Cycles and glTF's formula: it cancels over a
// closed solid, and a single-sheet pane, which refracts as a solid here, would be scaled once); thin walls;
// absorption by distance.
+// Smoother than this a reflection or refraction is sharp enough that an emitter seen through it needs no denoising
+// (`delta_path`; a polished floor's 0.035 still spreads it over pixels).
+const DELTA_ROUGHNESS: f32 = 0.025;
const GLASS_DELTA: f32 = 0.05; // roughness (RTXPT 0.04, Falcor 0.08)
// Unpolarised Fresnel reflectance: `c` the cosine on the incident side, `eta` = n(far) / n(incident); 1 at total
@@ -3083,6 +3086,7 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
};
@group(1) @binding(1) var<storage, read_write> ML: MergedLive;
fn refl_len() -> u32 { return P.live_len.x; }
+ fn refl_load(i: u32) -> vec4<f32> { return ML.vecs[P.live_first[0].y + i]; }
fn refl_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].y + i] = v; }
fn motion_len() -> u32 { return P.live_len.y; }
fn motion_store(i: u32, v: vec4<f32>) { ML.vecs[P.live_first[0].z + i] = v; }
@@ -3110,6 +3114,7 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
@group(1) @binding(6) var<storage, read_write> motion_out: array<vec4<f32>>;
@group(1) @binding(7) var<storage, read_write> direct_out: array<vec4<f32>>;
fn refl_len() -> u32 { return arrayLength(&refl); }
+ fn refl_load(i: u32) -> vec4<f32> { return refl[i]; }
fn refl_store(i: u32, v: vec4<f32>) { refl[i] = v; }
fn motion_len() -> u32 { return arrayLength(&motion_out); }
fn motion_store(i: u32, v: vec4<f32>) { motion_out[i] = v; }
@@ -3149,7 +3154,7 @@ fn sphere_hit(x: vec3<f32>, l: vec3<f32>, hit: Hit) -> vec3<f32> {
fn resolve_bound() -> bool { return LIVE && refl_len() >= 2u * P.size.x * P.size.y; }
// THREERT_CACHE_FLAGS bit 16 turns the resolve off (rays then stay in their pixel's specular, the resolve reads zeros).
-fn resolve_on() -> bool { return resolve_bound() && (u32(P.cache.w) & 16u) == 0u; }
+fn resolve_on() -> bool { return resolve_bound() && P.motion.y == 0.0 && (u32(P.cache.w) & 16u) == 0u; }
// Density of l under the base specular lobe alone (VNDF sampling).
fn pdf_spec(s: Surface, lb: Lobes, v: vec3<f32>, l: vec3<f32>) -> f32 {
@@ -3507,6 +3512,88 @@ fn finish(@builtin(global_invocation_id) gid: vec3<u32>) {
accum[pix] = px;
}
+// Deterministic reconstruction guides at smooth reflectors. Using the random BSDF sample makes
+// glass alternate between two different materials and leaves a hole wherever a diffuse lobe was drawn.
+struct GuideHit { albedo: vec3<f32>, normal: vec3<f32>, rough: f32, distance: f32 };
+fn guide_color(radiance: vec3<f32>) -> vec3<f32> {
+ // Keep a dark background dark and preserve the hue of bright emitters in the albedo guide.
+ return radiance / max(1.0, max(radiance.r, max(radiance.g, radiance.b)));
+}
+fn guide_hit(origin: vec3<f32>, dir: vec3<f32>, footprint: f32, through_glass: bool) -> GuideHit {
+ var o = offset_origin(origin, dir);
+ var d = dir;
+ var first = 0.0;
+ for (var i = 0u; i < 2u; i++) {
+ let h = trace(o, d, INF, TRACE_CLOSEST);
+ if (h.tri == 0xffffffffu) {
+ var sky = env_radiance(d);
+ if (through_glass) { sky = sky_mis(d, 0.0); }
+ return GuideHit(guide_color(sky), -d, 1.0, select(first, 1e4, i == 0u));
+ }
+ if (i == 0u) { first = h.t; }
+ let s = surface(o, d, h, footprint + h.t * 2.0 * P.cam_pos.w / lod_height());
+ // Continue through the back face of a clear solid to the material visible behind it.
+ if (i == 0u && through_glass && !s.front && s.transmission > 0.0 && s.roughness < GLASS_DELTA) {
+ let exit_d = refract(d, s.n, s.ior);
+ d = select(reflect(d, s.n), exit_d, dot(exit_d, exit_d) > 0.0);
+ o = offset_origin(s.p, d);
+ continue;
+ }
+ let m = lobes(s, max(dot(s.n, -d), 1e-4));
+ let emission = guide_color(s.emissive);
+ return GuideHit(clamp(max(cache_reflectance(m), emission), vec3<f32>(0.0), vec3<f32>(1.0)), s.n, s.roughness, first);
+ }
+ return GuideHit(vec3<f32>(1.0), -d, 1.0, first);
+}
+
+@compute @workgroup_size(8, 8) fn surface_guides(@builtin(global_invocation_id) gid: vec3<u32>) {
+ if (any(gid.xy >= P.size.xy)) { return; }
+ let q = gid.y * P.size.x + gid.x;
+ let px = accum[q];
+ let diffuse = refl_load(2u*q);
+ let specular = refl_load(2u*q+1u);
+ var alb = diffuse.rgb;
+ var normal = px.normal.xyz;
+ var rough = px.emit.w;
+ // Rough surfaces have no single reflected point. A stochastic second-bounce hit would move
+ // their guide even when both the object and camera stand still.
+ accum[q].spec.w = 0.0;
+ if (px.color.w > 0.0 && rough < MIRROR_ROUGHNESS && P.raster.w == 0.0 &&
+ (any(specular.rgb > vec3<f32>(0.005)) || diffuse.w > 0.0)) {
+ cur_depth = 1u;
+ mirror_path = true;
+ let ndc = ((vec2<f32>(gid.xy) + P.raster.yz) / vec2<f32>(P.size.xy) * 2.0 - 1.0) * vec2<f32>(1.0, -1.0);
+ let d = normalize(P.cam_fwd.xyz + P.cam_right.xyz * ndc.x * P.cam_pos.w * P.cam_fwd.w + P.cam_up.xyz * ndc.y * P.cam_pos.w);
+ let x = P.cam_pos.xyz + d * px.color.w;
+ let width = px.color.w * 2.0 * P.cam_pos.w / lod_height();
+ let reflected = guide_hit(x, reflect(d, normal), width, false);
+ accum[q].spec.w = reflected.distance;
+ // At a mirror or clear pane the visible material is the secondary surface. Preserve primary
+ // depth and motion for silhouettes, disocclusions and post; only the denoiser gets virtual guides.
+ let sharp = 1.0 - smoothstep(GLASS_DELTA, 0.18, rough);
+ let reflection = clamp(max(specular.r, max(specular.g, specular.b)), 0.0, 1.0);
+ var virtual_n = reflect(reflected.normal, normal);
+ var virtual_r = reflected.rough;
+ var share = reflection;
+ alb += sharp * specular.rgb * reflected.albedo;
+ if (diffuse.w > 0.0 && specular.w > 0.0) {
+ let refracted = refract(d, normal, specular.w);
+ if (dot(refracted, refracted) > 0.0) {
+ let transmitted = guide_hit(x, refracted, width, true);
+ let weight = diffuse.w * (1.0 - reflection);
+ alb += sharp * weight * px.albedo.rgb * transmitted.albedo;
+ if (weight > reflection) { virtual_n = transmitted.normal; virtual_r = transmitted.rough; }
+ share += weight;
+ }
+ }
+ if (dot(virtual_n, normal) < 0.0) { virtual_n = -virtual_n; }
+ normal = normalize(mix(normal, virtual_n, sharp * min(share, 1.0)));
+ rough = mix(rough, virtual_r, sharp * min(share, 1.0));
+ }
+ refl_store(2u*q, vec4<f32>(alb, bitcast<f32>(oct_enc(select(vec3<f32>(0.0, 0.0, 1.0), normal, dot(normal, normal) > 0.0)))));
+ refl_store(2u*q+1u, vec4<f32>(specular.rgb, rough));
+}
+
// Live, after the trace: MEDIA_TRAIN_POINTS fresh estimates (point_radiance) into the volume voxels, each at a random
// point where a camera ray toward a random traced pixel crosses the media before its first hit.
@compute @workgroup_size(64, 1, 1)
@@ -3684,6 +3771,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
var refl_pdf = 0.0;
var refl_w = vec3<f32>(0.0);
var refl_e = vec3<f32>(0.0);
+ var guide_diffuse = vec3<f32>(0.0);
+ var guide_glass = vec2<f32>(0.0); // transmitted share and incident/transmitted index ratio
var through0 = false;
// The camera hit is transmissive (glass, water): its reflections stay in the specular signal too (the resolve's
// neighbours there mostly went through, so it had no rays to rebuild them from: live glass lost its reflection).
@@ -3692,6 +3781,9 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
dl_det = vec3<f32>(0.0);
dl_det_spec = vec3<f32>(0.0);
var specular_bounce = true;
+ // Every bounce so far a delta sample off a smooth mirror or clear glass: an emitter the path then hits is seen
+ // sharply (MetalFX denoised takes it as emission: upscaled, not denoised).
+ var delta_path = true;
// Glass passed since the last scattering vertex: any (behind_glass), and whether an odd number of surfaces (bent).
// The vertex's shadow rays toward emitters stopped at the glass and those toward the sky at bending glass, so
// what the path finds there counts in full; behind glass that does not bend (a pane) the sky and the directional
@@ -3796,6 +3888,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
bent = false;
straight = false;
mirror_path = false;
+ delta_path = false;
cone_w += cone_a * tk.t;
cone_a += 2.0;
if (depth >= P.counts.w) {
@@ -3876,7 +3969,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let lum = luminance(c);
if (lum > clamp_v) { c *= clamp_v / lum; }
}
- if (depth == 0u) { e0 += c; }
+ if (depth == 0u || (LIVE && P.motion.y > 0.5 && delta_path)) { e0 += c; }
radiance += c;
}
if (s.card) { break; }
@@ -3975,6 +4068,12 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
through0 = through;
glass0 = has(F_GLASS) && s.transmission > 0.0;
refl_e = lb.e_spec;
+ if (LIVE && P.motion.y > 0.5) {
+ // MetalFX takes the directional reflectances of the layered BSDF, including glass and coat.
+ guide_diffuse = lb.diffuse * lb.kd * (1.0 - lb.e_coat);
+ refl_e = cache_reflectance(lb) - guide_diffuse;
+ if (has(F_GLASS)) { guide_glass = vec2<f32>(s.transmission * (1.0 - s.metallic), lb.eta); }
+ }
if (sampled_spec && !through && lb.coat <= 0.0) {
refl_l = l;
refl_pdf = pdf_spec(s, lb, v, l);
@@ -4002,6 +4101,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
cone_w = width;
cone_a += 2.0 * s.roughness * s.roughness;
mirror_path = (depth == 0u || mirror_path) && s.roughness < MIRROR_ROUGHNESS && (sampled_spec || sampled_trans);
+ delta_path = delta_path && s.roughness < DELTA_ROUGHNESS && (sampled_spec || sampled_trans);
if (depth >= P.counts.w) {
let q = min(max(thr.x, max(thr.y, thr.z)), 0.95);
if (rng1(rng_dim(D_RR)) > q) { break; }
@@ -4033,7 +4133,11 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
if (P.misc.w < 0.5 && motion_len() >= w * h) {
motion_store(pix, select(vec4<f32>(0.0), mv, !non_finite(mv.xyz)));
}
- if (resolve_bound() && P.misc.w < 0.5) {
+ if (P.motion.y > 0.5 && P.misc.w < 0.5 && resolve_bound()) {
+ // The reconstruction consumes the noisy path itself. Its material guides reuse the idle ray slots.
+ refl_store(pix * 2u, vec4<f32>(guide_diffuse, guide_glass.x));
+ refl_store(pix * 2u + 1u, vec4<f32>(refl_e, guide_glass.y));
+ } else if (resolve_bound() && P.misc.w < 0.5) {
// Radiance along the specular ray: what the path gathered after it, over the ray's weight.
var li = vec3<f32>(0.0);
if (resolve && refl_pdf > 0.0) {
diff --git a/renderer/shaders/reconstruction.wgsl b/renderer/shaders/reconstruction.wgsl
new file mode 100644
index 0000000..a347e5e
--- /dev/null
+++ b/renderer/shaders/reconstruction.wgsl
@@ -0,0 +1,78 @@
+// The reconstruction contracts' signals (live/reconstruction.rs): the frame's packed into textures for a vendor's
+// upscaler or joint denoiser, and its output taken back into the post chain. Appended to live.wgsl so camera
+// conventions and post-process targets stay shared. Render attachments allow R8/R16/RG16 textures without optional
+// WebGPU storage formats.
+@vertex fn rc_vertex(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
+ let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
+ return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
+}
+struct RcInputs {
+ @location(0) color: vec4<f32>,
+ @location(1) depth: f32,
+ @location(2) motion: vec2<f32>,
+ @location(3) reactive: f32,
+};
+// A fixed radiometric unit between exposure changes. The post chain receives scene radiance again.
+fn rc_radiance_unit() -> f32 {
+ // A joint denoiser takes lighting near display white (its overlay keeps much brighter emitters); an upscaler
+ // the whole lit frame in a wider linear range. (live/reconstruction.rs `encode` passes the same unit.)
+ return select(32.0, 1.0, L.mode.w == 1u) / clamp(L.misc.x, 0.00001, 64.0);
+}
+fn pack_rc_inputs(p: vec4<f32>) -> RcInputs {
+ let q = u32(p.y) * L.isz.x + u32(p.x);
+ let v = sample_vel[q];
+ let color = clamp(fb[q].rgb / rc_radiance_unit(), vec3<f32>(0.0), vec3<f32>(65504.0));
+ // Infinite reverse-Z perspective, near 1 cm; zero is the sky (the frame's `view_to_clip`).
+ let depth = select(0.0, 0.01 / max(v.z, 0.01), v.z > 0.0);
+ let motion = -v.xy * vec2<f32>(L.isz.xy) / vec2<f32>(L.size.xy);
+ return RcInputs(vec4<f32>(color, 1.0), depth, motion, v.w);
+}
+@fragment fn rc_upscale_inputs(@builtin(position) p: vec4<f32>) -> RcInputs {
+ return pack_rc_inputs(p);
+}
+struct RcJointInputs {
+ @location(0) color: vec4<f32>,
+ @location(1) depth: f32,
+ @location(2) motion: vec2<f32>,
+ @location(3) reactive: f32,
+ @location(4) overlay: vec4<f32>,
+ @location(5) bypass_denoise: f32,
+};
+@fragment fn rc_joint_inputs(@builtin(position) p: vec4<f32>) -> RcJointInputs {
+ let base = pack_rc_inputs(p);
+ let q = u32(p.y) * L.isz.x + u32(p.x);
+ let px = sample_px[q];
+ // Directly visible sky and emitters are deterministic: the overlay, which the provider upscales with the same
+ // jitter and visibility as the denoised frame. A mixed or moving medium stays in color.
+ let direct = sample_emission(q);
+ let overlay = medium_share(q) == 0.0 && (px.color.w == 0.0 || lum(direct) > max(0.001, 0.5 * lum(fb[q].rgb)));
+ let layer = select(vec3<f32>(0.0), base.color.rgb, overlay);
+ let lighting = base.color.rgb - layer;
+ // The bypass mask is 1 where denoising should be skipped (MetalFX's denoise-strength texture).
+ return RcJointInputs(vec4<f32>(lighting, 1.0), base.depth, base.motion, base.reactive, vec4<f32>(layer, f32(overlay)), f32(overlay));
+}
+struct RcGuides {
+ @location(0) diffuse: vec4<f32>,
+ @location(1) specular: vec4<f32>,
+ @location(2) normal: vec4<f32>,
+ @location(3) roughness: f32,
+ @location(4) hit: f32,
+};
+@fragment fn rc_guides(@builtin(position) p: vec4<f32>) -> RcGuides {
+ let q = u32(p.y) * L.isz.x + u32(p.x);
+ let px = sample_px[q];
+ let diffuse = refl_in[2u*q];
+ let specular = refl_in[2u*q+1u];
+ return RcGuides(vec4<f32>(diffuse.rgb, 1.0), vec4<f32>(specular.rgb, 1.0), vec4<f32>(oct_dec(bitcast<u32>(diffuse.w)), 1.0),
+ clamp(specular.w, 0.0, 1.0), clamp(px.spec.w, 0.0, 65504.0));
+}
+@group(1) @binding(0) var rc_output: texture_2d<f32>;
+@compute @workgroup_size(8,8) fn rc_output_to_post(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (any(id.xy >= L.size.xy)) { return; }
+ let i = id.y * L.size.x + id.x;
+ let c = finite_or_zero(max(textureLoad(rc_output, vec2<i32>(id.xy), 0).rgb, vec3<f32>(0.0))) * rc_radiance_unit();
+ let nearest = clamp(vec2<i32>(round((vec2<f32>(id.xy)+0.5)*vec2<f32>(L.isz.xy)/vec2<f32>(L.size.xy)-L.jit.xy)),
+ vec2<i32>(0), vec2<i32>(L.isz.xy)-1);
+ let img = vec4<f32>(c, dof_coc(sample_vel[u32(nearest.y)*L.isz.x+u32(nearest.x)].z));
+ if (L.misc2.z > 0.0 || L.dof.x > 0.0) { sb[i] = img; } else { fa[i] = img; }
+}
diff --git a/renderer/src/gpu.rs b/renderer/src/gpu.rs
index e15ce50..9ed13b5 100644
--- a/renderer/src/gpu.rs
+++ b/renderer/src/gpu.rs
@@ -18,11 +18,19 @@ struct Pages {
streams: Vec<(String, crate::texpack::Place)>,
}
+#[cfg(dlss)]
+pub(crate) type DlssSdk = std::sync::Arc<std::sync::Mutex<dlss_wgpu::DlssSdk>>;
+
pub struct Gpu {
pub instance: wgpu::Instance,
pub adapter: wgpu::Adapter,
/// GPU timestamp queries are available (used for adaptive samples per frame in the viewer).
pub timestamps: bool,
+ #[cfg(dlss)]
+ pub(crate) dlss_sdk: Option<DlssSdk>,
+ /// NGX reported DLSS Ray Reconstruction on this device (with `dlss_sdk`).
+ #[cfg(dlss)]
+ pub(crate) dlss_rr: bool,
pub device: wgpu::Device,
pub queue: wgpu::Queue,
pub adapter_info: wgpu::AdapterInfo,
@@ -1941,6 +1949,26 @@ fn stamp() {
}
";
+/// Reopen the selected Vulkan adapter with NGX's instance and device extensions. Keep the original adapter
+/// available for fallback, and never replace a non-Vulkan adapter (e.g. when WGPU_BACKEND requests DX12).
+#[cfg(dlss)]
+async fn open_dlss(
+ info: &wgpu::AdapterInfo, desc: &wgpu::DeviceDescriptor<'_>,
+) -> Result<(wgpu::Instance, wgpu::Adapter, wgpu::Device, wgpu::Queue, DlssSdk, bool)> {
+ const PROJECT: uuid::Uuid = uuid::uuid!("7e2053f1-3c7a-4d3c-9a60-d28593bcfdb7");
+ let mut support = dlss_wgpu::FeatureSupport::default();
+ let instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
+ let instance = dlss_wgpu::create_instance(PROJECT, &instance_desc, &mut support)?;
+ anyhow::ensure!(support.super_resolution_supported, "missing NGX Vulkan instance extensions");
+ let adapter = instance.enumerate_adapters(wgpu::Backends::VULKAN).await.into_iter()
+ .find(|adapter| adapter.get_info() == *info)
+ .ok_or_else(|| anyhow!("the selected Vulkan adapter is unavailable in the NGX instance"))?;
+ let (device, queue) = dlss_wgpu::request_device(PROJECT, &adapter, desc, &mut support, Some(desc.required_limits.clone()))?;
+ anyhow::ensure!(support.super_resolution_supported, "missing NGX Vulkan device extensions");
+ let sdk = dlss_wgpu::DlssSdk::new(PROJECT, device.clone())?;
+ Ok((instance, adapter, device, queue, sdk, support.ray_reconstruction_supported))
+}
+
impl Gpu {
/// The GPU, waited for (the native shell; a browser has `new_async`: nothing may block there).
#[cfg(not(target_arch = "wasm32"))]
@@ -1999,14 +2027,39 @@ impl Gpu {
// Compiled pipelines kept between runs, where a host gave a directory and the backend has a cache.
let cache_feature = options.pipeline_cache.as_ref().and_then(|_| crate::pipeline_cache::PipelineCache::feature(&adapter, &adapter_info));
features |= cache_feature.unwrap_or(wgpu::Features::empty());
- let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor {
+ let device_desc = wgpu::DeviceDescriptor {
label: Some("threert"),
required_features: features,
required_limits: limits,
// Ray queries are still flagged experimental in wgpu 30.
experimental_features: if hwrt { unsafe { wgpu::ExperimentalFeatures::enabled() } } else { wgpu::ExperimentalFeatures::disabled() },
..Default::default()
- }).await?;
+ };
+ #[cfg(dlss)]
+ let (instance, adapter, device, queue, dlss_sdk, dlss_rr) = {
+ let dlss = if adapter_info.backend == wgpu::Backend::Vulkan && adapter_info.vendor == 0x10de
+ && std::env::var("THREERT_DLSS").is_ok_and(|v| v == "1")
+ {
+ match open_dlss(&adapter_info, &device_desc).await {
+ Ok(opened) => Some(opened),
+ Err(err) => {
+ eprintln!("DLSS unavailable: {err:#}");
+ None
+ }
+ }
+ } else {
+ None
+ };
+ match dlss {
+ Some((instance, adapter, device, queue, sdk, rr)) => (instance, adapter, device, queue, Some(sdk), rr),
+ None => {
+ let (device, queue) = adapter.request_device(&device_desc).await?;
+ (instance, adapter, device, queue, None, false)
+ }
+ }
+ };
+ #[cfg(not(dlss))]
+ let (device, queue) = adapter.request_device(&device_desc).await?;
let pipeline_cache = cache_feature.and_then(|_| crate::pipeline_cache::PipelineCache::open(&device, options.pipeline_cache.as_ref()?, &adapter_info));
let uniform_tables = options.uniform_tables_on(merged, cfg!(target_os = "android"));
let whole_tables = !merged && !options.table_views_on(merged, cfg!(target_os = "android"));
@@ -2058,7 +2111,21 @@ impl Gpu {
} else {
(None, None, None, None)
};
- Ok(Gpu { instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default() })
+ Ok(Gpu {
+ #[cfg(dlss)]
+ dlss_sdk,
+ #[cfg(dlss)]
+ dlss_rr,
+ instance, adapter, timestamps, device, queue, adapter_info, uniform_tables, whole_tables, switches, approx, approx_default: approx, pipeline_cache, source: src, module, merged, modules: Default::default(), pipeline_layout: pl, pipelines: Default::default(), layout, vis_layout, no_vis, no_vis_bufs, no_vis_view, no_grid_view, grid_layout, fill: Default::default(), hwrt, pages: Default::default(), streams: Default::default(), tl_layout, tl_pipeline_layout, tl_vis_layout, no_vis_tl, tl_pipelines: Default::default(), kernel_passes: Default::default(), proc_cache: Default::default(), proc_blases: Default::default(),
+ })
+ }
+
+ /// Whether this device successfully initialized NGX with DLSS Super Resolution support.
+ pub fn dlss_supported(&self) -> bool {
+ #[cfg(dlss)]
+ { self.dlss_sdk.is_some() }
+ #[cfg(not(dlss))]
+ { false }
}
/// Whether this device's kernel buffers have the loop guard's count (`guard_room`; always in the merged layout).
diff --git a/renderer/src/live/dlss.rs b/renderer/src/live/dlss.rs
new file mode 100644
index 0000000..c65223d
--- /dev/null
+++ b/renderer/src/live/dlss.rs
@@ -0,0 +1,206 @@
+//! NVIDIA DLSS through Vulkan NGX (dlss_wgpu): Super Resolution / DLAA as an upscaler, Ray Reconstruction as a joint
+//! denoiser (live/reconstruction.rs has the two contracts).
+
+use super::reconstruction::{JointGuides, JointProvider, Prepared, ReconstructionFrame, ReconstructionSize, UpscaleProvider};
+use crate::gpu;
+use anyhow::{Context, Result};
+use dlss_wgpu::ray_reconstruction::{
+ DlssRayReconstruction, DlssRayReconstructionDepthMode, DlssRayReconstructionRenderParameters,
+ DlssRayReconstructionRoughnessMode, DlssRayReconstructionSpecularGuide, DlssRayReconstructionTransparencyOverlay,
+};
+use dlss_wgpu::super_resolution::{DlssSuperResolution, DlssSuperResolutionExposure, DlssSuperResolutionRenderParameters};
+use dlss_wgpu::{DlssError, DlssFeatureFlags, DlssPerfQualityMode as Mode};
+use std::ops::RangeInclusive;
+use wgpu::{CommandBuffer, CommandEncoder, TextureFormat, TextureUsages, TextureView};
+
+/// What both DLSS features share: a context made for one output size and quality mode, which accepts a range of
+/// input sizes.
+trait NgxFeature: Sized {
+ fn create(gpu: &gpu::Gpu, sdk: &gpu::DlssSdk, output: [u32; 2], mode: Mode) -> Result<Self, DlssError>;
+ fn output(&self) -> [u32; 2];
+ fn range(&self) -> RangeInclusive<[u32; 2]>;
+}
+
+impl NgxFeature for DlssSuperResolution {
+ fn create(gpu: &gpu::Gpu, sdk: &gpu::DlssSdk, output: [u32; 2], mode: Mode) -> Result<Self, DlssError> {
+ let flags = DlssFeatureFlags::HighDynamicRange | DlssFeatureFlags::LowResolutionMotionVectors
+ | DlssFeatureFlags::InvertedDepth | DlssFeatureFlags::AutoExposure;
+ DlssSuperResolution::new(output, mode, flags, sdk.clone(), &gpu.device, &gpu.queue)
+ }
+ fn output(&self) -> [u32; 2] { self.upscaled_resolution() }
+ fn range(&self) -> RangeInclusive<[u32; 2]> { self.render_resolution_range() }
+}
+
+impl NgxFeature for DlssRayReconstruction {
+ fn create(gpu: &gpu::Gpu, sdk: &gpu::DlssSdk, output: [u32; 2], mode: Mode) -> Result<Self, DlssError> {
+ // (Ray Reconstruction has no auto exposure: its input is in units of display white, `radiance_unit`.)
+ let flags = DlssFeatureFlags::HighDynamicRange | DlssFeatureFlags::LowResolutionMotionVectors | DlssFeatureFlags::InvertedDepth;
+ DlssRayReconstruction::new(output, mode, flags, DlssRayReconstructionRoughnessMode::Unpacked,
+ DlssRayReconstructionDepthMode::Hardware, sdk.clone(), &gpu.device, &gpu.queue)
+ }
+ fn output(&self) -> [u32; 2] { self.upscaled_resolution() }
+ fn range(&self) -> RangeInclusive<[u32; 2]> {
+ // NGX reports one render resolution for Ray Reconstruction; dynamic resolution recreates it.
+ let r = self.render_resolution();
+ r..=r
+ }
+}
+
+fn contains(r: &RangeInclusive<[u32; 2]>, input: [u32; 2]) -> bool {
+ // RangeInclusive<[u32; 2]>::contains would compare the dimensions lexicographically.
+ (0..2).all(|i| r.start()[i] <= input[i] && input[i] <= r.end()[i])
+}
+
+struct State<C> {
+ // The wrapper keeps NGX and the device alive and waits for GPU use before releasing this context.
+ context: C,
+ mode: Mode,
+ input: [u32; 2],
+ reset: bool,
+}
+
+/// The context for a size: the current one if it accepts it, else one per quality mode, nearest the input's
+/// ratio first (the modes' nominal ratios are not bounds: NGX reports each one's range).
+struct Feature<C> {
+ name: &'static str,
+ state: Option<State<C>>,
+}
+
+impl<C: NgxFeature> Feature<C> {
+ fn prepare(&mut self, gpu: &gpu::Gpu, available: bool, size: ReconstructionSize) -> Result<Prepared> {
+ let Some(sdk) = gpu.dlss_sdk.as_ref().filter(|_| available) else {
+ return Ok(Prepared::Unsupported(if gpu.dlss_sdk.is_none() {
+ "NGX is not running (an NVIDIA RTX GPU on Vulkan, THREERT_DLSS=1, nvngx_dlss.dll beside the program)".into()
+ } else {
+ format!("NGX reports no {} on this device or driver", self.name)
+ }));
+ };
+ if (0..2).any(|i| size.output[i] < 32 || size.input[i] == 0 || size.input[i] > size.output[i]) {
+ return Ok(Prepared::Unsupported(format!("{} needs an input of 1 x 1 up to the output, and an output of 32 x 32 or more", self.name)));
+ }
+ let native = size.input == size.output;
+ let fits = |s: &State<C>| s.context.output() == size.output && (s.mode == Mode::Dlaa) == native && contains(&s.context.range(), size.input);
+ if let Some(s) = &mut self.state {
+ if fits(s) && (size.dynamic || s.input == size.input) {
+ s.input = size.input;
+ return Ok(Prepared::ready(size));
+ }
+ }
+ let mut scaled = [(Mode::Quality, 667), (Mode::Balanced, 588), (Mode::Performance, 500), (Mode::UltraPerformance, 333)];
+ let modes = if native {
+ &[(Mode::Dlaa, 1000)][..]
+ } else {
+ scaled.sort_unstable_by_key(|&(_, k)| (size.input[0] as u64 * 1000).abs_diff(size.output[0] as u64 * k));
+ &scaled[..]
+ };
+ let mut ranges = vec![];
+ for &(mode, _) in modes {
+ let context = match C::create(gpu, sdk, size.output, mode) {
+ Ok(c) => c,
+ Err(DlssError::FeatureNotSupported | DlssError::InvalidParameters | DlssError::UnsupportedParameter) => continue,
+ Err(e) => return Err(e).with_context(|| format!("create {} {mode:?} for {:?}", self.name, size.output)),
+ };
+ let r = context.range();
+ if contains(&r, size.input) {
+ self.state = Some(State { context, mode, input: size.input, reset: true });
+ return Ok(Prepared::ready(size));
+ }
+ ranges.push(format!("{mode:?} {}x{}..{}x{}", r.start()[0], r.start()[1], r.end()[0], r.end()[1]));
+ }
+ Ok(Prepared::Unsupported(format!("an input of {}x{} is outside {}'s inputs for {}x{} ({})",
+ size.input[0], size.input[1], self.name, size.output[0], size.output[1], ranges.join(", "))))
+ }
+
+ fn state(&mut self, frame: &ReconstructionFrame<'_>) -> Result<&mut State<C>> {
+ let s = self.state.as_mut().with_context(|| format!("{} was not prepared", self.name))?;
+ anyhow::ensure!(s.input == frame.size.input && s.context.output() == frame.size.output, "{} was prepared for another size", self.name);
+ Ok(s)
+ }
+}
+
+fn check(view: &TextureView, name: &str, format: TextureFormat, [w, h]: [u32; 2], usage: TextureUsages) -> Result<()> {
+ let t = view.texture();
+ anyhow::ensure!(t.format() == format && t.width() >= w && t.height() >= h && t.usage().contains(usage),
+ "invalid DLSS {name} texture: expected {w}x{h} or larger, {format:?} with {usage:?}");
+ Ok(())
+}
+
+fn check_frame(f: &ReconstructionFrame<'_>) -> Result<()> {
+ let sampled = TextureUsages::TEXTURE_BINDING;
+ check(f.color, "colour", TextureFormat::Rgba16Float, f.size.input, sampled)?;
+ check(f.depth, "depth", TextureFormat::R32Float, f.size.input, sampled)?;
+ check(f.motion, "motion", TextureFormat::Rg16Float, f.size.input, sampled)?;
+ check(f.reactive, "reactive mask", TextureFormat::R8Unorm, f.size.input, sampled)?;
+ // Some Vulkan NGX paths also clear the output using vkCmdClearColorImage.
+ check(f.output, "output", TextureFormat::Rgba16Float, f.size.output, TextureUsages::STORAGE_BINDING | TextureUsages::COPY_DST)
+}
+
+/// DLSS Super Resolution, DLAA at scale 1.
+pub(super) struct Dlss(Feature<DlssSuperResolution>);
+
+impl Default for Dlss {
+ fn default() -> Self { Self(Feature { name: "DLSS Super Resolution", state: None }) }
+}
+
+impl UpscaleProvider for Dlss {
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { self.0.prepare(gpu, true, size) }
+
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>> {
+ check_frame(&frame)?;
+ let state = self.0.state(&frame)?;
+ // NGX wants the shift of the projected image, opposite to the displacement of the sample point.
+ let [x, y] = frame.jitter;
+ let params = DlssSuperResolutionRenderParameters {
+ color: frame.color, depth: frame.depth, motion_vectors: frame.motion,
+ exposure: DlssSuperResolutionExposure::Automatic, bias: Some(frame.reactive), dlss_output: frame.output,
+ reset: state.reset || frame.reset, jitter_offset: [-x, -y],
+ partial_texture_size: Some(frame.size.input), motion_vector_scale: None,
+ };
+ // The wrapper records barriers on `encoder`. Submit the returned buffer immediately after it, in the same submit.
+ let native = state.context.render(params, encoder, &frame.gpu.adapter).context("encode DLSS Super Resolution")?;
+ state.reset = false;
+ Ok(Some(native))
+ }
+}
+
+/// DLSS Ray Reconstruction.
+pub(super) struct DlssRr(Feature<DlssRayReconstruction>);
+
+impl Default for DlssRr {
+ fn default() -> Self { Self(Feature { name: "DLSS Ray Reconstruction", state: None }) }
+}
+
+impl JointProvider for DlssRr {
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { self.0.prepare(gpu, gpu.dlss_rr, size) }
+
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, g: JointGuides<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>> {
+ check_frame(&frame)?;
+ let sampled = TextureUsages::TEXTURE_BINDING;
+ check(g.overlay, "overlay", TextureFormat::Rgba16Float, frame.size.input, sampled)?;
+ check(g.diffuse_albedo, "diffuse albedo", TextureFormat::Rgba8Unorm, frame.size.input, sampled)?;
+ check(g.specular_albedo, "specular albedo", TextureFormat::Rgba8Unorm, frame.size.input, sampled)?;
+ check(g.normal, "normal", TextureFormat::Rgba16Float, frame.size.input, sampled)?;
+ check(g.roughness, "roughness", TextureFormat::R16Float, frame.size.input, sampled)?;
+ check(g.specular_hit_distance, "specular hit distance", TextureFormat::R16Float, frame.size.input, sampled)?;
+ let state = self.0.state(&frame)?;
+ let [x, y] = frame.jitter;
+ let params = DlssRayReconstructionRenderParameters {
+ diffuse_albedo: g.diffuse_albedo, specular_albedo: g.specular_albedo, normals: g.normal, roughness: Some(g.roughness),
+ color: frame.color, depth: frame.depth, motion_vectors: frame.motion,
+ // NGX's matrices are row-vector (v * M) and row-major: the same 16 floats as a column-vector matrix
+ // stored column-major (glam's `to_cols_array`).
+ specular_guide: DlssRayReconstructionSpecularGuide::SpecularHitDistance {
+ texture_view: g.specular_hit_distance, world_to_view_rows_array: frame.world_to_view, view_to_clip_rows_array: frame.view_to_clip,
+ },
+ // The overlay is premultiplied: its alpha is 1 where it is the whole pixel, and 0 (with no colour) elsewhere.
+ transparency_overlay: Some(DlssRayReconstructionTransparencyOverlay::Premultiplied(g.overlay)),
+ color_before_transparency: None, screen_space_subsurface_scattering_guide: None, depth_of_field_guide: None,
+ responsivity_mask: Some(frame.reactive), alpha: None, dlss_output_alpha: None, dlss_output: frame.output,
+ reset: state.reset || frame.reset, jitter_offset: [-x, -y],
+ partial_texture_size: Some(frame.size.input), motion_vector_scale: None,
+ };
+ let native = state.context.render(params, encoder, &frame.gpu.adapter).context("encode DLSS Ray Reconstruction")?;
+ state.reset = false;
+ Ok(Some(native))
+ }
+}
diff --git a/renderer/src/live/frame.rs b/renderer/src/live/frame.rs
index c1a4d8f..bdb7597 100644
--- a/renderer/src/live/frame.rs
+++ b/renderer/src/live/frame.rs
@@ -254,8 +254,13 @@ impl LiveCore {
// A dynamic sky's bake that finished since the last frame (time of day).
self.take_sky();
self.take_emitters();
+ // Settings a game or page requested since the last frame.
+ if let Some(r) = self.rendering_control.as_ref().and_then(|c| c.take()) { self.set_rendering(r); }
let (w, h) = (self.w, self.h);
let (iw, ih) = self.internal_size();
+ let size = ReconstructionSize { input: [iw, ih], output: [w, h], dynamic: self.dynamic_res };
+ self.reset |= self.reconstructor.prepare(&self.g, &self.targets, size, self.view_mode != 0);
+ let reconstruction = self.reconstructor.active;
self.ensure_deferred(iw as u64 * ih as u64);
if self.sc.up.translucent.is_some() {
self.targets.translucent_low(&self.g);
@@ -284,7 +289,7 @@ impl LiveCore {
// At most two frames in flight: beyond that the CPU waits, so latency stays bounded when GPU-bound.
// Wait for the oldest frame only (waiting for all work would leave the GPU idle while this frame records).
let t_wait = Instant::now();
- while self.inflight.len() >= 2 {
+ while self.inflight.len() >= self.frames_in_flight() {
let oldest = self.inflight.pop_front().unwrap();
let _ = g.device.poll(wgpu::PollType::Wait { submission_index: Some(oldest), timeout: None });
}
@@ -310,7 +315,7 @@ impl LiveCore {
Some(t) => {
let (latest, slot) = t.harvest(period);
if let Some((ms, frame, trace)) = latest {
- (self.gpu_ms, self.gpu_frame, self.gpu_trace_ms) = (ms, frame, trace);
+ (self.gpu_ms, self.gpu_frame, self.gpu_trace_ms) = (ms + self.reconstructor.untimed_gpu_ms(), frame, trace);
}
if let Some(k) = slot {
t.frames[k] = self.frame;
@@ -348,6 +353,7 @@ impl LiveCore {
let g = &self.g;
let t_submit = Instant::now();
let pipeline = g.pipeline(&self.sc.up.kernel, true);
+ let guides = reconstruction.guides().then(|| g.kernel_pass(&self.sc.up.kernel, "surface_guides"));
// (No media pass while every medium is hidden: a pool of idle fireballs costs the frame nothing.)
let media = self.sc.up.kernel.features & gpu::F_MEDIA != 0 && self.sc.up.media_hidden.borrow().iter().any(|h| !h);
let media_train = (media && self.cache.is_some()).then(|| g.kernel_pass(&self.sc.up.kernel, "media_train"));
@@ -357,9 +363,13 @@ impl LiveCore {
// This frame's sub-pixel jitter (Halton 2, 3), every camera ray's and the raster visibility pass's: 8 phases at
// full resolution, as many more as an output pixel has fewer traced ones (8 / scale^2: the upscaler needs each
// output pixel visited), in the 12 bits a side the samples carry it in.
- let phases = ((8.0 * (w as f32 / iw as f32) * (h as f32 / ih as f32)).round() as u32).clamp(8, 512);
- let quant = |v: f32| (v * 4095.0).round() / 4095.0;
- let jitter = (quant(halton(self.frame % phases + 1, 2)), quant(halton(self.frame % phases + 1, 3)));
+ let jitter = if reconstruction.unjittered() {
+ (0.5, 0.5)
+ } else {
+ let phases = ((8.0 * (w as f32 / iw as f32) * (h as f32 / ih as f32)).round() as u32).clamp(8, 512);
+ let quant = |v: f32| (v * 4095.0).round() / 4095.0;
+ (quant(halton(self.frame % phases + 1, 2)), quant(halton(self.frame % phases + 1, 3)))
+ };
// The light tiles (pathtrace.wgsl "Light tiles"), in a scene whose local lights are resampled (gpu::F_LISTS):
// the lists the last frame built, for this frame's paths (none after a reset: its reports were another
// view's), and this frame's grid offset, a pixel of 8 x 8.
@@ -372,6 +382,7 @@ impl LiveCore {
let moving = !self.sc.dynamic.1.is_empty() || self.sc.moving_instances;
for k in 0..spp.max(1) {
let mut p = self.sc.base;
+ p.motion[1] = reconstruction.raw_signal() as u32 as f32;
if let Some((row, at, size, cam)) = self.light_tiles {
(p.ltile[0], p.ltile[1], p.ltile[2]) = (1, row, at);
p.ltile2 = [size.0, size.1, 0, 0];
@@ -484,6 +495,10 @@ impl LiveCore {
pass.set_bind_group(0, &self.sc.up.bg, &[]);
pass.set_bind_group(1, &self.kernel_bg, &[]);
}
+ if let (Some(guides), true) = (&guides, last) {
+ pass.set_pipeline(guides);
+ pass.dispatch_workgroups(iw.div_ceil(8), ih.div_ceil(8), 1);
+ }
if let (Some(mt), 0) = (&media_train, k) {
pass.set_pipeline(mt);
pass.dispatch_workgroups(MEDIA_TRAIN_POINTS.div_ceil(64), 1, 1);
@@ -520,13 +535,13 @@ impl LiveCore {
let lp = LiveParams {
cur: cam.uniform(self.aspect),
prev: self.prev_cam.uniform(self.aspect),
- size: [w, h, self.frame, self.reset as u32],
+ size: [w, h, self.frame, (self.reset || reconstruction.history_free()) as u32],
misc: [self.view.exposure, cap, self.vignette, (self.bloom.1.iter().sum::<f32>() > 0.0) as u32 as f32],
// misc2.z: motion blur, this frame's motion (pixels) -> blur length. UE (PostProcessMotionBlur.cpp,
// UpdateMotionBlurTimeScale) blurs over +- amount / 2 x the motion x (1 / target FPS) / frame time, the
// actual frame time without a target. 0 while nothing moves (the pass then costs nothing).
misc2: [1.0, SAMPLE_CEILING, if !blur { 0.0 } else if self.blur.1 > 0.0 { self.blur.0 / (self.blur.1 * self.frame_dt.clamp(1.0 / 240.0, 0.25)) } else { self.blur.0 }, spp.max(1) as f32],
- mode: [self.view_mode, 0, self.live_lighting() as u32, 0],
+ mode: [self.view_mode, 0, self.live_lighting() as u32, reconstruction.raw_signal() as u32],
post: self.post,
ae: self.view.exposure_settings.ae,
ae2: self.view.exposure_settings.ae2,
@@ -589,18 +604,46 @@ impl LiveCore {
pass.set_bind_group(1, &self.kernel_bg, &[]);
pass.dispatch_workgroups((gpu::CACHE_SIZE / 256) as u32, 1, 1);
}
+ let mut before_post: Option<[wgpu::CommandBuffer; 2]> = None;
+ let use_provider = reconstruction.external();
+ let mut provider_failed = false;
+ let mut reconstruct = |e: &mut wgpu::CommandEncoder| {
+ match self.reconstructor.encode(g, e, size, cam, self.aspect, jitter, self.view.exposure, self.reset || cut) {
+ Ok(buffers) => buffers,
+ Err(_) => {
+ provider_failed = true;
+ // Start fresh rather than read a built-in history from before the switch. With reset, lock_carry
+ // does no work. (A joint denoiser's frame has no denoising: this one frame shows its raw signal.)
+ let at = (std::mem::offset_of!(LiveParams, size) + 3 * std::mem::size_of::<u32>()) as u64;
+ g.queue.write_buffer(&self.targets.params, at, bytemuck::bytes_of(&1u32));
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("builtin reconstruction fallback"), ..Default::default() });
+ for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
+ if !matches!(*name, "track" | "judge" | "reject" | "upscale") { continue; }
+ pass.set_pipeline(pipe);
+ pass.set_bind_group(0, &self.targets.bgs[k], &[]);
+ let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);
+ pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);
+ }
+ None
+ }
+ }
+ };
if let Some(p) = &self.profile {
// One compute pass per stage, each timed.
for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
let q = (k as u32 + 1) * 2;
- let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: Some(q + 1) }) });
- if (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) {
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: Some(q), end_of_pass_write_index: (!(use_provider && *name == "upscale")).then_some(q + 1) }) });
+ if !reconstruction.skips(name) && (self.view_mode != 0 || !layout::VIEW_MODE_PASSES.contains(name)) && (tiles_on || *name != layout::LIGHT_TILES_PASS) {
pass.set_pipeline(pipe);
pass.set_bind_group(0, &self.targets.bgs[k], &[]);
let (gw, gh) = grid.size((w, h), (iw, ih), self.prev_isz);
pass.dispatch_workgroups(gw.div_ceil(8), gh.div_ceil(8), 1);
}
drop(pass);
+ if use_provider && *name == "upscale" {
+ before_post = reconstruct(&mut e);
+ drop(e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("reconstruction end"), timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: &p.queries, beginning_of_pass_write_index: None, end_of_pass_write_index: Some(q + 1) }) }));
+ }
if *name == "upscale" && tl.is_some() {
for (j, train) in [(0u32, false), (1, true)] {
let q = (self.passes.pipes.len() as u32 + 4 + j) * 2;
@@ -614,9 +657,17 @@ impl LiveCore {
e.copy_buffer_to_buffer(&p.resolve, 0, &p.read, 0, p.read.size());
} else {
let tw = self.timer.as_ref().zip(timed).map(|(t, slot)| wgpu::ComputePassTimestampWrites { query_set: &t.queries, beginning_of_pass_write_index: Some(slot as u32 * 8 + 2), end_of_pass_write_index: Some(slot as u32 * 8 + 3) });
- let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live post"), timestamp_writes: tw });
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("live post"), timestamp_writes: tw.clone().map(|mut t| { if use_provider { t.end_of_pass_write_index = None; } t }) });
for (k, (name, grid, pipe)) in self.passes.pipes.iter().enumerate() {
- if (self.view_mode == 0 && layout::VIEW_MODE_PASSES.contains(name)) || (!tiles_on && *name == layout::LIGHT_TILES_PASS) {
+ if use_provider && *name == "upscale" {
+ drop(pass);
+ before_post = reconstruct(&mut e);
+ pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("post after reconstruction"), timestamp_writes: tw.clone().map(|mut t| { t.beginning_of_pass_write_index = None; t }) });
+ tl_dispatch(&mut pass, false);
+ tl_dispatch(&mut pass, true);
+ continue;
+ }
+ if reconstruction.skips(name) || (self.view_mode == 0 && layout::VIEW_MODE_PASSES.contains(name)) || (!tiles_on && *name == layout::LIGHT_TILES_PASS) {
continue;
}
pass.set_pipeline(pipe);
@@ -640,7 +691,9 @@ impl LiveCore {
e.copy_buffer_to_buffer(&count.buffer, count.offset, read, 0, 4);
}
extra(&mut e, &self.targets.out);
- let done = g.queue.submit([e.finish()]);
+ let done = g.queue.submit(before_post.into_iter().flatten().chain([e.finish()]));
+ if provider_failed { self.history_len = 1.0; }
+ if let Some(c) = &self.rendering_control { c.publish(self.rendering_status()); }
self.inflight.push_back(done);
self.cpu_wait_ms = waited;
if let (Some((read, state)), true) = (&self.guard_read, guard_free) {
diff --git a/renderer/src/live/fsr.rs b/renderer/src/live/fsr.rs
new file mode 100644
index 0000000..f6cc65c
--- /dev/null
+++ b/renderer/src/live/fsr.rs
@@ -0,0 +1,121 @@
+//! FidelityFX Super Resolution 1: EASU upsampling, then RCAS sharpening into the live HDR post target.
+use super::{gpu, layout, targets, Targets};
+
+fn source() -> String {
+ [targets::live_source(), include_str!("../../shaders/fsr.wgsl")].concat()
+}
+
+struct Pass {
+ pipeline: wgpu::ComputePipeline,
+ live: wgpu::BindGroup,
+ scratch: wgpu::BindGroup,
+}
+
+impl Pass {
+ fn new(
+ g: &gpu::Gpu,
+ module: &wgpu::ShaderModule,
+ name: &str,
+ entries: &[wgpu::BindGroupEntry<'_>],
+ scratch: &wgpu::TextureView,
+ scratch_binding: u32,
+ ) -> Self {
+ let d = &g.device;
+ let pipeline = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some(name),
+ layout: None,
+ module,
+ entry_point: Some(name),
+ compilation_options: Default::default(),
+ cache: g.cache(),
+ });
+ let live = d.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some(name),
+ layout: &pipeline.get_bind_group_layout(0),
+ entries,
+ });
+ let scratch = d.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some(name),
+ layout: &pipeline.get_bind_group_layout(1),
+ entries: &[wgpu::BindGroupEntry {
+ binding: scratch_binding,
+ resource: wgpu::BindingResource::TextureView(scratch),
+ }],
+ });
+ Self { pipeline, live, scratch }
+ }
+
+ fn encode(&self, encoder: &mut wgpu::CommandEncoder, label: &str, [x, y]: [u32; 2]) {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: Some(label),
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &self.live, &[]);
+ pass.set_bind_group(1, &self.scratch, &[]);
+ pass.dispatch_workgroups(x, y, 1);
+ }
+}
+
+pub(super) struct Fsr {
+ easu: Pass,
+ rcas: Pass,
+ workgroups: [u32; 2],
+}
+
+impl Fsr {
+ pub(super) fn new(g: &gpu::Gpu, targets: &Targets, output: [u32; 2]) -> Self {
+ let d = &g.device;
+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("FidelityFX FSR 1"),
+ source: wgpu::ShaderSource::Wgsl(source().into()),
+ });
+ // Keep FP32 headroom for reversing the HDR proxy. A write-only storage texture and
+ // unfiltered textureLoad of this format are both available on a baseline WebGPU device.
+ let scratch = d.create_texture(&wgpu::TextureDescriptor {
+ label: Some("FSR 1 EASU scratch"),
+ size: wgpu::Extent3d { width: output[0], height: output[1], depth_or_array_layers: 1 },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba32Float,
+ usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ }).create_view(&Default::default());
+ let entry = |name| wgpu::BindGroupEntry {
+ binding: layout::binding(name).binding,
+ resource: if name == "L" { targets.params.as_entire_binding() } else { targets.buf(name).binding() },
+ };
+ Self {
+ easu: Pass::new(g, &module, "fsr_easu", &["L", "fb"].map(entry), &scratch, 0),
+ rcas: Pass::new(g, &module, "fsr_rcas_to_post", &["L", "sample_vel", "fa", "sb"].map(entry), &scratch, 1),
+ workgroups: output.map(|dim| dim.div_ceil(8)),
+ }
+ }
+
+ pub(super) fn encode(&self, encoder: &mut wgpu::CommandEncoder) {
+ self.easu.encode(encoder, "FSR 1 EASU", self.workgroups);
+ self.rcas.encode(encoder, "FSR 1 RCAS", self.workgroups);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn fsr_shader_only_binds_composed_hdr_depth_and_post_targets() {
+ let src = super::source();
+ let module = naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src)));
+ let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())
+ .validate(&module).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src)));
+ for (name, expected) in [("fsr_easu", &["fb"][..]), ("fsr_rcas_to_post", &["fa", "sample_vel", "sb"][..])] {
+ let k = module.entry_points.iter().position(|e| e.name == name).unwrap();
+ let entry = info.get_entry_point(k);
+ let mut buffers: Vec<_> = module.global_variables.iter()
+ .filter(|(h, v)| matches!(v.space, naga::AddressSpace::Storage { .. }) && !entry[*h].is_empty())
+ .map(|(_, v)| v.name.as_deref().unwrap())
+ .collect();
+ buffers.sort_unstable();
+ assert_eq!(buffers, expected, "{name}");
+ }
+ }
+}
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index b03f1e1..fab6a52 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -3332,3 +3332,199 @@ fn a_hidden_volumes_passes_are_made_at_load() {
picture(&mut live, 2);
assert_eq!(made(&live), ["media_composite", "media_train"], "the frame that shows it makes none");
}
+
+/// A bright HDR panel catches clipping before reconstruction, stale bindings after resize, and
+/// carrying temporal history through a cut. MetalFX methods run only where the SDK supports them.
+#[test]
+fn reconstruction_keeps_hdr_emitters_and_resets_on_a_cut() {
+ let Ok(gpu) = gpu::Gpu::new() else { return };
+ let mut w = world();
+ w.set_material(5, serde_json::from_value(serde_json::json!({
+ "name": "HDR panel", "color": [0, 0, 0], "opacity": 1, "metalness": 0, "roughness": 1,
+ "emissive": [1, 0.25, 0.5], "emissiveIntensity": 1800, "doubleSided": true,
+ })).unwrap());
+ w.set_transform(12, Vec3::new(0.0, 0.0, 1.0), glam::Quat::IDENTITY, Vec3::new(5.0, 0.5, 1.0)).unwrap();
+ w.set_camera_desc(4, camera(50.0, None, manual(6.0))).unwrap();
+ let mut core = LiveCore::new(gpu, &w, Path::new("."), &crate::default_presets_dir(), 320, 180).unwrap();
+ let scene_cam = core.cam;
+ let center = |c: &LiveCore| {
+ let hdr = c.read_hdr().unwrap();
+ assert!(hdr.iter().all(|v| v.is_finite() && *v >= 0.0));
+ let p = ((c.h / 2 * c.w + c.w / 2) * 3) as usize;
+ [hdr[p], hdr[p + 1], hdr[p + 2]]
+ };
+ let methods = [
+ Method::Fsr,
+ Method::Off,
+ #[cfg(target_os = "macos")]
+ Method::MetalFx,
+ #[cfg(target_os = "macos")]
+ Method::MetalFxDenoised,
+ ];
+ for method in methods {
+ core.set_scale(0.5);
+ core.set_reconstruction(method.clone());
+ core.set_camera(scene_cam);
+ for _ in 0..16 { core.render(1, |_, _| {}); }
+ if core.reconstruction() == Method::Builtin {
+ assert!(!matches!(method, Method::Fsr | Method::Off));
+ eprintln!("{} unsupported on this device: {:?}", method.name(), core.reconstruction_status().skipped);
+ continue;
+ }
+ for (v, reference) in center(&core).into_iter().zip([1800.0, 450.0, 900.0]) {
+ assert!((v / reference - 1.0).abs() < 0.2, "{}: {v} of {reference}", method.name());
+ }
+ core.set_scale(0.0);
+ for scale in [0.5, 0.75, 0.625] {
+ core.render_scale = scale;
+ core.render(1, |_, _| {});
+ assert_eq!(core.reconstruction(), method);
+ assert!(center(&core)[0] > 1000.0, "{}: missing dynamic input at {scale}", method.name());
+ }
+ core.set_camera(Camera::look_at(scene_cam.pos, scene_cam.pos + Vec3::Z, scene_cam.tan_half_fov));
+ core.render(1, |_, _| {});
+ // (The view after the turn sees surfaces the panel lights a little, ~4 here; history carried over reads ~1800.)
+ assert!(center(&core).iter().all(|v| *v < 100.0), "{}: bright history after cut", method.name());
+ core.resize(257, 161).unwrap();
+ core.set_camera(scene_cam);
+ core.render(1, |_, _| {});
+ assert!(center(&core)[0] > 1000.0, "{}: missing output after resize", method.name());
+ core.resize(320, 180).unwrap();
+ }
+}
+
+/// A request is a preference list: the first method this device runs is used, and the status says why each one
+/// before it did not. A typed quality preset is the vendors' exact ratio.
+#[test]
+fn reconstruction_takes_the_first_method_that_runs_and_says_why() {
+ assert_eq!(Reconstruction::parse("metalfx-denoised, builtin").unwrap(), Reconstruction::Prefer(vec![Method::MetalFxDenoised, Method::Builtin]));
+ assert_eq!(Reconstruction::from_json(&serde_json::json!(["dlss-rr", "fsr"])).unwrap().name(), "dlss-rr,fsr");
+ assert_eq!(Reconstruction::parse("auto").unwrap(), Reconstruction::Auto);
+ assert!(Reconstruction::parse("dlss-fg").is_err());
+ let r = RenderingRequest::from_json(&serde_json::json!({ "quality": "ultra-performance", "latency": "on", "frameGeneration": "2x" })).unwrap();
+ assert_eq!(((1920.0 * r.quality.unwrap().scale().unwrap()) as f32).round(), 640.0, "a third of 1080p's width is DLSS's 640");
+ assert!(RenderingRequest::from_json(&serde_json::json!({ "upscaler": "dlss" })).is_err(), "unknown settings are errors");
+
+ let Ok(g) = gpu::Gpu::new() else { return };
+ let mut live = LiveCore::new(g, &world(), Path::new("."), &crate::default_presets_dir(), 97, 55).unwrap();
+ live.view_mode = 0;
+ let control = RenderingControl::default();
+ live.attach_rendering_control(control.clone());
+ control.request(RenderingRequest { reconstruction: Some(Reconstruction::parse("custom:none,fsr").unwrap()), ..r });
+ live.render(1, |_, _| {});
+ assert_eq!(live.reconstruction(), Method::Fsr);
+ let st = control.status();
+ assert_eq!(st["reconstruction"]["active"], "fsr");
+ assert_eq!(st["reconstruction"]["denoise"], "builtin");
+ assert_eq!(st["reconstruction"]["fallback"], "unavailable");
+ assert_eq!(st["reconstruction"]["skipped"][0]["method"], "custom:none");
+ assert_eq!(st["quality"]["scale"], 1.0 / 3.0f32);
+ assert_eq!(st["latency"]["active"], "on");
+ assert_eq!(live.frames_in_flight(), 1);
+ assert_eq!(st["frameGeneration"]["fallback"], "unavailable", "no frame generation yet, and it says so");
+}
+
+/// A test provider: on prepare, a pipeline that writes (4, 8, 12) into the output; the frame after, it fails.
+struct ConstantOnce(Option<wgpu::ComputePipeline>);
+
+impl ConstantOnce {
+ fn prepare(&mut self, g: &gpu::Gpu) {
+ let d = &g.device;
+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: None,
+ source: wgpu::ShaderSource::Wgsl(r#"
+ @group(0) @binding(0) var image: texture_storage_2d<rgba16float, write>;
+ @compute @workgroup_size(8,8) fn put_color(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (all(id.xy < textureDimensions(image))) {
+ textureStore(image, id.xy, vec4<f32>(4.0, 8.0, 12.0, 1.0));
+ }
+ }
+ "#.into()),
+ });
+ self.0 = Some(d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: None, layout: None, module: &module, entry_point: Some("put_color"),
+ compilation_options: Default::default(), cache: None,
+ }));
+ }
+
+ fn encode(&mut self, f: &ReconstructionFrame<'_>, e: &mut wgpu::CommandEncoder) -> Result<Option<wgpu::CommandBuffer>> {
+ let Some(pipe) = self.0.take() else { anyhow::bail!("test provider rejected the frame") };
+ let bg = f.gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &pipe.get_bind_group_layout(0),
+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(f.output) }],
+ });
+ let mut pass = e.begin_compute_pass(&Default::default());
+ pass.set_pipeline(&pipe);
+ pass.set_bind_group(0, &bg, &[]);
+ pass.dispatch_workgroups(f.size.output[0].div_ceil(8), f.size.output[1].div_ceil(8), 1);
+ Ok(None)
+ }
+}
+
+impl UpscaleProvider for ConstantOnce {
+ fn prepare(&mut self, g: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { ConstantOnce::prepare(self, g); Ok(Prepared::ready(size)) }
+ fn encode(&mut self, f: ReconstructionFrame<'_>, e: &mut wgpu::CommandEncoder) -> Result<Option<wgpu::CommandBuffer>> { ConstantOnce::encode(self, &f, e) }
+}
+
+#[test]
+fn reconstruction_falls_back_in_the_frame_a_custom_provider_fails() {
+ let Ok(g) = gpu::Gpu::new() else { return };
+ let mut live = LiveCore::new(g, &world(), Path::new("."), &crate::default_presets_dir(), 97, 55).unwrap();
+ live.view_mode = 0;
+ live.set_scale(0.5);
+ let control = RenderingControl::default();
+ live.attach_rendering_control(control.clone());
+ live.register_upscaler("custom:test", ConstantOnce(None)).unwrap();
+ control.request(RenderingRequest { reconstruction: Some(Reconstruction::parse("custom:test").unwrap()), ..Default::default() });
+ live.render(1, |_, _| {});
+ let p = ((live.h / 2 * live.w + live.w / 2) * 3) as usize;
+ assert_eq!(&live.read_hdr().unwrap()[p..p+3], &[128.0, 256.0, 384.0]);
+ assert_eq!(control.status()["reconstruction"]["active"], "custom:test");
+ assert_eq!(control.status()["reconstruction"]["upscale"], "custom:test");
+
+ live.render(1, |_, _| {});
+ let hdr = live.read_hdr().unwrap();
+ assert!(hdr[p] > 0.01 && hdr[p] < 32.0, "expected scene radiance after failure, got {}", hdr[p]);
+ assert_eq!(control.status()["reconstruction"], serde_json::json!({
+ "requested": "custom:test", "active": "builtin", "denoise": "builtin", "upscale": "builtin", "fallback": "provider-error",
+ "skipped": [{ "method": "custom:test", "reason": "provider-error", "detail": "test provider rejected the frame" }],
+ }));
+}
+
+/// A joint denoiser gets the noisy signal and every guide, at the input's size in the contract's formats, and the
+/// built-in denoiser does not run.
+#[test]
+fn a_joint_denoiser_gets_the_noisy_signal_and_the_guides() {
+ struct Joint(ConstantOnce, std::sync::Arc<std::sync::Mutex<Vec<String>>>);
+ impl JointProvider for Joint {
+ fn prepare(&mut self, g: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { self.0.prepare(g); Ok(Prepared::ready(size)) }
+ fn encode(&mut self, f: ReconstructionFrame<'_>, j: JointGuides<'_>, e: &mut wgpu::CommandEncoder) -> Result<Option<wgpu::CommandBuffer>> {
+ let seen = [f.color, f.depth, f.motion, f.reactive, j.overlay, j.bypass, j.diffuse_albedo, j.specular_albedo, j.normal, j.roughness, j.specular_hit_distance]
+ .map(|v| { let t = v.texture(); format!("{:?} {}x{}", t.format(), t.width(), t.height()) });
+ *self.1.lock().unwrap() = seen.into_iter().chain([f.radiance_unit.to_string()]).collect();
+ if self.0.0.is_none() { self.0.prepare(f.gpu); }
+ self.0.encode(&f, e)
+ }
+ }
+ let Ok(g) = gpu::Gpu::new() else { return };
+ let mut w = world();
+ w.set_camera_desc(4, camera(50.0, None, manual(6.0))).unwrap();
+ let mut live = LiveCore::new(g, &w, Path::new("."), &crate::default_presets_dir(), 96, 54).unwrap();
+ live.view_mode = 0;
+ live.set_scale(0.5);
+ let seen = std::sync::Arc::new(std::sync::Mutex::new(vec![]));
+ live.register_joint_denoiser("custom:joint", Joint(ConstantOnce(None), seen.clone())).unwrap();
+ live.set_reconstruction(Method::parse("custom:joint").unwrap());
+ live.render(1, |_, _| {});
+ let st = live.reconstruction_status();
+ assert_eq!((st.denoise.as_str(), st.upscale.as_str()), ("custom:joint", "custom:joint"));
+ let seen = seen.lock().unwrap().clone();
+ let unit: f32 = seen[11].parse().unwrap();
+ assert_eq!(seen[..11], ["Rgba16Float 48x27", "R32Float 48x27", "Rg16Float 48x27", "R8Unorm 48x27", "Rgba16Float 48x27",
+ "R8Unorm 48x27", "Rgba8Unorm 48x27", "Rgba8Unorm 48x27", "Rgba16Float 48x27", "R16Float 48x27", "R16Float 48x27"]);
+ let p = ((live.h / 2 * live.w + live.w / 2) * 3) as usize;
+ // The output's (4, 8, 12), in the frame's unit, back in nits.
+ let hdr = live.read_hdr().unwrap();
+ assert!((hdr[p] / (4.0 * unit) - 1.0).abs() < 0.01 && (hdr[p + 2] / (12.0 * unit) - 1.0).abs() < 0.01, "{:?} at {unit}", &hdr[p..p + 3]);
+}
diff --git a/renderer/src/live/metalfx.m b/renderer/src/live/metalfx.m
new file mode 100644
index 0000000..43103fb
--- /dev/null
+++ b/renderer/src/live/metalfx.m
@@ -0,0 +1,169 @@
+// Objective-C owns the MetalFX scaler. wgpu owns the Metal device, textures and command buffer.
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#include <math.h>
+#include <stdatomic.h>
+#include <string.h>
+
+// GPU time (ms, float bits) of the last finished command buffer that ran a scaler: the engine's timestamps time its
+// own passes only, and the dynamic-resolution governor needs the whole frame.
+static _Atomic uint32_t threert_fx_ms_bits;
+float threert_fx_gpu_ms(void) {
+ uint32_t b = atomic_load_explicit(&threert_fx_ms_bits, memory_order_relaxed);
+ float f;
+ memcpy(&f, &b, sizeof f);
+ return f;
+}
+#if __has_include(<MetalFX/MetalFX.h>)
+#import <MetalFX/MetalFX.h>
+#endif
+
+// NULL with *why: 1 = no such scaler on this OS or device, 2 = the input's scale is outside scales[0..2], 3 = it failed.
+void *threert_fx_create(void *device, bool denoise, bool dynamic, uint32_t iw, uint32_t ih, uint32_t ow, uint32_t oh, float *scales, int32_t *why) {
+ @autoreleasepool {
+ *why = 1;
+#if __has_include(<MetalFX/MetalFX.h>)
+ if (@available(macOS 13, *)) {
+ // Resolve the framework at runtime so the same binary runs on older systems.
+ NSBundle *framework = [NSBundle bundleWithPath:@"/System/Library/Frameworks/MetalFX.framework"];
+ if (![framework load]) return NULL;
+ Class cls = NSClassFromString(denoise ? @"MTLFXTemporalDenoisedScalerDescriptor" : @"MTLFXTemporalScalerDescriptor");
+ id<MTLDevice> gpu = (__bridge id<MTLDevice>)device;
+ if (!cls || ![cls supportsDevice:gpu]) return NULL;
+ // Apple reports output / input (e.g. 1..3). Integer input dimensions can be rounded.
+ // Earlier SDKs have no capability query. Limit reuse to this configuration there.
+ scales[0] = fminf((float)ow / iw, (float)oh / ih);
+ scales[1] = fmaxf((float)ow / iw, (float)oh / ih);
+#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140000
+ if ([cls respondsToSelector:@selector(supportedInputContentMaxScaleForDevice:)]) {
+ float maxScale = [cls supportedInputContentMaxScaleForDevice:gpu];
+ float minScale = [cls supportedInputContentMinScaleForDevice:gpu];
+ if (!(minScale > 0 && maxScale >= minScale)) return NULL;
+ scales[0] = minScale;
+ scales[1] = maxScale;
+ if (iw < floorf(ow / maxScale) || ih < floorf(oh / maxScale) ||
+ iw > ceilf(ow / minScale) || ih > ceilf(oh / minScale)) { *why = 2; return NULL; }
+ }
+#endif
+ id desc = [cls new];
+ [desc setInputWidth:dynamic ? ow : iw];
+ [desc setInputHeight:dynamic ? oh : ih];
+ [desc setOutputWidth:ow];
+ [desc setOutputHeight:oh];
+ [desc setColorTextureFormat:MTLPixelFormatRGBA16Float];
+ [desc setDepthTextureFormat:MTLPixelFormatR32Float];
+ [desc setMotionTextureFormat:MTLPixelFormatRG16Float];
+ [desc setOutputTextureFormat:MTLPixelFormatRGBA16Float];
+ [desc setAutoExposureEnabled:NO];
+#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140400
+ if ([desc respondsToSelector:@selector(setReactiveMaskTextureEnabled:)]) {
+ [desc setReactiveMaskTextureEnabled:YES];
+ [desc setReactiveMaskTextureFormat:MTLPixelFormatR8Unorm];
+ }
+#endif
+ if (denoise) {
+#if __has_include(<MetalFX/MTLFXTemporalDenoisedScaler.h>)
+ if (@available(macOS 26, *)) {
+ MTLFXTemporalDenoisedScalerDescriptor *d = desc;
+ d.diffuseAlbedoTextureFormat = MTLPixelFormatRGBA8Unorm;
+ d.specularAlbedoTextureFormat = MTLPixelFormatRGBA8Unorm;
+ d.normalTextureFormat = MTLPixelFormatRGBA16Float;
+ d.roughnessTextureFormat = MTLPixelFormatR16Float;
+ d.specularHitDistanceTextureEnabled = YES;
+ d.specularHitDistanceTextureFormat = MTLPixelFormatR16Float;
+ d.denoiseStrengthMaskTextureEnabled = YES;
+ d.denoiseStrengthMaskTextureFormat = MTLPixelFormatR8Unorm;
+ d.transparencyOverlayTextureEnabled = YES;
+ d.transparencyOverlayTextureFormat = MTLPixelFormatRGBA16Float;
+ id made = [d newTemporalDenoisedScalerWithDevice:gpu];
+ *why = made ? 0 : 3;
+ return (__bridge_retained void *)made;
+ }
+#endif
+ return NULL;
+ }
+ MTLFXTemporalScalerDescriptor *t = desc;
+ if (dynamic) {
+ t.inputContentPropertiesEnabled = YES;
+ t.inputContentMinScale = scales[0];
+ t.inputContentMaxScale = scales[1];
+ }
+ id made = [t newTemporalScalerWithDevice:gpu];
+ *why = made ? 0 : 3;
+ return (__bridge_retained void *)made;
+ }
+#endif
+ return NULL;
+ }
+}
+
+void threert_fx_release(void *scaler) { CFRelease(scaler); }
+
+// The order is metalfx.rs's: the frame's colour, depth, motion, reactive; then the joint guides (live/reconstruction.rs).
+void threert_fx_bind(void *scaler, bool denoise, void *const *inputs, void *output) {
+#if __has_include(<MetalFX/MetalFX.h>)
+ id s = (__bridge id)scaler;
+ [s setColorTexture:(__bridge id)inputs[0]];
+ [s setDepthTexture:(__bridge id)inputs[1]];
+ [s setMotionTexture:(__bridge id)inputs[2]];
+#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 140400
+ if ([s respondsToSelector:@selector(setReactiveMaskTexture:)]) [s setReactiveMaskTexture:(__bridge id)inputs[3]];
+#endif
+ [s setOutputTexture:(__bridge id)output];
+#if __has_include(<MetalFX/MTLFXTemporalDenoisedScaler.h>)
+ if (denoise) {
+ id<MTLFXTemporalDenoisedScaler> d = s;
+ d.diffuseAlbedoTexture = (__bridge id)inputs[6];
+ d.specularAlbedoTexture = (__bridge id)inputs[7];
+ d.normalTexture = (__bridge id)inputs[8];
+ d.roughnessTexture = (__bridge id)inputs[9];
+ d.specularHitDistanceTexture = (__bridge id)inputs[10];
+ d.denoiseStrengthMaskTexture = (__bridge id)inputs[5];
+ d.transparencyOverlayTexture = (__bridge id)inputs[4];
+ }
+#endif
+#endif
+}
+
+void threert_fx_encode(void *scaler, bool denoise, void *command, bool reset, uint32_t iw, uint32_t ih, float jx, float jy,
+ const float *view, const float *projection) {
+#if __has_include(<MetalFX/MetalFX.h>)
+ @autoreleasepool {
+ id s = (__bridge id)scaler;
+ [s setDepthReversed:YES];
+ [s setJitterOffsetX:jx];
+ [s setJitterOffsetY:jy];
+ [s setMotionVectorScaleX:1.0f];
+ [s setMotionVectorScaleY:1.0f];
+ if (denoise) {
+#if __has_include(<MetalFX/MTLFXTemporalDenoisedScaler.h>)
+ id<MTLFXTemporalDenoisedScaler> d = s;
+ simd_float4x4 v, p;
+ memcpy(&v, view, sizeof(v));
+ memcpy(&p, projection, sizeof(p));
+ d.worldToViewMatrix = v;
+ d.viewToClipMatrix = p;
+ d.shouldResetHistory = reset;
+#endif
+ } else {
+ id<MTLFXTemporalScaler> t = s;
+ t.inputContentWidth = iw;
+ t.inputContentHeight = ih;
+ t.reset = reset;
+ }
+ id<MTLCommandBuffer> buffer = (__bridge id<MTLCommandBuffer>)command;
+ [(id<MTLFXTemporalScaler>)s encodeToCommandBuffer:buffer];
+ // wgpu uses unretained Metal command buffers. Keep the scaler (and its private working set)
+ // alive even when the next frame switches backend or recreates the surfaces.
+ [buffer addCompletedHandler:^(id<MTLCommandBuffer> completed) {
+ (void)[s class];
+ float ms = (float)((completed.GPUEndTime - completed.GPUStartTime) * 1000.0);
+ if (ms >= 0.0f && ms < 1000.0f) {
+ uint32_t b;
+ memcpy(&b, &ms, sizeof b);
+ atomic_store_explicit(&threert_fx_ms_bits, b, memory_order_relaxed);
+ }
+ }];
+ }
+#endif
+}
diff --git a/renderer/src/live/metalfx.rs b/renderer/src/live/metalfx.rs
new file mode 100644
index 0000000..6d7298b
--- /dev/null
+++ b/renderer/src/live/metalfx.rs
@@ -0,0 +1,138 @@
+//! Apple MetalFX: the temporal scaler as an upscaler, the temporal denoised scaler (macOS 26) as a joint denoiser
+//! (live/reconstruction.rs has the two contracts). The engine packs the signals; this binds its textures to the
+//! scaler (metalfx.m) and encodes the scaler into a Metal command buffer that wgpu submits between its own.
+use super::reconstruction::{JointGuides, JointProvider, Prepared, ReconstructionFrame, ReconstructionSize, UpscaleProvider};
+use super::{gpu, Result};
+use std::ffi::c_void;
+use std::ptr::NonNull;
+use wgpu::hal::api::Metal;
+
+unsafe extern "C" {
+ /// NULL with `why`: 1 = no such scaler on this OS or device, 2 = the input's scale is outside `scales`
+ /// (min, max output / input), 3 = the scaler failed to build.
+ fn threert_fx_create(device: *const c_void, denoise: bool, dynamic: bool, iw: u32, ih: u32, ow: u32, oh: u32, scales: *mut f32, why: *mut i32) -> *mut c_void;
+ fn threert_fx_release(scaler: *mut c_void);
+ fn threert_fx_gpu_ms() -> f32;
+ /// `inputs`: the frame's colour, depth, motion, reactive; then (denoise) overlay, bypass, diffuse albedo,
+ /// specular albedo, normal, roughness, specular hit distance.
+ fn threert_fx_bind(scaler: *mut c_void, denoise: bool, inputs: *const *const c_void, output: *const c_void);
+ fn threert_fx_encode(scaler: *mut c_void, denoise: bool, cmd: *const c_void, reset: bool, iw: u32, ih: u32, jx: f32, jy: f32, view: *const f32, projection: *const f32);
+}
+
+struct Scaler(NonNull<c_void>);
+// A retained Metal object can move with its LiveCore. Only an exclusive borrow of that core binds or encodes the
+// scaler, and command-buffer completion holds its own Objective-C retain.
+unsafe impl Send for Scaler {}
+impl Drop for Scaler {
+ fn drop(&mut self) { unsafe { threert_fx_release(self.0.as_ptr()) }; }
+}
+
+/// One MetalFX scaler, made for a size (and, for dynamic resolution, a range of input scales).
+pub(super) struct MetalFx {
+ denoise: bool,
+ scaler: Option<Scaler>,
+ /// Input, output, dynamic.
+ key: Option<([u32; 2], [u32; 2], bool)>,
+ /// Dynamic resolution (the plain scaler only): inputs in textures of the output's size, within these scales.
+ range: Option<[f32; 2]>,
+ /// A new scaler: no history yet.
+ fresh: bool,
+}
+
+impl MetalFx {
+ pub(super) fn upscaler() -> Self { Self { denoise: false, scaler: None, key: None, range: None, fresh: true } }
+ pub(super) fn denoiser() -> Self { Self { denoise: true, scaler: None, key: None, range: None, fresh: true } }
+
+ fn name(&self) -> &'static str {
+ if self.denoise { "the MetalFX temporal denoised scaler" } else { "the MetalFX temporal scaler" }
+ }
+
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Prepared {
+ let ReconstructionSize { input, output, dynamic } = size;
+ let key = Some((input, output, dynamic));
+ // The plain scaler takes a varying input within the range it was made for.
+ let dynamic_inputs = dynamic && !self.denoise;
+ if self.key != key && dynamic_inputs && self.scaler.is_some() {
+ if let (Some((_, prev_out, true)), Some([min, max])) = (self.key, self.range) {
+ let fits = |i: u32, o: u32| i >= (o as f32 / max).floor() as u32 && i <= (o as f32 / min).ceil() as u32;
+ if output == prev_out && fits(input[0], output[0]) && fits(input[1], output[1]) {
+ self.key = key;
+ }
+ }
+ }
+ if self.key != key || self.scaler.is_none() {
+ self.scaler = None;
+ self.key = None;
+ let mut scales = [1.0f32; 2];
+ let mut why = 0i32;
+ // (Release the HAL guard before further calls on the wgpu device.)
+ let raw = unsafe { gpu.device.as_hal::<Metal>() }.and_then(|dev| {
+ let ptr = std::ptr::from_ref(&**dev.raw_device()).cast();
+ NonNull::new(unsafe { threert_fx_create(ptr, self.denoise, dynamic_inputs, input[0], input[1], output[0], output[1], scales.as_mut_ptr(), &mut why) })
+ });
+ let Some(raw) = raw else {
+ return Prepared::Unsupported(match why {
+ 1 => format!("this Mac has no {} (macOS {} or later on Apple silicon)", self.name(), if self.denoise { 26 } else { 13 }),
+ 2 => format!("{} takes outputs {:.2}x to {:.2}x its input; {}x{} to {}x{} is {:.2}x", self.name(), scales[0], scales[1],
+ input[0], input[1], output[0], output[1], output[0] as f32 / input[0] as f32),
+ _ => format!("{} could not be made for {}x{} to {}x{}", self.name(), input[0], input[1], output[0], output[1]),
+ });
+ };
+ self.scaler = Some(Scaler(raw));
+ self.key = key;
+ self.range = dynamic_inputs.then_some(scales);
+ self.fresh = true;
+ }
+ Prepared::Ready { capacity: if self.range.is_some() { output } else { input } }
+ }
+
+ fn encode(&mut self, f: &ReconstructionFrame<'_>, guides: Option<&JointGuides<'_>>) -> Result<Option<wgpu::CommandBuffer>> {
+ let scaler = self.scaler.as_ref().ok_or_else(|| anyhow::anyhow!("MetalFX was not prepared"))?.0.as_ptr();
+ // The textures' Metal objects; the scaler retains what it is given.
+ let raw = |v: &wgpu::TextureView| -> Result<*const c_void> {
+ let t = v.texture();
+ let hal = unsafe { t.as_hal::<Metal>() }.ok_or_else(|| anyhow::anyhow!("not a Metal texture"))?;
+ Ok(std::ptr::from_ref(hal.raw_handle()).cast::<c_void>())
+ };
+ let mut views = vec![f.color, f.depth, f.motion, f.reactive];
+ if let Some(g) = guides {
+ views.extend([g.overlay, g.bypass, g.diffuse_albedo, g.specular_albedo, g.normal, g.roughness, g.specular_hit_distance]);
+ }
+ let inputs = views.into_iter().map(raw).collect::<Result<Vec<_>>>()?;
+ let output = raw(f.output)?;
+ unsafe { threert_fx_bind(scaler, self.denoise, inputs.as_ptr(), output) };
+ // wgpu 30 permits one encoding API per encoder: the scaler gets a command buffer of its own, submitted after
+ // the encoder that packed its inputs and before the one that reads its output, on the same queue (Metal's
+ // tracked hazards order the accesses; wgpu keeps the textures alive through the submission).
+ let mut native = f.gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("MetalFX") });
+ let [iw, ih] = f.size.input;
+ unsafe {
+ native.as_hal_mut::<Metal, _, _>(|encoder| {
+ let cmd = encoder.and_then(|e| e.raw_command_buffer()).expect("Metal command buffer");
+ // MetalFX's jitter is the shift of the projected image: opposite to the sample's.
+ threert_fx_encode(scaler, self.denoise, std::ptr::from_ref(cmd).cast(), f.reset || self.fresh, iw, ih,
+ -f.jitter[0], -f.jitter[1], f.world_to_view.as_ptr(), f.view_to_clip.as_ptr());
+ });
+ }
+ self.fresh = false;
+ Ok(Some(native.finish()))
+ }
+}
+
+impl UpscaleProvider for MetalFx {
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { Ok(MetalFx::prepare(self, gpu, size)) }
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, _: &mut wgpu::CommandEncoder) -> Result<Option<wgpu::CommandBuffer>> {
+ MetalFx::encode(self, &frame, None)
+ }
+ fn untimed_gpu_ms(&self) -> f32 { if self.scaler.is_some() { unsafe { threert_fx_gpu_ms() } } else { 0.0 } }
+ fn invalidate(&mut self) { self.scaler = None; self.key = None; }
+}
+
+impl JointProvider for MetalFx {
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> { Ok(MetalFx::prepare(self, gpu, size)) }
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, guides: JointGuides<'_>, _: &mut wgpu::CommandEncoder) -> Result<Option<wgpu::CommandBuffer>> {
+ MetalFx::encode(self, &frame, Some(&guides))
+ }
+ fn untimed_gpu_ms(&self) -> f32 { if self.scaler.is_some() { unsafe { threert_fx_gpu_ms() } } else { 0.0 } }
+ fn invalidate(&mut self) { self.scaler = None; self.key = None; }
+}
diff --git a/renderer/src/live/mod.rs b/renderer/src/live/mod.rs
index 962a521..9da5930 100644
--- a/renderer/src/live/mod.rs
+++ b/renderer/src/live/mod.rs
@@ -49,8 +49,15 @@ use web_time::Instant;
mod edits;
mod frame;
+#[cfg(dlss)]
+mod dlss;
+mod fsr;
mod layout;
+#[cfg(target_os = "macos")]
+mod metalfx;
mod load;
+mod reconstruction;
+mod rendering;
#[cfg(not(target_arch = "wasm32"))]
mod session;
mod state;
@@ -60,6 +67,9 @@ pub(crate) use targets::live_source;
pub(crate) use targets::Targets;
#[cfg(not(target_arch = "wasm32"))]
pub use session::{parse_cmd, parse_launch, parse_opts, run, save_bgra};
+pub use reconstruction::{JointGuides, JointProvider, Method, Prepared, Reconstruction, ReconstructionFrame, ReconstructionSize, ReconstructionStatus, Skip, UpscaleProvider};
+pub use rendering::{next_method, FrameGeneration, Latency, Quality, RenderingControl, RenderingRequest, RenderingStatus};
+use reconstruction::Reconstructor;
use edits::*;
use frame::*;
use load::*;
@@ -67,6 +77,8 @@ use state::*;
use targets::*;
pub struct LiveOpts {
+ /// `--quality`, `--reconstruction`, `--frame-generation`, `--latency` (live/rendering.rs); `--quality` over `scale`.
+ pub rendering: RenderingRequest,
pub width: u32,
pub height: u32,
pub fps: u32,
@@ -215,6 +227,8 @@ pub enum Cmd {
Status(String),
/// Render scale (0 = dynamic resolution).
Scale(f32),
+ /// Rendering settings (live/rendering.rs): the fields given change.
+ Rendering(RenderingRequest),
/// The view at another size, pixels (`LiveCore::resize`; the window host: its window's).
Resize(u32, u32),
Quit,
@@ -223,6 +237,12 @@ pub enum Cmd {
/// The real-time renderer: scene + screen targets + camera/history state. Records one frame at a time; the output
/// (sRGB BGRA8 per pixel) lands in `targets.out`. Used by the headless runner, the native window viewer and the native clients.
pub struct LiveCore {
+ reconstructor: Reconstructor,
+ /// The requested render resolution (`render_scale` and `dynamic_res` are what it resolves to).
+ quality: Quality,
+ frame_generation: FrameGeneration,
+ latency: Latency,
+ rendering_control: Option<RenderingControl>,
/// The game's particle spawns since the last frame (`World::particle_spawns`), for the GPU particle pass.
particle_spawns: std::collections::BTreeMap<u32, Vec<f32>>,
/// The sources the game gave its density grids since the last frame (`World::grid_sources`), for the grid pass.
@@ -540,12 +560,78 @@ impl LiveCore {
// brings it, `gpu::loop_guard_of`.)
let guard_read = (gpu::loop_guard_of(!g.hwrt).is_some() && targets.kernel.guard.is_some())
.then(|| (g.device.create_buffer(&wgpu::BufferDescriptor { label: Some("loop guard read"), size: 4, usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false }), Arc::new(AtomicU32::new(0))));
- let mut core = LiveCore { pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
+ let reconstructor = Reconstructor::default();
+ #[cfg(not(target_arch = "wasm32"))]
+ let reconstructor = {
+ let mut reconstructor = reconstructor;
+ if let Ok(mode) = std::env::var("THREERT_RECONSTRUCTION") {
+ reconstructor.set(Reconstruction::parse(&mode)?);
+ }
+ reconstructor
+ };
+ let mut core = LiveCore {
+ reconstructor, quality: Quality::Native, frame_generation: FrameGeneration::Off, latency: Latency::Auto, rendering_control: None, pending_emitters: vec![], flipped: vec![], top_builds: 0, particle_spawns: Default::default(), grid_sources: Default::default(), g, passes, targets, sc, view, env, presets: presets.to_path_buf(), assets: assets.to_path_buf(), w, h, seq: 0, aspect: w as f32 / h as f32, cam, prev_cam: cam, frame: 0, history_len: 0.0, reset: true, bloom: ([0.0; 6], [0.0; 6]), vignette: 0.0, post: [0.0; 4], blur: (0.0, 0.0), inflight: Default::default(), gpu_ms: 0.0, gpu_frame: 0, gpu_trace_ms: 0.0, edit_ms: 0.0, instanced_ms: 0.0, build_ms: 0.0, edit_split: EditSplit::default(), rebuild_ms: 0.0, fallback: None, fallbacks: 0, bounces: 4, rays: true, view_mode: std::env::var("THREERT_VIEW_MODE").ok().and_then(|v| v.parse().ok()).unwrap_or(0), fixed_dt: None, triangles, scene_name, time: 0.0, frame_dt: 1.0 / 60.0, last_frame: Instant::now(), post_key: String::new(), render_scale: 1.0, dynamic_res: false, min_scale: MIN_SCALE, display_scale: 1.0, over_budget: (0, 0), born: Instant::now(), governed: Instant::now(), profile, timer, raster, cache, kernel_bg, tl_kernel_bg, prev_span: None, reposed: false, emitters_moved: false, emitters_reweigh: false, pose_spans: vec![], pose_reposed: false, inst_moving: vec![], inst_moved: false, prev_isz: (0, 0), light_tiles: None, lit_changed: 0, spark_lights: false, shown_spp: 1, cpu_skin_ms: 0.0, cpu_upload_ms: 0.0, gpu_blas_ms: 0.0, cpu_wait_ms: 0.0, guard_trips: guard_read.as_ref().map(|_| 0), guard_read };
core.spark_lights = core.sc.tables.emitter_tris.iter().any(|e| e.nominal);
core.apply_post();
Ok(core)
}
+ /// Change the rendering settings given (live/rendering.rs); from the next frame.
+ pub fn set_rendering(&mut self, r: RenderingRequest) {
+ if let Some(q) = r.quality {
+ self.set_scale(q.scale().unwrap_or(0.0));
+ self.quality = q;
+ }
+ if let Some(m) = r.reconstruction { self.set_reconstruction(m); }
+ if let Some(f) = r.frame_generation { self.frame_generation = f; }
+ if let Some(l) = r.latency { self.latency = l; }
+ }
+
+ /// A reconstruction request: a method, a preference list, or `Reconstruction::Auto`.
+ pub fn set_reconstruction(&mut self, r: impl Into<Reconstruction>) {
+ if self.reconstructor.set(r.into()) {
+ self.reset_history();
+ }
+ }
+
+ /// The method the last frame ran.
+ pub fn reconstruction(&self) -> Method { self.reconstructor.method() }
+
+ pub fn requested_reconstruction(&self) -> &Reconstruction { &self.reconstructor.requested }
+
+ pub fn reconstruction_status(&self) -> ReconstructionStatus { self.reconstructor.status() }
+
+ pub fn rendering_status(&self) -> RenderingStatus {
+ RenderingStatus {
+ quality: self.quality, scale: self.render_scale, dynamic: self.dynamic_res,
+ reconstruction: self.reconstruction_status(), frame_generation: self.frame_generation, latency: self.latency,
+ frames_in_flight: self.frames_in_flight() as u32,
+ }
+ }
+
+ /// Frames the CPU may record ahead of the GPU: one with low latency on (or frames generated, which need it).
+ pub(crate) fn frames_in_flight(&self) -> usize {
+ match self.latency { Latency::On => 1, Latency::Off | Latency::Auto => 2 }
+ }
+
+ /// Install an upscaler (live/reconstruction.rs), selected as `custom:<id>` like a built-in method.
+ pub fn register_upscaler(&mut self, id: &str, provider: impl UpscaleProvider + 'static) -> Result<()> {
+ self.reconstructor.register_upscaler(id, Box::new(provider))
+ }
+
+ /// Install a joint denoiser (live/reconstruction.rs), selected as `custom:<id>` like a built-in method.
+ pub fn register_joint_denoiser(&mut self, id: &str, provider: impl JointProvider + 'static) -> Result<()> {
+ self.reconstructor.register_joint(id, Box::new(provider))
+ }
+
+ /// Share the settings with a game runtime or a page: its requests apply from the next frame, and it reads each
+ /// frame's status.
+ pub fn attach_rendering_control(&mut self, control: RenderingControl) {
+ if let Some(r) = control.take() { self.set_rendering(r); }
+ control.publish(self.rendering_status());
+ self.rendering_control = Some(control);
+ }
+
pub fn scene_camera(&self) -> Camera {
self.view.camera
}
@@ -678,6 +764,7 @@ impl LiveCore {
/// Fixed render scale (`s` in SCALE_FLOOR ..= 1), or dynamic resolution (`s` = 0).
pub fn set_scale(&mut self, s: f32) {
+ self.quality = if s <= 0.0 { Quality::Auto } else { Quality::Scale(s) };
self.dynamic_res = s <= 0.0;
if s > 0.0 {
self.render_scale = s.clamp(SCALE_FLOOR, 1.0);
@@ -739,6 +826,7 @@ impl LiveCore {
anyhow::bail!("a view of {w} x {h}: more samples than this device holds in one buffer");
}
(self.w, self.h, self.aspect) = (w, h, w as f32 / h as f32);
+ self.reconstructor.invalidate();
self.targets.resize(&self.g, &self.passes, w, h);
if self.raster.is_some() {
self.raster = Some(Raster::new(&self.g, w, h));
@@ -1033,6 +1121,8 @@ impl LiveCore {
let c = &self.cam;
serde_json::json!({
"seq": self.seq, "frame": self.frame, "history": self.history_len, "gpu_ms": self.gpu_ms,
+ "reconstruction": self.reconstruction().name(), "requested_reconstruction": self.requested_reconstruction().name(),
+ "reconstruction_fallback": self.reconstructor.status().fallback.map(Skip::name), "rendering": self.rendering_status().json(),
"scene": self.scene_name, "triangles": self.triangles, "bounces": self.bounces, "mode": self.view_mode, "width": self.w, "height": self.h, "scale": self.render_scale,
"cam": { "pos": c.pos.to_array(), "fwd": c.fwd.to_array(), "up": c.up.to_array(), "right": c.right.to_array(), "tan": c.tan_half_fov, "aspect": self.aspect },
})
diff --git a/renderer/src/live/reconstruction.rs b/renderer/src/live/reconstruction.rs
new file mode 100644
index 0000000..9bf17e3
--- /dev/null
+++ b/renderer/src/live/reconstruction.rs
@@ -0,0 +1,712 @@
+//! Live reconstruction: the path tracer's few samples a pixel, at the render resolution, made into a clean image at
+//! the output resolution. That is two jobs, in this order:
+//!
+//! 1. **denoise**: the samples' noise (too few rays a pixel);
+//! 2. **upscale**: the image to the output size, anti-aliased (too few pixels), from the history of earlier frames.
+//!
+//! ThreeRT does both itself (`builtin`: live.wgsl `refl` .. `sfilt2`, then `lock_carry` .. `upscale`). Vendor
+//! technology takes over either the second job or both, and that is the only distinction the engine makes:
+//!
+//! - an **upscaler** ([`UpscaleProvider`]: DLSS Super Resolution and DLAA, the MetalFX temporal scaler, XeSS SR,
+//! FSR 2+, ...) reads ThreeRT's *denoised* image and replaces the upscale stage;
+//! - a **joint denoiser** ([`JointProvider`]: DLSS Ray Reconstruction, the MetalFX temporal denoised scaler, ...)
+//! reads the *noisy* signal, with the surface guides it needs to tell lighting from texture (albedos, normal,
+//! roughness, specular hit distance), and replaces both. One network that sees the raw signal keeps detail a
+//! separate denoiser would have averaged away before the upscaler saw it, and keeps one history instead of two.
+//!
+//! The two read different signals, so they are two contracts ([`ReconstructionFrame`], plus [`JointGuides`] for a
+//! joint denoiser), not variants of one. The engine owns the contracts: it packs the signals into textures and takes
+//! the result back into its post chain, so a vendor's code is an adapter of a few calls.
+//!
+//! A request ([`Reconstruction`]) is an ordered list of methods ([`Method`]); the first this device runs is used.
+//! The status says which ran, what each stage is, and why each method before it did not (nothing falls back
+//! silently).
+use super::{fsr, gpu, targets, Camera, Result, Targets};
+use std::sync::Arc;
+use wgpu::{CommandBuffer, CommandEncoder, TextureView};
+
+/// One way of reconstructing the frame: who denoises and who upscales.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub enum Method {
+ /// ThreeRT's denoiser, then its temporal upscaler.
+ Builtin,
+ /// Neither: each frame's samples as traced (the signal a joint denoiser receives), brought to the output size
+ /// without history. A view of the input, not a way to ship.
+ Off,
+ /// ThreeRT's denoiser, then FidelityFX Super Resolution 1 (spatial: no history).
+ Fsr,
+ /// ThreeRT's denoiser, then the MetalFX temporal scaler (macOS 13+).
+ MetalFx,
+ /// The MetalFX temporal denoised scaler: both jobs (macOS 26+, Apple silicon).
+ MetalFxDenoised,
+ /// ThreeRT's denoiser, then DLSS Super Resolution (DLAA at scale 1; NVIDIA RTX, feature `dlss`).
+ Dlss,
+ /// DLSS Ray Reconstruction: both jobs (NVIDIA RTX, feature `dlss`).
+ DlssRr,
+ /// A provider the embedding host registered under `custom:<id>` (either contract).
+ Custom(Arc<str>),
+}
+
+impl Method {
+ pub fn name(&self) -> &str {
+ match self {
+ Self::Builtin => "builtin",
+ Self::Off => "off",
+ Self::Fsr => "fsr",
+ Self::MetalFx => "metalfx",
+ Self::MetalFxDenoised => "metalfx-denoised",
+ Self::Dlss => "dlss",
+ Self::DlssRr => "dlss-rr",
+ Self::Custom(id) => id,
+ }
+ }
+
+ pub fn parse(s: &str) -> Result<Self> {
+ Ok(match s.trim() {
+ "builtin" => Self::Builtin,
+ "off" => Self::Off,
+ "fsr" => Self::Fsr,
+ "metalfx" => Self::MetalFx,
+ "metalfx-denoised" => Self::MetalFxDenoised,
+ "dlss" => Self::Dlss,
+ "dlss-rr" => Self::DlssRr,
+ s if s.strip_prefix("custom:").is_some_and(|id| {
+ (1..=48).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
+ }) => Self::Custom(Arc::from(s)),
+ s => anyhow::bail!("unknown reconstruction '{s}'; use auto, builtin, off, fsr, metalfx, metalfx-denoised, dlss, dlss-rr or custom:<id>"),
+ })
+ }
+
+ /// The methods this build could run on its platform, in the order the viewer's key cycles them.
+ pub fn platform() -> Vec<Method> {
+ let mut m = vec![Self::Builtin];
+ #[cfg(target_os = "macos")]
+ m.extend([Self::MetalFxDenoised, Self::MetalFx]);
+ #[cfg(dlss)]
+ m.extend([Self::DlssRr, Self::Dlss]);
+ m.extend([Self::Fsr, Self::Off]);
+ m
+ }
+}
+
+/// A reconstruction request: the methods to try, in order of preference.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Reconstruction {
+ /// The best this device runs: a joint denoiser, else an upscaler, else ThreeRT's own.
+ Auto,
+ /// These, in order; ThreeRT's own after the last if none of them runs.
+ Prefer(Vec<Method>),
+}
+
+impl Default for Reconstruction {
+ fn default() -> Self { Self::Prefer(vec![Method::Builtin]) }
+}
+
+impl From<Method> for Reconstruction {
+ fn from(m: Method) -> Self { Self::Prefer(vec![m]) }
+}
+
+impl Reconstruction {
+ /// `auto`, one method, or a comma-separated list (`metalfx-denoised,metalfx,builtin`).
+ pub fn parse(s: &str) -> Result<Self> {
+ if s.trim() == "auto" { return Ok(Self::Auto); }
+ let methods = s.split(',').filter(|m| !m.trim().is_empty()).map(Method::parse).collect::<Result<Vec<_>>>()?;
+ anyhow::ensure!(!methods.is_empty(), "empty reconstruction request");
+ Ok(Self::Prefer(methods))
+ }
+
+ /// A string as in [`Self::parse`] or an array of method names.
+ pub fn from_json(v: &serde_json::Value) -> Result<Self> {
+ match v {
+ serde_json::Value::String(s) => Self::parse(s),
+ serde_json::Value::Array(a) => {
+ let names = a.iter().map(|m| m.as_str().ok_or_else(|| anyhow::anyhow!("reconstruction methods are strings"))).collect::<Result<Vec<_>>>()?;
+ Self::parse(&names.join(","))
+ }
+ _ => anyhow::bail!("reconstruction is a method name, a list of them, or \"auto\""),
+ }
+ }
+
+ pub fn name(&self) -> String {
+ match self {
+ Self::Auto => "auto".into(),
+ Self::Prefer(m) => m.iter().map(Method::name).collect::<Vec<_>>().join(","),
+ }
+ }
+
+ /// The methods tried, in order. Each ends with `builtin`, which always runs.
+ fn chain(&self) -> Vec<Method> {
+ let mut chain = match self {
+ Self::Auto => {
+ #[allow(unused_mut)]
+ let mut m = vec![];
+ #[cfg(target_os = "macos")]
+ m.extend([Method::MetalFxDenoised, Method::MetalFx]);
+ #[cfg(dlss)]
+ m.extend([Method::DlssRr, Method::Dlss]);
+ m
+ }
+ Self::Prefer(m) => m.clone(),
+ };
+ if !chain.contains(&Method::Builtin) { chain.push(Method::Builtin); }
+ chain
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ReconstructionSize {
+ /// The traced image (the render resolution).
+ pub input: [u32; 2],
+ /// The view.
+ pub output: [u32; 2],
+ /// Dynamic resolution: `input` changes from frame to frame.
+ pub dynamic: bool,
+}
+
+/// What a provider's `prepare` answers.
+pub enum Prepared {
+ /// It runs at this size. Its input textures are `capacity` (at least `size.input`; larger for a provider that
+ /// takes a varying input in fixed textures); each frame's input is their top-left `size.input`.
+ Ready { capacity: [u32; 2] },
+ /// It does not run here; the reason goes to the status (e.g. "input 639 x 360 is below DLSS's 640 x 360").
+ Unsupported(String),
+}
+
+impl Prepared {
+ /// Ready, with input textures exactly the input's size.
+ pub fn ready(size: ReconstructionSize) -> Self { Self::Ready { capacity: size.input } }
+}
+
+/// The signals both contracts share. Textures are on the live device, top-left origin, valid for this encode only.
+pub struct ReconstructionFrame<'a> {
+ pub gpu: &'a gpu::Gpu,
+ pub size: ReconstructionSize,
+ /// RGBA16Float, scene-linear HDR radiance in units of `radiance_unit` (nonnegative, alpha 1). An upscaler gets
+ /// ThreeRT's denoised image; a joint denoiser the traced lighting, noisy, without [`JointGuides::overlay`].
+ pub color: &'a TextureView,
+ /// R32Float, reversed infinite Z (near = 0.01 m, sky = 0), the projection of `view_to_clip`.
+ pub depth: &'a TextureView,
+ /// RG16Float, current-to-previous displacement in input pixels; no jitter in it.
+ pub motion: &'a TextureView,
+ /// R8Unorm, 0 = stable, 1 = fully reactive (history unusable: animated shading, media).
+ pub reactive: &'a TextureView,
+ /// RGBA16Float storage texture of `size.output`: write the full image, in the same units as `color`.
+ pub output: &'a TextureView,
+ /// Nits per unit of `color`.
+ pub radiance_unit: f32,
+ /// Sample position minus pixel centre, in input pixels (+Y down).
+ pub jitter: [f32; 2],
+ /// Discard history: cuts, mode changes, recreated textures, an exposure change.
+ pub reset: bool,
+ pub camera: Camera,
+ pub aspect: f32,
+ /// Column-major, right-handed, the camera at the origin looking down -Z.
+ pub world_to_view: [f32; 16],
+ /// Column-major, reversed infinite Z with near 0.01 m (`depth`'s projection), unjittered.
+ pub view_to_clip: [f32; 16],
+}
+
+/// What a joint denoiser reads besides [`ReconstructionFrame`], at the same size.
+pub struct JointGuides<'a> {
+ /// RGBA16Float, radiance that has no noise to remove (emitters and sky seen directly, or through a mirror or
+ /// clear glass), in `radiance_unit`; alpha 1 where the pixel is entirely that. Composite over the result.
+ pub overlay: &'a TextureView,
+ /// R8Unorm, 1 = do not denoise this pixel (the overlay's).
+ pub bypass: &'a TextureView,
+ /// RGBA8Unorm, the diffuse reflectance seen at the pixel (the virtual surface's through a mirror).
+ pub diffuse_albedo: &'a TextureView,
+ /// RGBA8Unorm, the specular reflectance (directional albedo of the specular lobe).
+ pub specular_albedo: &'a TextureView,
+ /// RGBA16Float, world-space unit normal (xyz).
+ pub normal: &'a TextureView,
+ /// R16Float, linear roughness, 0 = mirror.
+ pub roughness: &'a TextureView,
+ /// R16Float, metres from the surface to what its specular ray hit (0 where unknown).
+ pub specular_hit_distance: &'a TextureView,
+}
+
+/// Replaces the upscale stage; reads ThreeRT's denoised image. ThreeRT still denoises and runs its post chain.
+pub trait UpscaleProvider: Send {
+ /// On first use and when the size changes.
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared>;
+
+ /// Record on `encoder`, or return a native command buffer ordered after it and before ThreeRT reads `output`.
+ /// A native provider records its resource transitions on `encoder` and keeps its resources alive through GPU use.
+ /// On error the encoder stays usable; the frame falls back to ThreeRT's own.
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>>;
+
+ /// GPU time (ms) of work outside `encoder` (a native command buffer), last finished frame: added to the frame's,
+ /// which the dynamic-resolution governor steers by.
+ fn untimed_gpu_ms(&self) -> f32 { 0.0 }
+
+ /// The view was resized: release size-dependent state.
+ fn invalidate(&mut self) {}
+}
+
+/// Replaces both stages; reads the noisy signal and the guides. ThreeRT's denoiser does not run.
+pub trait JointProvider: Send {
+ fn prepare(&mut self, gpu: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared>;
+ /// As [`UpscaleProvider::encode`].
+ fn encode(&mut self, frame: ReconstructionFrame<'_>, guides: JointGuides<'_>, encoder: &mut CommandEncoder) -> Result<Option<CommandBuffer>>;
+ fn untimed_gpu_ms(&self) -> f32 { 0.0 }
+ fn invalidate(&mut self) {}
+}
+
+enum Provider {
+ Upscale(Box<dyn UpscaleProvider>),
+ Joint(Box<dyn JointProvider>),
+}
+
+impl Provider {
+ fn joint(&self) -> bool { matches!(self, Self::Joint(_)) }
+ fn prepare(&mut self, g: &gpu::Gpu, size: ReconstructionSize) -> Result<Prepared> {
+ match self { Self::Upscale(p) => p.prepare(g, size), Self::Joint(p) => p.prepare(g, size) }
+ }
+ fn untimed_gpu_ms(&self) -> f32 {
+ match self { Self::Upscale(p) => p.untimed_gpu_ms(), Self::Joint(p) => p.untimed_gpu_ms() }
+ }
+ fn invalidate(&mut self) {
+ match self { Self::Upscale(p) => p.invalidate(), Self::Joint(p) => p.invalidate() }
+ }
+}
+
+/// What ran: the pipeline's configuration for a frame.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub(super) enum Active {
+ #[default]
+ Builtin,
+ Off,
+ Fsr,
+ /// `providers[i]`, an upscaler.
+ Upscaler(usize),
+ /// `providers[i]`, a joint denoiser.
+ Joint(usize),
+}
+
+/// The built-in denoiser's passes (live/layout.rs `PASSES`).
+fn denoise_pass(pass: &str) -> bool {
+ matches!(pass, "refl" | "dtemporal" | "stemporal") || pass.starts_with("atrous") || pass.starts_with("sfilt")
+}
+
+/// The built-in temporal upscaler's passes.
+fn upscale_pass(pass: &str) -> bool {
+ matches!(pass, "lock_carry" | "track" | "judge" | "reject" | "upscale")
+}
+
+impl Active {
+ /// The trace leaves its raw signal (no demodulation, the whole specular path) for something other than
+ /// ThreeRT's denoiser: `compose` writes it as it is (`L.mode.w`, the kernel's `P.motion.y`).
+ pub(super) fn raw_signal(self) -> bool { matches!(self, Self::Off | Self::Joint(_)) }
+
+ /// The kernel computes the joint denoiser's surface guides (pathtrace.wgsl `surface_guides`).
+ pub(super) fn guides(self) -> bool { matches!(self, Self::Joint(_)) }
+
+ /// Nothing of an earlier frame is used (the reset lane stays set: `L.size.w`).
+ pub(super) fn history_free(self) -> bool { self == Self::Off }
+
+ /// No sub-pixel jitter: nothing accumulates it.
+ pub(super) fn unjittered(self) -> bool { matches!(self, Self::Off | Self::Fsr) }
+
+ /// A provider takes the upscale stage's place (its passes do not run; it does, where `upscale` would).
+ pub(super) fn external(self) -> bool { matches!(self, Self::Fsr | Self::Upscaler(_) | Self::Joint(_)) }
+
+ pub(super) fn skips(self, pass: &str) -> bool {
+ (self.external() && upscale_pass(pass)) || (self.raw_signal() && denoise_pass(pass))
+ }
+}
+
+/// Why a method in the request did not run.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Skip {
+ /// Not in this build or on this platform, or no such provider registered.
+ Unavailable,
+ /// The device, the OS or this size is outside what it supports.
+ Unsupported,
+ /// It failed (at prepare or encode).
+ ProviderError,
+ /// A view mode (base colour, normals, ...) is on: those are ThreeRT's own buffers.
+ DiagnosticView,
+}
+
+impl Skip {
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Unavailable => "unavailable",
+ Self::Unsupported => "unsupported",
+ Self::ProviderError => "provider-error",
+ Self::DiagnosticView => "diagnostic-view",
+ }
+ }
+}
+
+/// Which method ran, each stage's implementation, and why the methods before it did not.
+#[derive(Clone, Debug, Default)]
+pub struct ReconstructionStatus {
+ pub requested: String,
+ /// None before the first frame.
+ pub active: Option<String>,
+ /// "builtin", "none" or the joint denoiser's method.
+ pub denoise: String,
+ /// "builtin", "none" or the provider's method.
+ pub upscale: String,
+ /// The first skipped method's reason, unless the request was `auto`.
+ pub fallback: Option<Skip>,
+ /// Method, reason, detail: each method tried before the one that ran.
+ pub skipped: Vec<(String, Skip, String)>,
+}
+
+impl ReconstructionStatus {
+ pub fn json(&self) -> serde_json::Value {
+ serde_json::json!({
+ "requested": self.requested, "active": self.active, "denoise": self.denoise, "upscale": self.upscale,
+ "fallback": self.fallback.map(Skip::name),
+ "skipped": self.skipped.iter().map(|(m, s, d)| serde_json::json!({ "method": m, "reason": s.name(), "detail": d })).collect::<Vec<_>>(),
+ })
+ }
+}
+
+pub(super) struct Reconstructor {
+ pub(super) requested: Reconstruction,
+ pub(super) active: Active,
+ key: Option<(ReconstructionSize, bool)>,
+ skipped: Vec<(Method, Skip, String)>,
+ fsr: Option<fsr::Fsr>,
+ providers: Vec<(Method, Provider)>,
+ // Fields drop in declaration order: providers release GPU work before their input/output textures.
+ textures: Option<ProviderTextures>,
+ pipes: Option<ProviderPipelines>,
+}
+
+impl Default for Reconstructor {
+ fn default() -> Self {
+ #[allow(unused_mut)]
+ let mut providers: Vec<(Method, Provider)> = vec![];
+ #[cfg(target_os = "macos")]
+ providers.extend([
+ (Method::MetalFx, Provider::Upscale(Box::new(super::metalfx::MetalFx::upscaler()))),
+ (Method::MetalFxDenoised, Provider::Joint(Box::new(super::metalfx::MetalFx::denoiser()))),
+ ]);
+ #[cfg(dlss)]
+ providers.extend([
+ (Method::Dlss, Provider::Upscale(Box::new(super::dlss::Dlss::default()))),
+ (Method::DlssRr, Provider::Joint(Box::new(super::dlss::DlssRr::default()))),
+ ]);
+ Self { requested: Reconstruction::default(), active: Active::Builtin, key: None, skipped: vec![], fsr: None, providers, textures: None, pipes: None }
+ }
+}
+
+impl Reconstructor {
+ /// A new request (the frame after resolves it). False if it is the current one.
+ pub(super) fn set(&mut self, r: Reconstruction) -> bool {
+ if self.requested == r { return false; }
+ self.requested = r;
+ self.key = None;
+ true
+ }
+
+ fn register(&mut self, id: &str, provider: Provider) -> Result<()> {
+ let m = Method::parse(id)?;
+ anyhow::ensure!(matches!(m, Method::Custom(_)), "a provider's id is custom:<id>");
+ anyhow::ensure!(!self.providers.iter().any(|(k, _)| *k == m), "a reconstruction provider '{id}' is registered already");
+ self.key = None;
+ self.providers.push((m, provider));
+ Ok(())
+ }
+
+ pub(super) fn register_upscaler(&mut self, id: &str, p: Box<dyn UpscaleProvider>) -> Result<()> { self.register(id, Provider::Upscale(p)) }
+ pub(super) fn register_joint(&mut self, id: &str, p: Box<dyn JointProvider>) -> Result<()> { self.register(id, Provider::Joint(p)) }
+
+ pub(super) fn invalidate(&mut self) {
+ self.key = None;
+ self.fsr = None;
+ self.textures = None;
+ for (_, p) in &mut self.providers { p.invalidate(); }
+ }
+
+ pub(super) fn method(&self) -> Method {
+ match self.active {
+ Active::Builtin => Method::Builtin,
+ Active::Off => Method::Off,
+ Active::Fsr => Method::Fsr,
+ Active::Upscaler(i) | Active::Joint(i) => self.providers[i].0.clone(),
+ }
+ }
+
+ pub(super) fn status(&self) -> ReconstructionStatus {
+ let m = self.method();
+ let (denoise, upscale) = match self.active {
+ Active::Builtin => ("builtin".into(), "builtin".into()),
+ Active::Off => ("none".into(), "none".into()),
+ Active::Fsr | Active::Upscaler(_) => ("builtin".into(), m.name().into()),
+ Active::Joint(_) => (m.name().into(), m.name().into()),
+ };
+ ReconstructionStatus {
+ requested: self.requested.name(),
+ active: self.key.is_some().then(|| m.name().to_string()),
+ denoise, upscale,
+ fallback: (self.requested != Reconstruction::Auto).then(|| self.skipped.first().map(|s| s.1)).flatten(),
+ skipped: self.skipped.iter().map(|(m, s, d)| (m.name().to_string(), *s, d.clone())).collect(),
+ }
+ }
+
+ /// Resolve before tracing, so the trace's signals, denoising and jitter are this frame's. True if the
+ /// configuration changed (history is reset).
+ pub(super) fn prepare(&mut self, g: &gpu::Gpu, targets: &Targets, size: ReconstructionSize, diagnostic: bool) -> bool {
+ if self.key == Some((size, diagnostic)) { return false; }
+ self.key = Some((size, diagnostic));
+ let old = self.active;
+ self.skipped.clear();
+ self.active = if diagnostic {
+ if let Some(m) = self.requested.chain().into_iter().find(|m| *m != Method::Builtin) {
+ self.skipped.push((m, Skip::DiagnosticView, "a view mode shows ThreeRT's own buffers".into()));
+ }
+ Active::Builtin
+ } else {
+ self.select(g, targets, size)
+ };
+ self.active != old
+ }
+
+ fn select(&mut self, g: &gpu::Gpu, targets: &Targets, size: ReconstructionSize) -> Active {
+ for m in self.requested.chain() {
+ match self.try_method(g, targets, &m, size) {
+ Ok(active) => return active,
+ Err((skip, detail)) => {
+ if skip == Skip::ProviderError { eprintln!("live: {} reconstruction failed: {detail}", m.name()); }
+ self.skipped.push((m, skip, detail));
+ }
+ }
+ }
+ Active::Builtin
+ }
+
+ fn try_method(&mut self, g: &gpu::Gpu, targets: &Targets, m: &Method, size: ReconstructionSize) -> std::result::Result<Active, (Skip, String)> {
+ match m {
+ Method::Builtin => return Ok(Active::Builtin),
+ Method::Off => return Ok(Active::Off),
+ _ => {}
+ }
+ let limit = g.device.limits().max_texture_dimension_2d;
+ if size.output.into_iter().any(|side| side > limit) {
+ return Err((Skip::Unsupported, format!("the view is larger than this device's {limit}-pixel textures")));
+ }
+ if *m == Method::Fsr {
+ self.fsr.get_or_insert_with(|| fsr::Fsr::new(g, targets, size.output));
+ return Ok(Active::Fsr);
+ }
+ let Some(i) = self.providers.iter().position(|(k, _)| k == m) else {
+ return Err((Skip::Unavailable, match m {
+ Method::MetalFx | Method::MetalFxDenoised => "MetalFX runs on macOS only".into(),
+ Method::Dlss | Method::DlssRr => "this build has no DLSS (feature `dlss`, x86-64 Windows or Linux)".into(),
+ _ => format!("no provider is registered as {}", m.name()),
+ }));
+ };
+ match self.providers[i].1.prepare(g, size) {
+ Ok(Prepared::Ready { capacity }) => {
+ let joint = self.providers[i].1.joint();
+ self.prepare_textures(g, targets, joint, size, capacity);
+ Ok(if joint { Active::Joint(i) } else { Active::Upscaler(i) })
+ }
+ Ok(Prepared::Unsupported(why)) => Err((Skip::Unsupported, why)),
+ Err(e) => Err((Skip::ProviderError, format!("{e:#}"))),
+ }
+ }
+
+ fn prepare_textures(&mut self, g: &gpu::Gpu, targets: &Targets, joint: bool, size: ReconstructionSize, capacity: [u32; 2]) {
+ let capacity = [capacity[0].max(size.input[0]), capacity[1].max(size.input[1])];
+ if self.textures.as_ref().is_none_or(|t| t.key != (joint, capacity, size.output)) {
+ let pipes = self.pipes.get_or_insert_with(|| ProviderPipelines::new(g));
+ self.textures = Some(ProviderTextures::new(g, targets, pipes, joint, capacity, size.output));
+ }
+ }
+
+ /// GPU time (ms) the active provider spends outside the frame timer's passes.
+ pub(super) fn untimed_gpu_ms(&self) -> f32 {
+ match self.active {
+ Active::Upscaler(i) | Active::Joint(i) => self.providers[i].1.untimed_gpu_ms(),
+ _ => 0.0,
+ }
+ }
+
+ /// A provider failed while encoding: ThreeRT's own from this frame on (until the request or size changes).
+ fn provider_error(&mut self, e: &anyhow::Error) {
+ let m = self.method();
+ eprintln!("live: {} reconstruction failed: {e:#}; using builtin", m.name());
+ self.skipped.push((m, Skip::ProviderError, format!("{e:#}")));
+ self.active = Active::Builtin;
+ }
+
+ /// In place of the upscale stage. Returns the command buffers to submit before the rest of the frame when the
+ /// provider recorded native work.
+ pub(super) fn encode(&mut self, g: &gpu::Gpu, e: &mut CommandEncoder, size: ReconstructionSize,
+ cam: Camera, aspect: f32, jitter: (f32, f32), exposure: f32, reset: bool,
+ ) -> Result<Option<[CommandBuffer; 2]>> {
+ let i = match self.active {
+ Active::Builtin | Active::Off => return Ok(None),
+ Active::Fsr => { self.fsr.as_ref().unwrap().encode(e); return Ok(None); }
+ Active::Upscaler(i) | Active::Joint(i) => i,
+ };
+ let textures = self.textures.as_mut().expect("prepared reconstruction textures");
+ let pipes = self.pipes.as_ref().unwrap();
+ textures.pack(e, pipes, size.input);
+ let unit = if textures.key.0 { 1.0 } else { 32.0 } / exposure.clamp(0.00001, 64.0);
+ let world_to_view = glam::Mat4::look_to_rh(cam.pos, cam.fwd, cam.up).to_cols_array();
+ let view_to_clip = glam::Mat4::perspective_infinite_reverse_rh(2.0 * cam.tan_half_fov.atan(), aspect, 0.01).to_cols_array();
+ let [color, depth, motion, reactive, ..] = &textures.inputs[..] else { unreachable!() };
+ let frame = ReconstructionFrame {
+ gpu: g, size, color, depth, motion, reactive, output: &textures.output, radiance_unit: unit,
+ jitter: [jitter.0 - 0.5, jitter.1 - 0.5], reset: reset || textures.fresh || textures.exposure != exposure,
+ camera: cam, aspect, world_to_view, view_to_clip,
+ };
+ let dispatch = match &mut self.providers[i].1 {
+ Provider::Upscale(p) => p.encode(frame, e),
+ Provider::Joint(p) => {
+ let [_, _, _, _, overlay, bypass, diffuse_albedo, specular_albedo, normal, roughness, specular_hit_distance] = &textures.inputs[..] else { unreachable!() };
+ p.encode(frame, JointGuides { overlay, bypass, diffuse_albedo, specular_albedo, normal, roughness, specular_hit_distance }, e)
+ }
+ };
+ let native = match dispatch {
+ Ok(cb) => cb,
+ Err(err) => { self.provider_error(&err); return Err(err); }
+ };
+ let before_post = native.map(|native| [std::mem::replace(e, g.device.create_command_encoder(&Default::default())).finish(), native]);
+ textures.fresh = false;
+ textures.exposure = exposure;
+ let mut pass = e.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("reconstruction to post"), ..Default::default() });
+ pass.set_pipeline(&pipes.output);
+ pass.set_bind_group(0, &textures.post_group, &[]);
+ pass.set_bind_group(1, &textures.output_group, &[]);
+ pass.dispatch_workgroups(size.output[0].div_ceil(8), size.output[1].div_ceil(8), 1);
+ Ok(before_post)
+ }
+}
+
+use wgpu::TextureFormat::*;
+/// [`ReconstructionFrame`]'s inputs, then [`JointGuides`]' (shaders/reconstruction.wgsl `rc_*_inputs`, `rc_guides`).
+const SIGNALS: [wgpu::TextureFormat; 4] = [Rgba16Float, R32Float, Rg16Float, R8Unorm];
+const JOINT_LAYERS: [wgpu::TextureFormat; 2] = [Rgba16Float, R8Unorm];
+const GUIDES: [wgpu::TextureFormat; 5] = [Rgba8Unorm, Rgba8Unorm, Rgba16Float, R16Float, R16Float];
+
+struct ProviderPipelines {
+ upscale_inputs: wgpu::RenderPipeline,
+ joint_inputs: wgpu::RenderPipeline,
+ guides: wgpu::RenderPipeline,
+ output: wgpu::ComputePipeline,
+}
+
+impl ProviderPipelines {
+ fn new(g: &gpu::Gpu) -> Self {
+ let d = &g.device;
+ let module = d.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("reconstruction signals"),
+ source: wgpu::ShaderSource::Wgsl([targets::live_source(), include_str!("../../shaders/reconstruction.wgsl")].concat().into()),
+ });
+ let render = |entry: &str, formats: &[wgpu::TextureFormat]| {
+ let targets: Vec<_> = formats.iter().map(|f| Some((*f).into())).collect();
+ d.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(entry), layout: None,
+ vertex: wgpu::VertexState { module: &module, entry_point: Some("rc_vertex"), buffers: &[], compilation_options: Default::default() },
+ fragment: Some(wgpu::FragmentState { module: &module, entry_point: Some(entry), compilation_options: Default::default(), targets: &targets }),
+ primitive: Default::default(), depth_stencil: None, multisample: Default::default(), multiview_mask: None, cache: g.cache(),
+ })
+ };
+ let output = d.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("reconstruction output"), layout: None, module: &module,
+ entry_point: Some("rc_output_to_post"), compilation_options: Default::default(), cache: g.cache(),
+ });
+ Self {
+ upscale_inputs: render("rc_upscale_inputs", &SIGNALS),
+ joint_inputs: render("rc_joint_inputs", &[&SIGNALS[..], &JOINT_LAYERS].concat()),
+ guides: render("rc_guides", &GUIDES),
+ output,
+ }
+ }
+}
+
+struct ProviderTextures {
+ /// Joint, input capacity, output size.
+ key: (bool, [u32; 2], [u32; 2]),
+ /// SIGNALS, then (joint) JOINT_LAYERS and GUIDES.
+ inputs: Vec<TextureView>,
+ output: TextureView,
+ input_group: wgpu::BindGroup,
+ guide_group: Option<wgpu::BindGroup>,
+ post_group: wgpu::BindGroup,
+ output_group: wgpu::BindGroup,
+ fresh: bool,
+ exposure: f32,
+}
+
+impl ProviderTextures {
+ fn new(g: &gpu::Gpu, targets: &Targets, pipes: &ProviderPipelines, joint: bool, capacity: [u32; 2], output_size: [u32; 2]) -> Self {
+ use wgpu::TextureUsages as Usage;
+ let d = &g.device;
+ let view = |label, format, [width, height]: [u32; 2], extra| d.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label), format,
+ size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
+ mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2,
+ usage: Usage::RENDER_ATTACHMENT | Usage::TEXTURE_BINDING | extra, view_formats: &[],
+ }).create_view(&Default::default());
+ let formats: Vec<_> = if joint { [&SIGNALS[..], &JOINT_LAYERS, &GUIDES].concat() } else { SIGNALS.to_vec() };
+ let inputs = formats.into_iter().map(|f| view("reconstruction input", f, capacity, Usage::empty())).collect();
+ let output = view("reconstruction HDR", Rgba16Float, output_size, Usage::STORAGE_BINDING | Usage::COPY_DST);
+ let bind = |layout: wgpu::BindGroupLayout, names: &[&str]| {
+ let entries: Vec<_> = names.iter().map(|&n| wgpu::BindGroupEntry {
+ binding: super::layout::binding(n).binding,
+ resource: match n {
+ "L" => targets.params.as_entire_binding(),
+ "sample_px" => targets.accum.as_entire_binding(),
+ _ => targets.buf(n).binding(),
+ },
+ }).collect();
+ d.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("reconstruction signals"), layout: &layout, entries: &entries })
+ };
+ let input_group = if joint {
+ bind(pipes.joint_inputs.get_bind_group_layout(0), &["L", "fb", "sample_px", "sample_vel"])
+ } else {
+ bind(pipes.upscale_inputs.get_bind_group_layout(0), &["L", "fb", "sample_vel"])
+ };
+ let guide_group = joint.then(|| bind(pipes.guides.get_bind_group_layout(0), &["L", "sample_px", "refl_in"]));
+ let post_group = bind(pipes.output.get_bind_group_layout(0), &["L", "fa", "sb", "sample_vel"]);
+ let output_group = d.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("reconstruction HDR"), layout: &pipes.output.get_bind_group_layout(1),
+ entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&output) }],
+ });
+ Self { key: (joint, capacity, output_size), inputs, output, input_group, guide_group, post_group, output_group, fresh: true, exposure: 0.0 }
+ }
+
+ /// The signals, into the top-left `input` of the textures.
+ fn pack(&self, e: &mut CommandEncoder, pipes: &ProviderPipelines, input: [u32; 2]) {
+ fn attachment(view: &TextureView) -> Option<wgpu::RenderPassColorAttachment<'_>> {
+ Some(wgpu::RenderPassColorAttachment {
+ view, depth_slice: None, resolve_target: None,
+ ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
+ })
+ }
+ if self.fresh {
+ // Initialize before a native writer, so wgpu doesn't clear its output on the first read.
+ drop(e.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("reconstruction output init"), color_attachments: &[attachment(&self.output)], ..Default::default()
+ }));
+ }
+ let mut draw = |views: &[TextureView], pipe: &wgpu::RenderPipeline, group: &wgpu::BindGroup| {
+ let attachments: Vec<_> = views.iter().map(attachment).collect();
+ let mut pass = e.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("reconstruction inputs"), color_attachments: &attachments, ..Default::default()
+ });
+ pass.set_scissor_rect(0, 0, input[0], input[1]);
+ pass.set_viewport(0.0, 0.0, input[0] as f32, input[1] as f32, 0.0, 1.0);
+ pass.set_pipeline(pipe);
+ pass.set_bind_group(0, group, &[]);
+ pass.draw(0..3, 0..1);
+ };
+ match &self.guide_group {
+ Some(guides) => {
+ let (base, rest) = self.inputs.split_at(SIGNALS.len() + JOINT_LAYERS.len());
+ draw(base, &pipes.joint_inputs, &self.input_group);
+ draw(rest, &pipes.guides, guides);
+ }
+ None => draw(&self.inputs, &pipes.upscale_inputs, &self.input_group),
+ }
+ }
+}
diff --git a/renderer/src/live/rendering.rs b/renderer/src/live/rendering.rs
new file mode 100644
index 0000000..a84ac41
--- /dev/null
+++ b/renderer/src/live/rendering.rs
@@ -0,0 +1,262 @@
+//! The live view's rendering settings, by the gap each one closes between what a frame can afford and what is shown:
+//!
+//! | setting | the gap | ThreeRT's own | vendor technology |
+//! |---|---|---|---|
+//! | `quality` | how many rays: the render resolution (the input every stage below works from) | dynamic resolution | (none: a budget, not a technique) |
+//! | `reconstruction` | noise and pixels (live/reconstruction.rs) | denoiser + temporal upscaler | DLSS SR / RR, MetalFX, FSR, XeSS |
+//! | `frameGeneration` | frames: more shown than rendered | none | DLSS FG, FSR FG, XeSS FG, MetalFX frame interpolation |
+//! | `latency` | input to photon | at most one frame queued | Reflex, Anti-Lag 2, XeLL |
+//!
+//! Each is a request ("what I want"), resolved each frame against the device to what runs, and read back as a
+//! status: a request this device cannot run is not an error, and is never silent. Neural techniques are not a
+//! setting of their own: a neural denoiser or upscaler is a reconstruction method; a neural radiance cache would be
+//! a lighting option and neural texture compression an asset format.
+//!
+//! These are device-local view settings (a player's graphics options, a host's default), not scene state: a game
+//! may request them (`rendering.set` in @threert/scene), the viewer's flags and keys override them.
+use super::{Method, Reconstruction, ReconstructionStatus, Result};
+use std::sync::{Arc, Mutex};
+
+/// The render resolution, as a fraction of the output's side.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Quality {
+ /// Dynamic resolution: the governor keeps the frame within its time.
+ Auto,
+ /// 1: every output pixel traced (reconstruction is anti-aliasing: DLAA, MetalFX at 1x).
+ Native,
+ /// 2/3.
+ Quality,
+ /// 0.58.
+ Balanced,
+ /// 1/2.
+ Performance,
+ /// 1/3.
+ UltraPerformance,
+ /// A fraction of its own (0.25 ..= 1).
+ Scale(f32),
+}
+
+impl Quality {
+ pub fn parse(s: &str) -> Result<Self> {
+ Ok(match s.trim() {
+ "auto" | "dynamic" => Self::Auto,
+ "native" => Self::Native,
+ "quality" => Self::Quality,
+ "balanced" => Self::Balanced,
+ "performance" => Self::Performance,
+ "ultra-performance" => Self::UltraPerformance,
+ s => match s.parse::<f32>() {
+ Ok(v) if v > 0.0 && v <= 1.0 => Self::Scale(v),
+ Ok(v) if v == 0.0 => Self::Auto,
+ _ => anyhow::bail!("unknown quality '{s}'; use auto, native, quality, balanced, performance, ultra-performance or a scale in (0, 1]"),
+ },
+ })
+ }
+
+ pub fn from_json(v: &serde_json::Value) -> Result<Self> {
+ match v {
+ serde_json::Value::String(s) => Self::parse(s),
+ serde_json::Value::Number(n) => Self::parse(&n.to_string()),
+ _ => anyhow::bail!("quality is a name or a scale"),
+ }
+ }
+
+ pub fn name(&self) -> String {
+ match self {
+ Self::Auto => "auto".into(),
+ Self::Native => "native".into(),
+ Self::Quality => "quality".into(),
+ Self::Balanced => "balanced".into(),
+ Self::Performance => "performance".into(),
+ Self::UltraPerformance => "ultra-performance".into(),
+ Self::Scale(s) => format!("{s}"),
+ }
+ }
+
+ /// The render scale, or None for dynamic resolution. (The presets are the vendors' ratios exactly: a third of
+ /// 1920 is 640, the smallest input DLSS takes for 1080p, where a typed 0.333 gives 639.)
+ pub fn scale(&self) -> Option<f32> {
+ match self {
+ Self::Auto => None,
+ Self::Native => Some(1.0),
+ Self::Quality => Some(2.0 / 3.0),
+ Self::Balanced => Some(0.58),
+ Self::Performance => Some(0.5),
+ Self::UltraPerformance => Some(1.0 / 3.0),
+ Self::Scale(s) => Some(*s),
+ }
+ }
+}
+
+/// Frames shown per frame rendered. No provider is integrated yet: a request other than `off` reports itself
+/// unavailable and the view shows each rendered frame once.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FrameGeneration {
+ Off,
+ /// What the device does best (nothing yet).
+ Auto,
+ /// 2 to 4 frames shown per frame rendered.
+ Multiply(u8),
+}
+
+impl FrameGeneration {
+ pub fn parse(s: &str) -> Result<Self> {
+ Ok(match s.trim() {
+ "off" => Self::Off,
+ "auto" => Self::Auto,
+ "2x" => Self::Multiply(2),
+ "3x" => Self::Multiply(3),
+ "4x" => Self::Multiply(4),
+ s => anyhow::bail!("unknown frame generation '{s}'; use off, auto, 2x, 3x or 4x"),
+ })
+ }
+
+ pub fn name(&self) -> String {
+ match self { Self::Off => "off".into(), Self::Auto => "auto".into(), Self::Multiply(n) => format!("{n}x") }
+ }
+}
+
+/// How far the CPU may run ahead of the GPU.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Latency {
+ /// Two frames queued (throughput first).
+ Off,
+ /// `on` while frames are generated (a generated frame needs it), else `off`.
+ Auto,
+ /// One frame queued: the next frame's input is read as late as the GPU allows.
+ On,
+}
+
+impl Latency {
+ pub fn parse(s: &str) -> Result<Self> {
+ Ok(match s.trim() {
+ "off" => Self::Off,
+ "auto" => Self::Auto,
+ "on" => Self::On,
+ s => anyhow::bail!("unknown latency '{s}'; use off, auto or on"),
+ })
+ }
+
+ pub fn name(&self) -> &'static str {
+ match self { Self::Off => "off", Self::Auto => "auto", Self::On => "on" }
+ }
+}
+
+/// A request: each field set is changed, each left out kept.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct RenderingRequest {
+ pub quality: Option<Quality>,
+ pub reconstruction: Option<Reconstruction>,
+ pub frame_generation: Option<FrameGeneration>,
+ pub latency: Option<Latency>,
+}
+
+impl RenderingRequest {
+ /// `{"quality": "performance", "reconstruction": ["metalfx-denoised", "builtin"], "frameGeneration": "off",
+ /// "latency": "auto"}`, any of them.
+ pub fn from_json(v: &serde_json::Value) -> Result<Self> {
+ let o = v.as_object().ok_or_else(|| anyhow::anyhow!("rendering settings are an object"))?;
+ let str_of = |k: &str| o.get(k).map(|v| v.as_str().ok_or_else(|| anyhow::anyhow!("{k} is a string")));
+ for k in o.keys() {
+ anyhow::ensure!(matches!(k.as_str(), "quality" | "reconstruction" | "frameGeneration" | "latency" | "cmd"),
+ "unknown rendering setting '{k}'; use quality, reconstruction, frameGeneration or latency");
+ }
+ Ok(Self {
+ quality: o.get("quality").map(Quality::from_json).transpose()?,
+ reconstruction: o.get("reconstruction").map(Reconstruction::from_json).transpose()?,
+ frame_generation: str_of("frameGeneration").transpose()?.map(FrameGeneration::parse).transpose()?,
+ latency: str_of("latency").transpose()?.map(Latency::parse).transpose()?,
+ })
+ }
+
+ fn merge(&mut self, r: RenderingRequest) {
+ if r.quality.is_some() { self.quality = r.quality; }
+ if r.reconstruction.is_some() { self.reconstruction = r.reconstruction; }
+ if r.frame_generation.is_some() { self.frame_generation = r.frame_generation; }
+ if r.latency.is_some() { self.latency = r.latency; }
+ }
+}
+
+/// The settings as requested and as they ran (the last frame).
+#[derive(Clone, Debug)]
+pub struct RenderingStatus {
+ pub quality: Quality,
+ /// The render scale the last frame ran at, and whether the governor sets it.
+ pub scale: f32,
+ pub dynamic: bool,
+ pub reconstruction: ReconstructionStatus,
+ pub frame_generation: FrameGeneration,
+ pub latency: Latency,
+ pub frames_in_flight: u32,
+}
+
+impl RenderingStatus {
+ pub fn json(&self) -> serde_json::Value {
+ serde_json::json!({
+ "quality": { "requested": self.quality.name(), "scale": self.scale, "dynamic": self.dynamic },
+ "reconstruction": self.reconstruction.json(),
+ "frameGeneration": {
+ "requested": self.frame_generation.name(), "active": "off",
+ "fallback": matches!(self.frame_generation, FrameGeneration::Multiply(_)).then_some("unavailable"),
+ },
+ "latency": {
+ "requested": self.latency.name(), "active": if self.frames_in_flight == 1 { "on" } else { "off" },
+ "framesInFlight": self.frames_in_flight,
+ },
+ })
+ }
+}
+
+#[derive(Default)]
+struct ControlState {
+ pending: Option<RenderingRequest>,
+ status: Option<RenderingStatus>,
+}
+
+/// Settings shared with a game runtime or a browser page: requests queue for the next frame, the status is the last
+/// frame's. Requests made before the view's first frame apply to it.
+#[derive(Clone, Default)]
+pub struct RenderingControl(Arc<Mutex<ControlState>>);
+
+impl RenderingControl {
+ pub fn request(&self, r: RenderingRequest) {
+ let mut s = self.0.lock().unwrap();
+ s.pending.get_or_insert_with(Default::default).merge(r);
+ }
+
+ pub(super) fn take(&self) -> Option<RenderingRequest> { self.0.lock().unwrap().pending.take() }
+
+ pub(super) fn publish(&self, status: RenderingStatus) { self.0.lock().unwrap().status = Some(status); }
+
+ /// The last frame's settings, with requests not yet applied shown as requested. Null before the first frame.
+ pub fn status(&self) -> serde_json::Value {
+ let s = self.0.lock().unwrap();
+ let Some(mut st) = s.status.clone() else { return serde_json::Value::Null };
+ if let Some(p) = &s.pending {
+ if let Some(q) = p.quality { st.quality = q; }
+ if let Some(r) = &p.reconstruction { st.reconstruction.requested = r.name(); }
+ if let Some(f) = p.frame_generation { st.frame_generation = f; }
+ if let Some(l) = p.latency { st.latency = l; }
+ }
+ st.json()
+ }
+}
+
+/// The viewer's key: the next of this platform's methods after `m`.
+pub fn next_method(m: &Method) -> Method {
+ let all = Method::platform();
+ let i = all.iter().position(|k| k == m).map_or(0, |i| (i + 1) % all.len());
+ all[i].clone()
+}
+
+impl RenderingRequest {
+ /// `--quality`, `--reconstruction`, `--frame-generation`, `--latency` (`flag` returns a flag's value).
+ pub fn from_flags(flag: impl Fn(&str) -> Option<String>) -> Result<Self> {
+ Ok(Self {
+ quality: flag("--quality").map(|v| Quality::parse(&v)).transpose()?,
+ reconstruction: flag("--reconstruction").map(|v| Reconstruction::parse(&v)).transpose()?,
+ frame_generation: flag("--frame-generation").map(|v| FrameGeneration::parse(&v)).transpose()?,
+ latency: flag("--latency").map(|v| Latency::parse(&v)).transpose()?,
+ })
+ }
+}
diff --git a/renderer/src/live/session.rs b/renderer/src/live/session.rs
index a54e66e..0949131 100644
--- a/renderer/src/live/session.rs
+++ b/renderer/src/live/session.rs
@@ -21,6 +21,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
let (mut fs_sum, mut fs_max, mut fs_n) = (0.0f32, 0.0f32, 0u32);
core.bounces = opts.bounces;
core.set_scale(opts.scale.unwrap_or(0.0));
+ core.set_rendering(opts.rendering.clone());
core.set_display_scale(opts.display_scale);
eprintln!("live: load {}", serde_json::Value::Object(core.load_timings().iter().map(|(k, v)| (k.clone(), (*v).into())).collect()));
eprintln!("live: {}x{} @{} fps on {} ({})", core.w, core.h, opts.fps, core.g.adapter_info.name, if core.g.hwrt { "HW RT" } else { "BVH" });
@@ -79,6 +80,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
Cmd::Time(t) => core.set_time(t),
Cmd::Mode(m) => core.view_mode = m,
Cmd::Bounces(b) => core.bounces = b,
+ Cmd::Rendering(r) => core.set_rendering(r),
Cmd::Scale(s) => core.set_scale(s),
Cmd::Resize(w, h) => {
let t = Instant::now();
@@ -179,7 +181,7 @@ pub fn run(presets: &Path, opts: LiveOpts) -> Result<()> {
use std::io::Write;
let line = serde_json::json!({
"t": start.elapsed().as_secs_f64() * 1e3, "interval": last_frame.elapsed().as_secs_f64() * 1e3, "start": t_frame.duration_since(prev_start).as_secs_f64() * 1e3,
- "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "build": core.build_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "top": core.top_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved, "kicks": s.kicks }) }), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
+ "cpu": t_frame.elapsed().as_secs_f64() * 1e3, "script": game.frame_ms, "js": game.js_ms, "commit": game.commit_ms, "skin": core.cpu_skin_ms, "upload": core.cpu_upload_ms, "blas": core.gpu_blas_ms, "wait": core.cpu_wait_ms, "gpu": core.gpu_ms, "trace": core.gpu_trace_ms, "edit": core.edit_ms, "instanced": core.instanced_ms, "build": core.build_ms, "edit_split": [core.edit_split.tris, core.edit_split.upload, core.edit_split.blas, core.edit_split.added, core.edit_split.deformed, core.edit_split.objects], "rebuild": core.rebuild_ms, "fallback": core.fallback, "fallbacks": core.fallbacks, "room": core.room_stats(), "top": core.top_stats(), "voxel": std::mem::take(&mut game.host.voxels.borrow_mut().ticks), "physics": game.host.physics.borrow_mut().as_mut().map(|p| { let s = p.take_stats(); serde_json::json!({ "ticks": s.ticks, "step": s.step_ms, "sync": s.sync_ms, "bodies": s.bodies, "moved": s.moved, "kicks": s.kicks }) }), "reconstruction": core.reconstruction().name(), "reconstruction_fallback": core.reconstruction_status().fallback.map(Skip::name), "scale": core.render_scale, "history": core.history_len, "guard": core.guard_count(),
});
writeln!(l, "{line}")?;
}
@@ -285,6 +287,10 @@ pub fn parse_cmd(line: &str) -> Option<Cmd> {
"mode" => Cmd::Mode(v["mode"].as_u64()? as u32),
"bounces" => Cmd::Bounces(v["bounces"].as_u64()?.clamp(1, 16) as u32),
"spp" => Cmd::SppCap(v["max"].as_u64()?.clamp(1, 16) as u32),
+ // `{"cmd":"rendering","reconstruction":["metalfx-denoised","builtin"],"quality":"performance"}`; the older
+ // `{"cmd":"reconstruction","mode":"fsr"}` is the same with one setting.
+ "rendering" => Cmd::Rendering(RenderingRequest::from_json(&v).map_err(|e| eprintln!("live: {e:#}")).ok()?),
+ "reconstruction" => Cmd::Rendering(RenderingRequest { reconstruction: Some(Reconstruction::from_json(&v["mode"]).map_err(|e| eprintln!("live: {e:#}")).ok()?), ..Default::default() }),
"scale" => Cmd::Scale(v["scale"].as_f64()? as f32),
"resize" => Cmd::Resize(v["width"].as_u64()? as u32, v["height"].as_u64()? as u32),
"sync" => Cmd::Sync(v["id"].as_str().map(str::to_string).unwrap_or_else(|| v["id"].to_string()), v["frames"].as_u64().unwrap_or(1) as u32),
@@ -297,6 +303,7 @@ pub fn parse_opts(args: &[String]) -> Result<LiveOpts> {
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let num = |name: &str, d: u32| -> Result<u32> { flag(name).map(|v| v.parse().map_err(|_| anyhow!("{name} must be a number"))).transpose().map(|v| v.unwrap_or(d)) };
Ok(LiveOpts {
+ rendering: RenderingRequest::from_flags(&flag)?,
width: num("--width", 1280)?,
height: num("--height", 720)?,
fps: num("--fps", 60)?,
diff --git a/renderer/src/main.rs b/renderer/src/main.rs
index 65ad9e1..d8d125c 100644
--- a/renderer/src/main.rs
+++ b/renderer/src/main.rs
@@ -41,6 +41,9 @@ struct Job {
hdr: Option<PathBuf>,
/// A live job's approximations (`gpu::A_*` bits; None: the device's).
approx: Option<u32>,
+ reconstruction: Option<live::Reconstruction>,
+ /// Fixed internal resolution for a live job, as a fraction of its output size.
+ scale: Option<f32>,
/// `--signals PREFIX`: PREFIX-diffuse.raw / -specular.raw / -emission.raw, the image's linear signals apart as the
/// live denoiser splits them (RGB f32, output size; live snapshots to `*.signals` write the same).
signals: Option<PathBuf>,
@@ -179,6 +182,8 @@ fn main() -> Result<()> {
size: (flag("--width").map(|s| s.parse()).transpose()?, flag("--height").map(|s| s.parse()).transpose()?),
hdr: flag("--hdr").map(PathBuf::from),
approx: None,
+ reconstruction: None,
+ scale: None,
signals: flag("--signals").map(PathBuf::from),
};
let stats = render(&g, &job, &presets, init_ms, &mut Hosts::default())?;
@@ -309,7 +314,7 @@ fn main() -> Result<()> {
"serve" => {
// One job per stdin line: {id, game: bundle path (or game module + runtime: runtime module), assets, room,
// seed, state?, seq?, out, spp?, denoise?, overrides?, camera?, preset?, width?, height?, time?, hdr? (raw f32
- // RGB linear radiance, nits), live? (frames of the real-time renderer instead, `render_live`), approx? (a
+ // RGB linear radiance, nits), live? (frames of the real-time renderer, with optional scale and reconstruction), approx? (a
// live job's approximations, `gpu::A_*` bits; the device's without)}; one result line
// each: {id, ok, stats} or
// {id, ok: false, error, missing?: [files to put under the asset root before retrying]}.
@@ -340,6 +345,8 @@ fn main() -> Result<()> {
time: v["time"].as_f64().map(|t| t as f32),
size: (v["width"].as_u64().map(|x| x as u32), v["height"].as_u64().map(|x| x as u32)),
hdr: v["hdr"].as_str().map(PathBuf::from),
+ reconstruction: v.get("reconstruction").filter(|r| !r.is_null()).map(live::Reconstruction::from_json).transpose()?,
+ scale: v["scale"].as_f64().map(|s| s as f32),
approx: v["approx"].as_u64().map(|x| x as u32),
signals: v["signals"].as_str().map(PathBuf::from),
};
@@ -368,7 +375,7 @@ fn main() -> Result<()> {
/// A `serve` job with `live: frames`: the real-time renderer (radiance cache, temporal and denoising passes) runs that
-/// many frames at 100 % scale on the scene's camera, the game's frame script (if any) before each at 60 fps; `hdr` gets
+/// many frames at the job's scale on the scene's camera, the game's frame script (if any) before each at 60 fps; `hdr` gets
/// its linear radiance, `out` the displayed image.
fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u32, hosts: &mut Hosts) -> Result<serde_json::Value> {
let t0 = Instant::now();
@@ -395,7 +402,9 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u
};
g.set_approx(job.approx);
let mut core = live::LiveCore::new(g, &w, &job.game.assets, presets, width, height)?;
- core.set_scale(1.0);
+ host.attach_rendering(&mut core);
+ if let Some(mode) = &job.reconstruction { core.set_reconstruction(mode.clone()); }
+ core.set_scale(job.scale.unwrap_or(1.0));
drop(w);
// A frame script runs at 60 fps: the renderer's frame time is the same (motion blur, exposure adaptation).
if host.has_frame() {
@@ -423,8 +432,13 @@ fn render_live(slot: &mut Option<gpu::Gpu>, job: &Job, presets: &Path, frames: u
}
let ev100 = core.read_ev100()?;
let ms = t0.elapsed().as_secs_f64() * 1000.0;
+ let info = serde_json::json!({
+ "width": width, "height": height, "frames": frames, "scale": core.render_scale,
+ "reconstruction": core.reconstruction().name(), "requested_reconstruction": core.requested_reconstruction().name(),
+ "ev100": ev100, "timings_ms": { "total_ms": ms }
+ });
*slot = Some(core.g);
- Ok(serde_json::json!({ "width": width, "height": height, "frames": frames, "ev100": ev100, "timings_ms": { "total_ms": ms } }))
+ Ok(info)
}
/// PREFIX-diffuse.raw, -specular.raw, -emission.raw (RGB f32 each).
diff --git a/renderer/src/script.rs b/renderer/src/script.rs
index 47e07f7..9b04e26 100644
--- a/renderer/src/script.rs
+++ b/renderer/src/script.rs
@@ -234,6 +234,7 @@ pub struct ScriptHost {
pub voxels: Rc<RefCell<crate::voxel::VoxelWorld>>,
/// The physics world (`__engine.physics`; renderer/src/physics.rs): None until scene code makes a physics call.
pub physics: Rc<RefCell<Option<crate::physics::PhysicsWorld>>>,
+ rendering: crate::live::RenderingControl,
/// What the game posted for the app (`host.post`: JSON texts), until `take_posts`.
posts: Rc<RefCell<Vec<String>>>,
/// The promises rejected with no handler in the entry running now (`Rejected`); empty between entries.
@@ -303,9 +304,19 @@ fn thrown(ctx: &Ctx, e: crate::api::Error) -> rquickjs::Error {
/// The engine API (`globalThis.__engine`), see packages/scene/src/engine.ts: each call's arguments out of QuickJS,
/// then what the call does (api.rs: the same code a browser's exports run, renderer/web).
-fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>, physics: &Rc<RefCell<Option<crate::physics::PhysicsWorld>>>, budget: &Arc<Budget>) -> rquickjs::Result<()> {
+fn install_engine<'js>(ctx: &Ctx<'js>, world: &Rc<RefCell<World>>, voxels: &Rc<RefCell<crate::voxel::VoxelWorld>>, physics: &Rc<RefCell<Option<crate::physics::PhysicsWorld>>>, budget: &Arc<Budget>, rendering: &crate::live::RenderingControl) -> rquickjs::Result<()> {
use crate::api;
let e = Object::new(ctx.clone())?;
+ // Rendering settings (live/rendering.rs): a request as JSON, applied from the next frame; the last frame's status.
+ let control = rendering.clone();
+ e.set("setRendering", Function::new(ctx.clone(), move |ctx: Ctx, json: String| -> rquickjs::Result<()> {
+ let r = serde_json::from_str(&json).map_err(anyhow::Error::from).and_then(|v| crate::live::RenderingRequest::from_json(&v))
+ .map_err(|e| Exception::throw_type(&ctx, &format!("{e:#}")))?;
+ control.request(r);
+ Ok(())
+ })?)?;
+ let control = rendering.clone();
+ e.set("renderingStatus", Function::new(ctx.clone(), move || control.status().to_string())?)?;
// Physics (renderer/src/physics.rs): one call, `physics(op, args)`, answering in JSON. The world is made by the
// first call; the engine steps it, scene code cannot.
let (p, w) = (physics.clone(), world.clone());
@@ -490,7 +501,7 @@ impl ScriptHost {
let ctx = Context::full(&rt)?;
let world = Rc::new(RefCell::new(World::default()));
let voxels = Rc::new(RefCell::new(crate::voxel::VoxelWorld::default()));
- let mut h = ScriptHost { rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default(), posts: Default::default(), rejected };
+ let mut h = ScriptHost { rt, ctx, budget, epoch, info: serde_json::Value::Null, world, voxels, physics: Default::default(), rendering: Default::default(), posts: Default::default(), rejected };
let (w, v, ph, d2, posts) = (h.world.clone(), h.voxels.clone(), h.physics.clone(), h.budget.clone(), h.posts.clone());
let (info, rejections) = h.enter(SETUP_MS, |ctx| {
let g = ctx.globals();
@@ -514,7 +525,7 @@ impl ScriptHost {
// tens of megabytes that the script would take seconds over. packages/gameplay/src/files.ts uses them.
g.set("__host_base64_encode", Function::new(ctx.clone(), base64_encode)?)?;
g.set("__host_base64_decode", Function::new(ctx.clone(), base64_decode)?)?;
- install_engine(ctx, &w, &v, &ph, &d2)?;
+ install_engine(ctx, &w, &v, &ph, &d2, &h.rendering)?;
ctx.eval::<(), _>(PRELUDE)?;
code(ctx)?;
host(ctx)?.get::<_, Function>("describe")?.call::<_, String>(())
@@ -538,6 +549,10 @@ impl ScriptHost {
r
}
+ pub fn attach_rendering(&self, core: &mut crate::live::LiveCore) {
+ core.attach_rendering_control(self.rendering.clone());
+ }
+
/// One entry into the script: `f` under a time budget, then the promise jobs the entry left (`run_jobs`), within
/// the same budget, whether `f` threw or not. Returns `f`'s result (its own error first, else the jobs': the entry
/// fails when its time is up with jobs still to run, as it does when `f` overruns) and the entry's unhandled
@@ -841,7 +856,8 @@ impl GameSession {
/// Opens the first live view of a loaded session (`load_code`).
pub fn start_loaded(self, assets: &std::path::Path, g: crate::gpu::Gpu, presets: &std::path::Path, w: u32, h: u32) -> Result<(GameSession, crate::live::LiveCore)> {
self.realize_voxels(assets)?;
- let core = crate::live::LiveCore::new(g, &self.host.world.borrow(), assets, presets, w, h)?;
+ let mut core = crate::live::LiveCore::new(g, &self.host.world.borrow(), assets, presets, w, h)?;
+ self.host.attach_rendering(&mut core);
Ok((self, core))
}
@@ -849,6 +865,7 @@ impl GameSession {
pub fn open_loaded(self, assets: &std::path::Path, core: &mut crate::live::LiveCore) -> Result<GameSession> {
self.realize_voxels(assets)?;
core.open(&self.host.world.borrow(), assets)?;
+ self.host.attach_rendering(core);
core.seq = 0;
Ok(self)
}
diff --git a/renderer/src/view.rs b/renderer/src/view.rs
index 12d5be9..66ec8ac 100644
--- a/renderer/src/view.rs
+++ b/renderer/src/view.rs
@@ -44,6 +44,8 @@ use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
use winit::window::{CursorGrabMode, Window, WindowId};
pub struct ViewArgs {
+ /// `--quality`, `--reconstruction`, `--frame-generation`, `--latency` (live/rendering.rs).
+ pub rendering: crate::live::RenderingRequest,
/// Game bundle to run in-process.
pub bundle: PathBuf,
/// Asset root the scene's model / texture paths resolve against.
@@ -236,6 +238,7 @@ impl App {
}
core.bounces = a.bounces;
core.set_scale(a.scale.unwrap_or(0.0));
+ core.set_rendering(a.rendering.clone());
core.set_display_scale(window.scale_factor() as f32);
let d = &core.g.device;
let module = d.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("blit"), source: wgpu::ShaderSource::Wgsl(BLIT.into()) });
@@ -444,6 +447,19 @@ impl ApplicationHandler for App {
"Escape" => el.exit(),
"R" => s.orbit = s.home,
"P" => s.snapshot = Some(PathBuf::from(format!("view-{}.png", s.core.frame))),
+ // Reconstruction (live/rendering.rs): M between ThreeRT's own and the best this device
+ // has (`auto`: MetalFX's joint denoiser on a Mac, DLSS on an RTX GPU), N through every method.
+ "M" | "N" => {
+ let next: crate::live::Reconstruction = if name == "N" {
+ crate::live::next_method(&s.core.reconstruction()).into()
+ } else if s.core.reconstruction() == crate::live::Method::Builtin {
+ crate::live::Reconstruction::Auto
+ } else {
+ crate::live::Method::Builtin.into()
+ };
+ eprintln!("view: reconstruction {}", next.name());
+ s.core.set_reconstruction(next);
+ }
"0" => s.spp_cap = 16,
"1" | "2" | "4" | "8" => s.spp_cap = name.parse().unwrap(),
// F1..F6 style view modes on the number row with Alt held
@@ -593,6 +609,7 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServi
s.core.bounces = b;
}
Cmd::SppCap(n) => s.spp_cap = n,
+ Cmd::Rendering(r) => s.core.set_rendering(r),
Cmd::Scale(v) => s.core.set_scale(v),
Cmd::Resize(w, h) => {
// The window's size; the view follows it (`fit`).
@@ -733,10 +750,12 @@ fn frame(s: &mut State, cmds: &mpsc::Receiver<Cmd>, services: &mut dyn HostServi
let g = &s.game;
let status = [s.status.as_str(), g.status.as_str()].iter().filter(|t| !t.is_empty()).map(|t| format!("{t} · ")).collect::<String>() + &format!("frame script {:.2} ms", g.frame_ms);
s.window.set_title(&format!(
- "ThreeRT live · {:.0} fps · {} spp/frame · GPU {:.1} ms · {conv}{}",
+ "ThreeRT live · {:.0} fps · {} spp/frame · GPU {:.1} ms · {} @ {:.0}% · {conv}{}",
s.fps,
s.spp,
s.core.gpu_ms,
+ reconstruction_label(&s.core.reconstruction_status()),
+ s.core.render_scale * 100.0,
if status.is_empty() { String::new() } else { format!(" · {status}") }
));
let mut st = s.core.meta();
@@ -838,6 +857,7 @@ pub fn parse_args(args: &[String], presets: &Path) -> Result<ViewArgs> {
let flag = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let num = |name: &str, d: u32| flag(name).and_then(|v| v.parse().ok()).unwrap_or(d);
Ok(ViewArgs {
+ rendering: crate::live::RenderingRequest::from_flags(&flag)?,
bundle: PathBuf::from(args.get(2).filter(|a| !a.starts_with("--")).ok_or_else(|| anyhow::anyhow!("game bundle required"))?),
assets: PathBuf::from(flag("--assets").unwrap_or_else(|| ".".into())),
room: flag("--room").unwrap_or_else(|| "local".into()),
@@ -854,3 +874,12 @@ pub fn parse_args(args: &[String], presets: &Path) -> Result<ViewArgs> {
pick: flag("--pick").map(|p| p.split(',').filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default(),
})
}
+
+/// The title's reconstruction: the method that ran, and the one asked for when it did not.
+fn reconstruction_label(r: &crate::live::ReconstructionStatus) -> String {
+ let active = r.active.as_deref().unwrap_or("builtin");
+ match r.skipped.first() {
+ Some((m, why, _)) if r.fallback.is_some() => format!("{active} ({m} {})", why.name()),
+ _ => active.to_string(),
+ }
+}
diff --git a/renderer/web/Cargo.lock b/renderer/web/Cargo.lock
index 9274ca3..a96a9ae 100644
--- a/renderer/web/Cargo.lock
+++ b/renderer/web/Cargo.lock
@@ -2678,6 +2678,7 @@ dependencies = [
"anyhow",
"base64 0.23.1",
"bytemuck",
+ "cc",
"glam 0.30.10",
"gltf",
"half",
diff --git a/renderer/web/src/lib.rs b/renderer/web/src/lib.rs
index 87daa65..ddf9a4f 100644
--- a/renderer/web/src/lib.rs
+++ b/renderer/web/src/lib.rs
@@ -19,7 +19,7 @@ use glam::Vec3;
use serde_json::{json, Value};
use std::cell::RefCell;
use std::path::Path;
-use threert_render::live::{Camera, LiveCore};
+use threert_render::live::{Camera, LiveCore, RenderingControl, RenderingRequest};
use threert_render::physics::PhysicsWorld;
use threert_render::voxel::VoxelWorld;
use threert_render::world::World;
@@ -32,6 +32,7 @@ struct Engine {
world: World,
voxels: VoxelWorld,
physics: Option<PhysicsWorld>,
+ rendering: RenderingControl,
}
/// The live view and the canvas it is shown on.
@@ -305,6 +306,20 @@ pub fn settings(d: &str) -> Result<(), JsValue> {
Ok(())
}
+/// Rendering settings (renderer/src/live/rendering.rs) as JSON, from the next frame.
+#[wasm_bindgen(js_name = setRendering)]
+pub fn set_rendering(json: &str) -> Result<(), JsValue> {
+ let v: serde_json::Value = serde_json::from_str(json).map_err(failed)?;
+ let r = RenderingRequest::from_json(&v).map_err(failed)?;
+ engine(|e| e.rendering.request(r));
+ Ok(())
+}
+
+#[wasm_bindgen(js_name = renderingStatus)]
+pub fn rendering_status() -> String {
+ engine(|e| e.rendering.status().to_string())
+}
+
// ---- The session ----
/// The canvas' pixels from the view's output (sRGB BGRA8 per pixel, live.wgsl `out_px`), bilinear to the canvas' size:
@@ -395,6 +410,7 @@ pub async fn start(canvas: web_sys::HtmlCanvasElement, width: u32, height: u32,
LiveCore::new(g, &e.world, Path::new(""), Path::new(""), width, height)
})
.map_err(failed)?;
+ core.attach_rendering_control(engine(|e| e.rendering.clone()));
core.dynamic_res = scale <= 0.0;
if scale > 0.0 {
core.render_scale = scale.clamp(threert_render::live::MIN_SCALE, 1.0);
diff --git a/renderer/web/www/engine.ts b/renderer/web/www/engine.ts
index b43f48e..32d9912 100644
--- a/renderer/web/www/engine.ts
+++ b/renderer/web/www/engine.ts
@@ -7,6 +7,8 @@ import type { Engine } from "@threert/scene";
/** The module's exports this file calls (wasm-bindgen's JavaScript for renderer/web: `threert_web.js`). */
export interface EngineExports {
+ setRendering(json: string): void;
+ renderingStatus(): string;
physics(op: string, args: string): string;
physicsPoses(): Float32Array;
voxelLevel(d: string): void;
@@ -71,6 +73,8 @@ const json = (d: unknown) => JSON.stringify(d ?? null);
/** `__engine` for the page: every call goes to the export of its name. */
export function webEngine(w: EngineExports): WebEngine {
return {
+ setRendering: (json) => w.setRendering(json),
+ renderingStatus: () => w.renderingStatus(),
physics: (op, args) => w.physics(op, json(args)),
physicsPoses: () => w.physicsPoses(),
voxelLevel: (d) => w.voxelLevel(json(d)),
diff --git a/tools/bench-metalfx.ts b/tools/bench-metalfx.ts
new file mode 100644
index 0000000..8506280
--- /dev/null
+++ b/tools/bench-metalfx.ts
@@ -0,0 +1,86 @@
+// macOS live reconstruction at 2x. Hold the camera for 80 frames, then move it laterally across
+// 12 frames. Compare the last frame of each sequence with a full-resolution 256-spp reference.
+// node tools/bench-metalfx.ts [--scene neon|glass|cornell] # THREERT_BIN selects the build
+import { execFileSync } from "node:child_process";
+import { copyFileSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { bundleGame } from "./bundle-game.ts";
+import type { Metrics } from "./compare/lib.ts";
+import { cachedRef, frameStats, repoRoot, rendererBin, requireQuietGpu } from "./lib/bench.ts";
+import { startLive } from "./lib/live.ts";
+
+const scenes = {
+ neon: { src: "scenes/neon-reflections.ts", preset: "cinematic", pos: [0.3, 1.5, 5.6], target: [0.2, 0.9, -0.6], fov: 40, distance: 0.75, width: 960, height: 540 },
+ glass: { src: "showcase/refraction/refraction.game.ts", preset: "preview", pos: [0, 0.15, 0.65], target: [0.003, 0.08, 0], fov: 31, distance: 0.06, width: 640, height: 360 },
+ cornell: { src: "scenes/cornell-box.ts", preset: "cinematic", pos: [0, 1, 3.9], target: [0, 1, 0], fov: 39, distance: 0.36, width: 640, height: 360 },
+};
+const index = process.argv.indexOf("--scene");
+const scene = index < 0 ? "neon" : process.argv[index + 1];
+if (scene !== "neon" && scene !== "glass" && scene !== "cornell") throw new Error("--scene accepts neon, glass or cornell");
+const config = scenes[scene];
+const quiet = requireQuietGpu();
+const out = join(repoRoot, "out/metalfx", scene === "neon" ? "" : scene);
+mkdirSync(out, { recursive: true });
+const build = { bin: rendererBin, assets: repoRoot, presets: join(repoRoot, "presets"), bundles: join(repoRoot, "out/bundles"), label: "MetalFX" };
+const { out: bundle } = await bundleGame(join(repoRoot, config.src));
+const { width, height } = config;
+const spp = 256;
+const env = { THREERT_SEED: "24301", THREERT_NO_GRAIN: "1", THREERT_MOTION_BLUR: "0,0,0" };
+const run = (args: string[]) => execFileSync(rendererBin, args, { cwd: repoRoot, encoding: "utf8", env: { ...process.env, ...env } });
+const pose = (frame: number) => {
+ const x = config.distance * frame / 12;
+ const shift = ([px, py, pz]: number[]) => [px + x, py, pz];
+ return { pos: shift(config.pos), target: shift(config.target) };
+};
+const image = (variant: string, shot: string) => join(out, `${variant}-${shot}.png`);
+const shots = ["still", "moving"] as const;
+for (const shot of shots) {
+ const { pos: position, target } = pose(shot === "still" ? 0 : 12);
+ const args = ["render", bundle, "--width", String(width), "--height", String(height), "--spp", String(spp),
+ "--no-denoise", "--camera", JSON.stringify({ position, target, fov: config.fov })];
+ const key = [readFileSync(bundle, "utf8"), readFileSync(join(build.presets, config.preset + ".json"), "utf8"), ...args].join("\n");
+ const ref = cachedRef(key);
+ if (!ref.hit) {
+ const tmp = ref.path + "." + process.pid + ".png";
+ try {
+ run([...args, "-o", tmp]);
+ renameSync(tmp, ref.path);
+ } finally {
+ rmSync(tmp, { force: true });
+ }
+ }
+ copyFileSync(ref.path, image("reference", shot));
+}
+const results: { mode: string; gpu: ReturnType<typeof frameStats>; still: Metrics; moving: Metrics }[] = [];
+for (const mode of ["builtin", "metalfx", "metalfx-denoised"]) {
+ const log = join(out, mode + ".jsonl");
+ const live = startLive(build, bundle, { width, height, scale: "0.5", frameLog: log, env, args: ["--reconstruction", mode] });
+ live.send({ cmd: "lockstep", dt: 0 });
+ try {
+ await live.firstFrame;
+ const step = async (cmd: object, shot: string) => {
+ const snapshot = shots.some((s) => s === shot) ? image(mode, shot) : undefined;
+ live.send({ ...cmd, sync: shot, snapshot });
+ await live.wait((line) => snapshot ? line.includes("live: snapshot " + snapshot + " at history") : line === "live: sync " + shot);
+ };
+ await step({ cmd: "frames", n: 80 }, "still");
+ for (let frame = 1; frame <= 12; frame++) {
+ await step({ cmd: "camera", ...pose(frame), frames: 1 }, frame === 12 ? "moving" : "move" + frame);
+ }
+ } finally {
+ if (live.p.exitCode === null && live.p.signalCode === null) await live.quit();
+ }
+ const frames = readFileSync(log, "utf8").trim().split("\n").map((s) => JSON.parse(s));
+ const active = [...new Set(frames.map((f) => f.reconstruction))];
+ if (active.length !== 1 || active[0] !== mode) throw new Error(`Requested ${mode}, observed ${active.join(", ")}`);
+ const gpu = frameStats(frames.slice(40, 80).map((f) => f.gpu));
+ const compare = (shot: string): Metrics => JSON.parse(run(["compare", image("reference", shot), image(mode, shot)]));
+ const result = { mode, gpu, still: compare("still"), moving: compare("moving") };
+ console.log(`${mode}: GPU p50 ${gpu.p50.toFixed(2)} ms, SSIM still ${result.still.ssim}, moving ${result.moving.ssim}`);
+ // Reversing the denoising mask leaves 1-spp grain on the flat walls (~0.79 on the M1).
+ if (scene === "cornell" && mode === "metalfx-denoised" && result.still.ssim < 0.90) {
+ throw new Error(`Cornell diffuse reconstruction: SSIM ${result.still.ssim} below 0.90`);
+ }
+ results.push(result);
+}
+writeFileSync(join(out, "results.json"), JSON.stringify({ scene, width, height, scale: 0.5, referenceSpp: spp, quiet, results }, null, 2) + "\n");
diff --git a/tools/denoise-demo/live.sh b/tools/denoise-demo/live.sh
new file mode 100755
index 0000000..64cff50
--- /dev/null
+++ b/tools/denoise-demo/live.sh
@@ -0,0 +1,11 @@
+#!/bin/sh
+# Kaleido in a window, live: press M to switch between ThreeRT's denoiser and the best this device has (MetalFX's
+# joint denoiser on a Mac), N to step through every method (builtin, metalfx-denoised, metalfx, fsr, off). The
+# window's title says which ran, the frame rate and the render scale. Esc quits.
+# The window is 960 x 540 points: 1920 x 1080 pixels on a Retina display, the recordings' size.
+# tools/denoise-demo/live.sh [extra play flags, e.g. --quality balanced or --width 1280 --height 720]
+cd "$(dirname "$0")/../.." || exit 1
+[ -f out/bundles/kaleido.js ] || node tools/bundle-game.ts games/kaleido/kaleido.game.ts -o out/bundles/kaleido.js
+# (The radiance cache over-brightens with hundreds of moving lights: off, as in the recordings.)
+THREERT_CACHE=0 exec renderer/target/release/threert-render play out/bundles/kaleido.js --assets . --presets presets \
+ --width 960 --height 540 --quality performance --reconstruction builtin "$@"
diff --git a/tools/denoise-demo/overlay.py b/tools/denoise-demo/overlay.py
new file mode 100644
index 0000000..3324638
--- /dev/null
+++ b/tools/denoise-demo/overlay.py
@@ -0,0 +1,18 @@
+# A transparent overlay of text labels on dark boxes (this machine's ffmpeg has no drawtext).
+# python3 overlay.py out.png width height font '[{"text": "...", "x": 24, "y": 24, "size": 40, "align": "left|right|center"}]'
+import json, sys
+from PIL import Image, ImageDraw, ImageFont
+
+out, w, h, font, labels = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4], json.loads(sys.argv[5])
+img = Image.new("RGBA", (w, h), (0, 0, 0, 0))
+d = ImageDraw.Draw(img)
+for l in labels:
+ f = ImageFont.truetype(font, l["size"])
+ x0, y0, x1, y1 = d.textbbox((0, 0), l["text"], font=f)
+ tw, th = x1 - x0, y1 - y0
+ pad = max(8, l["size"] // 3)
+ x = {"left": l["x"], "right": w - l["x"] - tw, "center": (w - tw) // 2}[l.get("align", "left")]
+ y = l["y"] if l["y"] >= 0 else h + l["y"] - th
+ d.rounded_rectangle((x - pad, y - pad, x + tw + pad, y + th + pad), radius=pad // 2, fill=(0, 0, 0, 150))
+ d.text((x - x0, y - y0), l["text"], font=f, fill=(255, 255, 255, 255))
+img.save(out)
diff --git a/tools/denoise-demo/perf.ts b/tools/denoise-demo/perf.ts
new file mode 100644
index 0000000..2563f57
--- /dev/null
+++ b/tools/denoise-demo/perf.ts
@@ -0,0 +1,34 @@
+// Real-time speed of each method on Kaleido's show: uncapped, 12 s, the first 3 s (load, warm-up) left out.
+// node tools/denoise-demo/perf.ts [--methods builtin,metalfx-denoised] [--repeat 2] (best of the repeats)
+import { spawn } from "node:child_process";
+import { readFileSync, rmSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+const root = resolve(import.meta.dirname, "../..");
+const args = process.argv.slice(2);
+const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);
+const bin = process.env.THREERT_BIN ?? join(root, "renderer/target/release/threert-render");
+const bundle = resolve(flag("--bundle", join(root, "out/bundles/kaleido.js")));
+const env = { ...process.env, THREERT_SEED: "24301", THREERT_CACHE: "0" };
+const pct = (xs: number[], q: number) => [...xs].sort((a, b) => a - b)[Math.floor(q * (xs.length - 1))];
+const results: Record<string, unknown> = {};
+for (const method of flag("--methods", "builtin,metalfx-denoised").split(",")) {
+ let best: { fps: number; gpuP50: number; gpuP95: number } | null = null;
+ for (let r = 0; r < Number(flag("--repeat", "2")); r++) {
+ const log = `/tmp/denoise-perf-${method}.jsonl`;
+ rmSync(log, { force: true });
+ const p = spawn(bin, ["live", bundle, "--assets", root, "--presets", join(root, "presets"), "--width", "1920", "--height", "1080",
+ "--quality", flag("--quality", "performance"), "--reconstruction", method, "--frame-log", log, "--fps", "1000"], { cwd: root, stdio: ["pipe", "ignore", "ignore"], env });
+ await new Promise((res) => setTimeout(res, 12_000));
+ p.stdin!.write('{"cmd":"quit"}\n');
+ await new Promise((res) => p.on("exit", res));
+ const all = readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
+ const fs = all.filter((f) => f.t >= all[0].t + 3000);
+ if (fs.some((f) => f.reconstruction !== method)) throw new Error(`${method} did not run on every frame`);
+ const run = { fps: (1000 * (fs.length - 1)) / (fs[fs.length - 1].t - fs[0].t), gpuP50: pct(fs.map((f) => f.gpu), 0.5), gpuP95: pct(fs.map((f) => f.gpu), 0.95) };
+ if (!best || run.fps > best.fps) best = run;
+ }
+ results[method] = best;
+ console.log(method, JSON.stringify(best));
+}
+console.log(JSON.stringify(results));
diff --git a/tools/denoise-demo/record.ts b/tools/denoise-demo/record.ts
new file mode 100644
index 0000000..dcbe57c
--- /dev/null
+++ b/tools/denoise-demo/record.ts
@@ -0,0 +1,57 @@
+// The denoiser demo's frames: Kaleido's show (games/kaleido) in lockstep at 60 Hz, every frame saved, once per
+// reconstruction method, so frame k is the same moment in each run.
+// node tools/bundle-game.ts out/kaleido-demo/wait.game.ts -o out/kaleido-demo/kaleido-wait.js
+// node tools/denoise-demo/record.ts --methods off,builtin,metalfx-denoised [--frames 660] [--quality performance]
+// out/kaleido-demo/<method>/f####.png and frames.jsonl; each run must report its method on every frame.
+import { spawn } from "node:child_process";
+import { createInterface } from "node:readline";
+import { mkdirSync, readFileSync, rmSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+const root = resolve(import.meta.dirname, "../..");
+const args = process.argv.slice(2);
+const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);
+const bin = process.env.THREERT_BIN ?? join(root, "renderer/target/release/threert-render");
+const bundle = resolve(flag("--bundle", join(root, "out/kaleido-demo/kaleido-wait.js")));
+const out = resolve(flag("--out", join(root, "out/kaleido-demo")));
+const frames = Number(flag("--frames", "660"));
+const quality = flag("--quality", "performance");
+// The radiance cache over-brightens with hundreds of moving emitters (docs/ROADMAP.md): off for both methods.
+const env = { ...process.env, THREERT_SEED: "24301", THREERT_NO_GRAIN: "1", THREERT_MOTION_BLUR: "0,0,0", THREERT_CACHE: "0" };
+
+for (const method of flag("--methods", "off,builtin,metalfx-denoised").split(",")) {
+ const dir = join(out, method);
+ mkdirSync(dir, { recursive: true });
+ const log = join(dir, "frames.jsonl");
+ rmSync(log, { force: true });
+ const p = spawn(bin, ["live", bundle, "--assets", root, "--presets", join(root, "presets"), "--width", "1920", "--height", "1080",
+ "--quality", quality, "--reconstruction", method, "--frame-log", log, "--fps", "60"], { cwd: root, stdio: ["pipe", "ignore", "pipe"], env });
+ const lines: string[] = [];
+ let waiters: [(l: string) => boolean, (l: string) => void][] = [];
+ createInterface({ input: p.stderr! }).on("line", (l) => {
+ lines.push(l);
+ if (/panick|error|failed/i.test(l)) console.log(` [${method}] ${l}`);
+ waiters = waiters.filter(([f, r]) => (f(l) ? (r(l), false) : true));
+ });
+ const exited = new Promise<void>((r) => p.on("exit", () => r()));
+ const wait = (f: (l: string) => boolean) => new Promise<string>((res, rej) => {
+ const hit = lines.find(f);
+ if (hit) return res(hit);
+ waiters.push([f, res]);
+ exited.then(() => rej(new Error(lines.slice(-8).join("\n"))));
+ });
+ const send = (c: object) => p.stdin!.write(JSON.stringify(c) + "\n");
+ await wait((l) => l.includes("fps on"));
+ send({ cmd: "lockstep", dt: 1 / 60 });
+ send({ cmd: "event", type: "go" });
+ const t0 = Date.now();
+ for (let k = 0; k < frames; k++) {
+ send({ cmd: "frames", n: 1, sync: "f" + k, snapshot: join(dir, `f${String(k).padStart(4, "0")}.png`) });
+ await wait((l) => l === "live: sync f" + k);
+ }
+ send({ cmd: "quit" });
+ await exited;
+ const ran = [...new Set(readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l).reconstruction))];
+ if (ran.length !== 1 || ran[0] !== method) throw new Error(`${method}: ran ${ran.join(", ")}`);
+ console.log(`${method}: ${frames} frames in ${((Date.now() - t0) / 1000).toFixed(0)} s`);
+}
diff --git a/tools/denoise-demo/video.ts b/tools/denoise-demo/video.ts
new file mode 100644
index 0000000..8adcd74
--- /dev/null
+++ b/tools/denoise-demo/video.ts
@@ -0,0 +1,62 @@
+// The denoiser demo's videos from tools/denoise-demo/record.ts's frames (ffmpeg):
+// split: the whole frame, ThreeRT's denoiser on the left half, MetalFX's on the right (the same frame), at 60 fps:
+// the speed it was rendered at.
+// 3up: 1:1 crops of the middle of the frame: the input (the trace, not denoised), ThreeRT's, MetalFX's, at half speed.
+// node tools/denoise-demo/video.ts [--from 0 --to 659] [--fps-builtin 49 --fps-metalfx 53]
+import { execFileSync } from "node:child_process";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+const root = resolve(import.meta.dirname, "../..");
+const args = process.argv.slice(2);
+const flag = (k: string, d: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);
+const dir = resolve(flag("--dir", join(root, "out/kaleido-demo")));
+const out = join(dir, "video");
+mkdirSync(out, { recursive: true });
+const from = Number(flag("--from", "0")), to = Number(flag("--to", "659"));
+const font = flag("--font", "/System/Library/Fonts/Hiragino Sans GB.ttc");
+const fpsOf = (m: string) => flag(`--fps-${m}`, "");
+const enc = () => ["-frames:v", String(to - from + 1), "-c:v", "libx264", "-preset", "slow", "-crf", "14", "-pix_fmt", "yuv420p", "-movflags", "+faststart"];
+const input = (m: string, rate: number) => ["-framerate", String(rate), "-start_number", String(from), "-i", join(dir, m, "f%04d.png")];
+// Labels: a transparent PNG drawn by overlay.py (this machine's ffmpeg has no drawtext), laid over the frame.
+type Label = { text: string; x: number; y: number; size: number; align?: "left" | "right" | "center" };
+let n = 0;
+const labels = (w: number, h: number, ls: Label[]) => {
+ const f = join(out, `labels-${n++}.png`);
+ execFileSync("python3", ["-I", join(import.meta.dirname, "overlay.py"), f, String(w), String(h), font, JSON.stringify(ls)]);
+ return f;
+};
+const ffmpeg = (a: string[]) => execFileSync("ffmpeg", ["-y", "-loglevel", "error", ...a], { stdio: "inherit" });
+const fps = (m: string) => (fpsOf(m) ? ` · ${fpsOf(m)} fps` : "");
+
+// Split screen: the left half of ThreeRT's frame beside the right half of MetalFX's.
+const caption = "同一帧 · 输出 1920×1080 · 渲染 960×540(50%)· 每像素每帧 1 条光线 · 按渲染速度 60 fps 播放";
+const splitLabels = (cap: boolean) => labels(1920, 1080, [
+ { text: `ThreeRT 内置降噪${cap ? fps("builtin") : ""}`, x: 28, y: 28, size: 40 },
+ { text: `MetalFX 联合降噪${cap ? fps("metalfx") : ""}`, x: 28, y: 28, size: 40, align: "right" },
+ ...(cap ? [{ text: caption, x: 0, y: -30, size: 26, align: "center" as const }] : []),
+]);
+const split = "[0]crop=960:1080:0:0[l];[1]crop=960:1080:960:0[r];[l][r]hstack=2,drawbox=x=958:y=0:w=4:h=1080:[email protected]:t=fill[v];[v][2]overlay=0:0";
+ffmpeg([...input("builtin", 60), ...input("metalfx-denoised", 60), "-i", splitLabels(true), "-filter_complex", split,
+ ...enc(), join(out, "kaleido-split.mp4")]);
+
+// Three 1:1 crops of the middle (no resampling: each method's own pixels), at half speed.
+const [cw, ch, cx, cy] = [640, 720, 640, 260];
+const threeLabels = (cap: boolean) => labels(1920, 720, [
+ { text: "输入:光追原始信号(未降噪)", x: 24, y: 24, size: 30 },
+ { text: "ThreeRT 内置降噪", x: 664, y: 24, size: 30 },
+ { text: "MetalFX 联合降噪", x: 1304, y: 24, size: 30 },
+ ...(cap ? [{ text: "画面中央 1:1 裁切 · 半速播放", x: 0, y: -24, size: 24, align: "center" as const }] : []),
+]);
+const three = [0, 1, 2].map((i) => `[${i}]crop=${cw}:${ch}:${cx}:${cy}[c${i}]`).join(";") + ";[c0][c1][c2]hstack=3," +
+ "drawbox=x=638:y=0:w=4:h=720:[email protected]:t=fill,drawbox=x=1278:y=0:w=4:h=720:[email protected]:t=fill[v];[v][3]overlay=0:0";
+ffmpeg([...input("off", 30), ...input("builtin", 30), ...input("metalfx-denoised", 30), "-i", threeLabels(true), "-filter_complex", three,
+ ...enc(), join(out, "kaleido-3up.mp4")]);
+
+// Stills of both at a few moments.
+for (const k of [222, 300, 480]) {
+ const f = (m: string) => ["-i", join(dir, m, `f${String(k).padStart(4, "0")}.png`)];
+ ffmpeg([...f("builtin"), ...f("metalfx-denoised"), "-i", splitLabels(false), "-filter_complex", split, "-frames:v", "1", join(out, `kaleido-split-f${k}.png`)]);
+ ffmpeg([...f("off"), ...f("builtin"), ...f("metalfx-denoised"), "-i", threeLabels(false), "-filter_complex", three, "-frames:v", "1", join(out, `kaleido-3up-f${k}.png`)]);
+}
+console.log(`videos and stills in ${out}`);