Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an offline CPU path tracer for stills

Nguyen Xuan Anee5f476c1c75
diff --git a/.gitignore b/.gitignore
index d537b834..779332e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,7 @@ public/terrain.md
public/grass.md
public/clutter.md
public/light-bake.md
+public/path-tracer.md
public/scene-graph.md
public/modeling.md
public/animation-curves.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 14501d95..03736a2e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add `67js/addons/path-tracer` (part of issue #57; the Cycles comparison is partial). `renderPathTracedImage({ parts, environment, camera }, options)` draws a still by CPU path tracing against the triangle BVH of the light bake, with next-event estimation for the sun, point, spot and area lights, an importance-sampled environment map, GGX metal, clear coat, glass, maps and cutouts, and a wavelet denoiser, on up to eight module workers. An `image` render job selects it with `settings.renderer: { type: "pathTracer", samples, bounces, denoise, seed, maxSeconds }`; the same recipe and seed give the same PNG, a job past `maxSeconds` fails with no image, and samples, size and ray work are bounded. It loads on demand: the core bundle and the agent scene do not carry it (the limits live in `src/path-tracer-capabilities.js`, listed under `jobs.pathTracer` in `scene_capabilities`; the tool schemas gain one `renderer` field inside the total budget). `npm run reference -- --path-tracer` scores it against Cycles: better than the rasterizer on 7 of the 11 reference scenes (`lit-interior` 0.5055 to 0.1993, `spot-area` 0.1242 to 0.0639), worse on `outdoor-hdri`, `character` and `fog`, mean 0.171 against 0.189. Not drawn: volume fog, normal maps, translucent leaves, caustics, lights seen in mirrors. `src/ray-query.js` now holds the ray query and light falloff that `light-bake` used to carry. `npm run smoke:path-tracer` checks it through MCP.
+
- Add recipe particles and hair (part of issue #63, no new tool). A `particles` section holds seeded emitter systems (point, box, sphere or disc; gravity, drag, wind, a landing floor, size over life) and hair systems that grow strands from a surface node, loaded on demand with the new `particles` module (`src/particles.js`, `src/hair.js`). Each particle is a closed-form function of its seed, index and time, so a seek never replays: the same time gives the same particles, a seek backwards repeats them and a seeded system gives identical bytes (`npm run smoke:agent-particles` checks PNG bytes through the MCP preview, including a second session). Counts are bounded to 4 systems, 2000 particles each, 4000 in total and 100000 drawn vertices. New `set-particles` operation and a `particles` report in `scene_inspect`; the schema takes one record reference, so the tool schemas stay within the total budget and the fields live in `scene_capabilities`. Cloth and particles now share validation helpers (`src/agent-recipe-checks.js`). Left out: particle collisions and bounce, rotation, colour and alpha, hair collision and combing. The smoke, fire and liquid decision (no browser solver, with measured grid costs) is in `docs/physics.md`.
- Add `67js/addons/light-bake` (part of issue #55; recipes, MCP, GLB export and reflection probes are not done). `bakeLightmaps(parts, lights, options)` traces cosine-weighted paths on the CPU against a triangle BVH and returns new parts that carry the light that bounces between surfaces (point lights and the sun, shadowed) as a lightmap texture drawn through the emissive map, with lightmap UVs from the `uv_unwrap` unwrap. The renderer and its shaders are untouched, so a scene without a bake renders as before and core size is unchanged. Bounded and deterministic: `samples`, `bounces`, `texelsPerUnit`, `maxResolution` and `maxSeconds` are range checked, texel, triangle, light and ray-work totals are checked before any ray is traced, and the same input gives the same bytes. Parts with their own maps, pattern, emission, skin or transparency are skipped and listed in the report. `npm run reference -- --bake lit-interior` takes `lit-interior` from 0.5055 to 0.1444 against Cycles (6 s bake); no other scene moved by more than 0.002. The package archive grows by 3,525 bytes (717,978 to 721,503). See `docs/light-bake.md`.
diff --git a/README.md b/README.md
index f48ec3a7..a102929d 100644
--- a/README.md
+++ b/README.md
@@ -120,6 +120,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Terrain | `67js/addons/terrain`, `67js/addons/texture-set` | [Chunked terrain](https://67js.codepawl.com/terrain.md) with level of detail and a four-layer splat material from scanned textures. |
| Grass | `67js/addons/grass` | [Grass fields](https://67js.codepawl.com/grass.md) of clumped, curved blades with rolling wind gusts, paths and level of detail. |
| Clutter | `67js/addons/clutter` | [Pebbles, rocks, twigs and fallen leaves](https://67js.codepawl.com/clutter.md) scattered over terrain in streamed tiles. |
+| Path tracer | `67js/addons/path-tracer` | [Offline stills that follow Cycles](https://67js.codepawl.com/path-tracer.md): bounced light, glass and soft shadows on the CPU. |
| Light bake | `67js/addons/light-bake` | [Bounced light baked into one lightmap per part](https://67js.codepawl.com/light-bake.md), drawn through the emissive map. |
| Vegetation | `67js/addons/vegetation` | [Seeded trees, bushes and grass](https://67js.codepawl.com/vegetation.md) with scanned leaves and bark, wind and level of detail. |
| Liquid | `67js/addons/spume` | [Baked liquid playback](https://67js.codepawl.com/spume.md) with refraction and spray from the Spume solver. |
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 5813d903..f2eadaf0 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -58,3 +58,21 @@ EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In
- `car-paint` scored 0.1521 against Cycles and `glass` 0.1326 (it was 0.1450 with the `liquid` material). The other scenes scored the same as in the table above, to four digits. The table above is the 2026-10-30 baseline and has not been rewritten.
- `fog` has no noise on either side. EEVEE and 67.js approximate scattering, and Cycles follows 8 volume bounces.
- Sample counts are fixed: 256 for Cycles with denoising, 64 for EEVEE and 4 MSAA samples for 67.js.
+
+Path tracer (issue #57): `npm run reference -- --path-tracer [--samples 32]` draws each scene with `addons/path-tracer` (CPU, 960 by 540, four threads, below-normal priority) and scores it against the Cycles renders of an earlier run into `path-tracer.json`; `baseline.json` and `images/` stay as they are. Measured 2026-10-31 at 32 samples with the tracer's own denoiser, on a Ryzen 5 5600X that another session was also loading (seconds are wall time and are inflated by that):
+
+| Scene | 67.js rasterizer | Path tracer | Seconds | Not drawn by the tracer |
+| --- | --- | --- | --- | --- |
+| `brick-graph` | 0.2269 | 0.1538 | 34.2 | normal map (bump) |
+| `car-paint` | 0.1521 | 0.1372 | 44.5 | |
+| `character` | 0.0995 | 0.1143 | 35.5 | |
+| `fog` | 0.2612 | 0.5622 | 33.5 | volume fog |
+| `foliage` | 0.1594 | 0.1597 | 126.1 | leaf translucency |
+| `glass` | 0.1326 | 0.1237 | 50.3 | |
+| `lit-interior` | 0.5055 | 0.1993 | 238.0 | |
+| `material-spheres` | 0.1598 | 0.1215 | 66.8 | |
+| `metal` | 0.1868 | 0.1467 | 43.2 | |
+| `outdoor-hdri` | 0.0676 | 0.1036 | 25.1 | |
+| `spot-area` | 0.1242 | 0.0639 | 71.6 | |
+
+The mean against Cycles is 0.171 for the path tracer and 0.189 for the rasterizer (the light bake gets `lit-interior` to 0.1444, better than the tracer's 0.1993). The tracer is worse on `outdoor-hdri` and `character`: in the images the floor is darker than in Cycles (the cause is not found), and `fog` shows the missing volume. The denoiser blurs some soft shadows. Cycles used 256 samples. See `docs/path-tracer.md` for what the tracer draws and skips.
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index df3e150b..cb271abc 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -1,6 +1,7 @@
// Runs in the page: draws one reference scene, and describes it as plain data for Blender.
import { Renderer67 } from '/src/renderer.js';
import { REFERENCE_SCENES } from './scenes.js';
+import { skinnedGeometry } from '/src/path-tracer-scene.js';
function encodeBytes(typedArray) {
const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
@@ -26,40 +27,13 @@ function plainData(value) {
return value;
}
-function addWeightedTransform(output, offset, palette, joint, weight, x, y, z, translationWeight) {
- const base = joint * 16;
- output[offset] += weight * (palette[base] * x + palette[base + 4] * y + palette[base + 8] * z + palette[base + 12] * translationWeight);
- output[offset + 1] += weight * (palette[base + 1] * x + palette[base + 5] * y + palette[base + 9] * z + palette[base + 13] * translationWeight);
- output[offset + 2] += weight * (palette[base + 2] * x + palette[base + 6] * y + palette[base + 10] * z + palette[base + 14] * translationWeight);
-}
-
// Blender's glTF importer cannot reproduce this rig's pose (three.js and 67.js agree on it), so Blender gets the
// skinned result as plain geometry. A score then measures shading, and not an importer's pose.
-function bakeSkinnedGeometry(part) {
- const { geometry, skin } = part;
- const positions = new Float32Array(geometry.positions.length);
- const normals = new Float32Array(geometry.normals.length);
- const influenceCount = geometry.skinWeights.length / (geometry.positions.length / 3);
- for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {
- const offset = vertex * 3;
- for (let influence = 0; influence < influenceCount; influence++) {
- const weight = geometry.skinWeights[vertex * influenceCount + influence];
- if (weight === 0) continue;
- const joint = geometry.skinIndices[vertex * influenceCount + influence];
- addWeightedTransform(positions, offset, skin.jointMatrices, joint, weight, geometry.positions[offset], geometry.positions[offset + 1], geometry.positions[offset + 2], 1);
- addWeightedTransform(normals, offset, skin.jointMatrices, joint, weight, geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2], 0);
- }
- const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]) || 1;
- for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;
- }
- return { ...geometry, positions, normals };
-}
-
function describeScene(id, scene) {
const { map: _map, ...environment } = scene.environment;
const geometries = new Map();
const describedParts = scene.parts.map(part => {
- const geometry = part.skin ? bakeSkinnedGeometry(part) : part.geometry;
+ const geometry = part.skin ? skinnedGeometry(part) : part.geometry;
if (!geometries.has(geometry)) geometries.set(geometry, geometries.size);
return { name: part.name, geometry: geometries.get(geometry), matrix: [...part.matrix], material: plainData(part.material) };
});
@@ -103,5 +77,17 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambien
return result;
}
+async function renderReferencePathTraced(id, options) {
+ const scene = await REFERENCE_SCENES[id]();
+ const { renderPathTracedImage } = await import('/src/path-tracer.js');
+ const result = await renderPathTracedImage({ parts: scene.parts, environment: scene.environment, camera: scene.camera }, options);
+ const canvas = document.createElement('canvas');
+ canvas.width = result.width;
+ canvas.height = result.height;
+ canvas.getContext('2d').putImageData(new ImageData(result.rgba, result.width, result.height), 0, 0);
+ return { image: canvas.toDataURL('image/png').split(',')[1], report: result.report };
+}
+
window.renderReferenceScene = renderReferenceScene;
+window.renderReferencePathTraced = renderReferencePathTraced;
window.referenceSceneIds = Object.keys(REFERENCE_SCENES);
diff --git a/bench/reference/path-tracer.json b/bench/reference/path-tracer.json
new file mode 100644
index 00000000..c6494d6d
--- /dev/null
+++ b/bench/reference/path-tracer.json
@@ -0,0 +1,79 @@
+{
+ "metric": "FLIP (LDR), mean error against Cycles, lower is better",
+ "scores": {
+ "brick-graph": {
+ "pathtracer-vs-cycles": 0.1538,
+ "seconds": 34.2,
+ "samples": 32,
+ "ignored": [
+ "normalMap is ignored."
+ ]
+ },
+ "car-paint": {
+ "pathtracer-vs-cycles": 0.1372,
+ "seconds": 44.5,
+ "samples": 32,
+ "ignored": []
+ },
+ "character": {
+ "pathtracer-vs-cycles": 0.1143,
+ "seconds": 35.5,
+ "samples": 32,
+ "ignored": [
+ "gltf materials are traced as plain surfaces."
+ ]
+ },
+ "fog": {
+ "pathtracer-vs-cycles": 0.5622,
+ "seconds": 33.5,
+ "samples": 32,
+ "ignored": [
+ "volumeFog is not traced."
+ ]
+ },
+ "foliage": {
+ "pathtracer-vs-cycles": 0.1597,
+ "seconds": 126.1,
+ "samples": 32,
+ "ignored": [
+ "foliage materials are traced as plain surfaces."
+ ]
+ },
+ "glass": {
+ "pathtracer-vs-cycles": 0.1237,
+ "seconds": 50.3,
+ "samples": 32,
+ "ignored": []
+ },
+ "lit-interior": {
+ "pathtracer-vs-cycles": 0.1993,
+ "seconds": 238,
+ "samples": 32,
+ "ignored": []
+ },
+ "material-spheres": {
+ "pathtracer-vs-cycles": 0.1215,
+ "seconds": 66.8,
+ "samples": 32,
+ "ignored": []
+ },
+ "metal": {
+ "pathtracer-vs-cycles": 0.1467,
+ "seconds": 43.2,
+ "samples": 32,
+ "ignored": []
+ },
+ "outdoor-hdri": {
+ "pathtracer-vs-cycles": 0.1036,
+ "seconds": 25.1,
+ "samples": 32,
+ "ignored": []
+ },
+ "spot-area": {
+ "pathtracer-vs-cycles": 0.0639,
+ "seconds": 71.6,
+ "samples": 32,
+ "ignored": []
+ }
+ }
+}
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index 0bbd3419..4b4c59e0 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -2,6 +2,8 @@
// --ambient-occlusion <strength> [--ambient-occlusion-radius <units>] turns occlusion on (off by default).
// --bake [<id>,<id>] bakes bounced light into the named scenes (every scene when no ids follow) before 67.js draws them;
// Blender still gets the plain scene.
+// --path-tracer [--samples <n>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the
+// Cycles renders of an earlier run, and scores them into path-tracer.json. Nothing in baseline.json or images/ changes.
// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.
import { spawnSync } from 'node:child_process';
import { mkdir, writeFile } from 'node:fs/promises';
@@ -35,6 +37,9 @@ const ambientOcclusionRadius = radiusFlag >= 0 ? Number(argumentsGiven[radiusFla
const bakeFlag = argumentsGiven.indexOf('--bake');
const bakeValue = bakeFlag >= 0 ? argumentsGiven[bakeFlag + 1] : undefined;
const bakedSceneIds = bakeFlag >= 0 && bakeValue && !bakeValue.startsWith('--') ? bakeValue.split(',') : null;
+const pathTracerFlag = argumentsGiven.includes('--path-tracer');
+const samplesFlag = argumentsGiven.indexOf('--samples');
+const pathTracerSamples = samplesFlag >= 0 ? Number(argumentsGiven[samplesFlag + 1]) : 64;
const onlyScene = sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1] : null;
async function renderBackend(backend, serverUrl, graphics) {
@@ -65,6 +70,29 @@ async function renderBackend(backend, serverUrl, graphics) {
}
}
+async function renderPathTracerScenes(serverUrl) {
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS.cpu });
+ const timings = {};
+ try {
+ const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });
+ page.setDefaultTimeout(0);
+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });
+ await page.waitForFunction(() => window.renderReferencePathTraced, null, { timeout: PAGE_LOAD_TIMEOUT });
+ const sceneIds = await page.evaluate(() => window.referenceSceneIds);
+ for (const id of sceneIds) {
+ if (onlyScene && id !== onlyScene) continue;
+ const options = { width: WIDTH, height: HEIGHT, samples: pathTracerSamples, maxSeconds: 1800 };
+ const result = await page.evaluate(([sceneId, tracerOptions]) => window.renderReferencePathTraced(sceneId, tracerOptions), [id, options]);
+ await writeFile(`${WORK_DIRECTORY}/${id}-pathtracer.png`, Buffer.from(result.image, 'base64'));
+ timings[id] = { seconds: Number(result.report.seconds.toFixed(1)), samples: result.report.samples, ignored: result.report.ignored };
+ console.log(`${id} path traced: ${timings[id].seconds} s at ${timings[id].samples} samples`);
+ }
+ } finally {
+ await browser.close();
+ }
+ await writeFile(`${WORK_DIRECTORY}/pathtracer-timings.json`, JSON.stringify(timings, null, 1));
+}
+
function runChecked(command, commandArguments) {
const result = spawnSync(command, commandArguments, { stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8', maxBuffer: 1 << 28 });
const lines = result.stdout.split('\n').filter(line => !/^(Fra:|Saved:|Time:|\s*$)/.test(line));
@@ -75,7 +103,17 @@ function runChecked(command, commandArguments) {
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
await mkdir(`${WORK_DIRECTORY}/scenes`, { recursive: true });
-if (!scoreOnly) {
+if (pathTracerFlag && !scoreOnly) {
+ const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+ await server.listen();
+ try {
+ await renderPathTracerScenes(`http://127.0.0.1:${server.httpServer.address().port}`);
+ } finally {
+ await server.close();
+ }
+}
+
+if (!scoreOnly && !pathTracerFlag) {
const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
await server.listen();
const graphics = {};
@@ -93,9 +131,9 @@ if (!scoreOnly) {
}
}
-if (!onlyScene) {
+if (!onlyScene || pathTracerFlag) {
runChecked('uv', [
'run', '--no-project', '--python', '3.12', '--with', 'flip-evaluator', '--with', 'pillow', '--with', 'numpy',
- 'python', '-I', 'bench/reference/score.py', WORK_DIRECTORY, OUTPUT_DIRECTORY,
+ 'python', '-I', 'bench/reference/score.py', WORK_DIRECTORY, OUTPUT_DIRECTORY, ...(pathTracerFlag ? ['--path-tracer'] : []),
]);
}
diff --git a/bench/reference/score.py b/bench/reference/score.py
index 59d60d5b..062f265e 100644
--- a/bench/reference/score.py
+++ b/bench/reference/score.py
@@ -54,7 +54,25 @@ def side_by_side(cycles, eevee, gpu, scores):
return sheet
+def score_path_tracer(work_directory, output_directory):
+ """FLIP of each path traced render against the Cycles render of the same scene, with the time it took."""
+ timings = json.loads((work_directory / "pathtracer-timings.json").read_text(encoding="utf-8"))
+ results = {}
+ for scene_id in sorted(timings):
+ cycles = tone_map_like_67js(np.load(work_directory / f"{scene_id}-cycles.npy"))
+ traced = load_png(work_directory / f"{scene_id}-pathtracer.png")
+ results[scene_id] = {"pathtracer-vs-cycles": flip_score(cycles, traced), **timings[scene_id]}
+ report = {"metric": "FLIP (LDR), mean error against Cycles, lower is better", "scores": results}
+ (output_directory / "path-tracer.json").write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")
+ print("scene".ljust(20) + "pathtracer-vs-cycles".rjust(22) + "seconds".rjust(10))
+ for scene_id, entry in results.items():
+ print(scene_id.ljust(20) + f"{entry['pathtracer-vs-cycles']:.4f}".rjust(22) + f"{entry['seconds']:.1f}".rjust(10))
+
+
def main():
+ if "--path-tracer" in sys.argv:
+ score_path_tracer(Path(sys.argv[1]), Path(sys.argv[2]))
+ return
work_directory = Path(sys.argv[1])
output_directory = Path(sys.argv[2])
images_directory = output_directory / "images"
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 0d9b4a2b..b05e3a5b 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 283335,
- "gzip": 80949,
- "brotli": 69068
+ "min": 283440,
+ "gzip": 80969,
+ "brotli": 68932
},
"entry:model": {
"min": 40093,
@@ -125,8 +125,13 @@
},
"entry:light-bake": {
"min": 67640,
- "gzip": 24805,
- "brotli": 21989
+ "gzip": 24815,
+ "brotli": 21956
+ },
+ "entry:path-tracer": {
+ "min": 31466,
+ "gzip": 12605,
+ "brotli": 11075
},
"entry:texture-set": {
"min": 1837,
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 9800dda8..16696e80 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -1,5 +1,5 @@
{
- "archiveBytes": 751100,
+ "archiveBytes": 758000,
"goals": {
"lit-box": 50000,
"gltf-box": 80000,
@@ -28,6 +28,7 @@
"entry:terrain": 3100,
"entry:grass": 4400,
"entry:clutter": 5300,
+ "entry:path-tracer": 12700,
"entry:light-bake": 25400,
"entry:texture-set": 900,
"entry:agent-scene": 63300,
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index a1a9fb5e..f71cbfc0 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -71,6 +71,17 @@ Videos hold the lit image only.
A seek to any frame gives the same pixels: a job samples each frame from its time and keeps no state between frames.
`npm run smoke:render-passes` proves it through MCP: it renders eight stills with every pass, then renders frame 3 again as an image in a different order of seeks and compares the bytes of the lit image and all five passes.
+## Path tracer
+
+An `image` job can ask for the offline [path tracer](path-tracer.md) with `settings.renderer`:
+
+```json
+{ "kind": "image", "width": 960, "height": 540,
+ "renderer": { "type": "pathTracer", "samples": 64, "bounces": 8, "denoise": true, "seed": 0, "maxSeconds": 120 } }
+```
+
+Every field after `type` is optional. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 240 (the job also keeps its own five minute deadline). `passes` and the other kinds are refused with it. The tracer loads in the job page on demand, uses four threads, and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG. A job that passes `maxSeconds` fails and writes no image.
+
## Controller API
This module provides persistent job records around a trusted render callback.
diff --git a/docs/parity.md b/docs/parity.md
index 18c9b08a..010c37ec 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
-| Rendering > Render Engines > Cycles | partial | No path tracer. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; it is code only (no recipe field, no GLB export, no reflection probes, no spot or area lights, no baked AO). On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 |
+| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It does not trace volume fog, normal maps or translucent leaves, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; it is code only (no recipe field, no GLB export, no reflection probes, no spot or area lights, no baked AO). On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [lit-interior scene](../bench/reference/scenes.js) | #55, #57 |
| Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | |
| Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
new file mode 100644
index 00000000..45d0d31c
--- /dev/null
+++ b/docs/path-tracer.md
@@ -0,0 +1,59 @@
+# Path tracer
+
+`67js/addons/path-tracer` draws one still the way an offline renderer does: it follows light paths on the CPU instead of rasterizing. It is in the current source and not yet published. It loads only when a render job asks for it, so a normal scene pays nothing (issue #57).
+
+```js
+import { renderPathTracedImage } from '67js/addons/path-tracer';
+
+const { rgba, linear, report } = await renderPathTracedImage(
+ { parts, environment, camera }, // the same objects the rasterizer takes
+ { width: 960, height: 540, samples: 64, bounces: 8, seed: 0, denoise: true, threads: 4, maxSeconds: 300 },
+);
+```
+
+From an agent, submit an `image` render job with `settings.renderer` (see [render jobs](agent-render-jobs.md#path-tracer)).
+
+## What it draws
+
+Unidirectional path tracing against the triangle BVH that the [light bake](light-bake.md) uses, with next-event estimation for every light and the environment map drawn by importance, then a wavelet denoiser.
+
+- Surfaces: diffuse, GGX specular with metals, clear coat, glass (`transmission`, `ior`, rough glass), emission, image maps (`map`, with `alphaMode: "mask"` cutouts) and vertex colour. Skinned parts are drawn at their current pose.
+- Lights: the sun (`keyColor`, `lightDirection`, as a 1 degree disk), point lights with a radius, spot lights with a soft cone, rectangular area lights, and the environment map with its rotation. All of them cast soft shadows, whatever their `castShadow` says, as in Cycles.
+- Light that bounces between surfaces, and the sky seen in mirrors and through glass.
+
+## What it does not draw
+
+`report.ignored` lists the ones this scene asks for.
+
+- Volume fog (`volumeFog`), and the procedural sky when there is no environment map (the sky is black).
+- Normal maps, metallic-roughness maps, occlusion maps and emissive maps. Material graphs and patterns are drawn through the colour map they bake.
+- Translucent leaves (foliage looks darker than in the rasterizer), liquids, foam and blended transparency (traced as plain or opaque surfaces).
+- Lights seen in mirrors (area lights and spot lights are lit but not visible), caustics, subsurface scattering, motion blur, depth of field, bloom and colour grade.
+- Multiple-scattering GGX: rough metal is a little darker than in Blender.
+
+## Limits
+
+| Option | Default | Range | Meaning |
+| --- | --- | --- | --- |
+| `width`, `height` | 960, 540 | 16 to 4096 | Output size, at most 2,073,600 pixels. |
+| `samples` | 64 | 1 to 1024 | Paths per pixel. |
+| `bounces` | 8 | 1 to 16 | Reflections followed by each path. |
+| `seed` | 0 | 0 to 2147483647 | Changes the noise. |
+| `threads` | 4 | 1 to 8 | Module workers; the pixels are the same for any count. Without `Worker` it runs on one thread. |
+| `maxSeconds` | 300 | 1 to 1800 | Wall-clock limit. Passing it throws; there is never a partial image. |
+| `denoise` | true | boolean | Filters the light with normal, depth and noise guides. |
+| `fireflyClamp` | 20 | 1 to 1000 | Largest radiance one bounce may add to a sample. |
+
+Also checked before any ray is traced: samples times pixels times bounces at most 4 billion, 400,000 triangles, 1,024 parts, 32 lights, and finite numbers and in-range indices in every part. A render job limits `maxSeconds` to 240 so that it ends before the job deadline.
+
+The same scene and options give the same bytes. Random numbers come from a hash of the pixel, the sample and the seed, never from `Math.random` or the clock, and a pixel does not depend on which thread drew it.
+
+## Choosing CPU
+
+A WebGL2 fragment tracer was not built. The WebGPU decision (issue #56) set no WebGPU backend for now, and a fragment path would need the BVH and every material in textures. The CPU path reuses `src/triangle-bvh.js` and `src/ray-query.js` as they are, runs in the job page next to the scene, and needs no GPU: it measured 25 to 238 seconds for a 960 by 540 still at 32 samples on a Ryzen 5 5600X with four threads, while another session also loaded the machine (table in `bench/reference/README.md`).
+
+## Measured
+
+`npm run reference -- --path-tracer [--samples 32]` draws each reference scene with the tracer and scores it against the Cycles render of the same scene with FLIP (`bench/reference/path-tracer.json`). It leaves `baseline.json` and `images/` alone, and it needs the Cycles renders of an earlier `npm run reference`.
+
+Scores and times are in the table of `bench/reference/README.md`. Cycles used 256 samples with a denoiser, and the tracer 32 samples with its own filter, so the remaining gap is partly noise and partly the differences listed above.
diff --git a/package.json b/package.json
index 845b0aad..ed06e302 100644
--- a/package.json
+++ b/package.json
@@ -71,6 +71,7 @@
"./addons/grass": "./build/grass.js",
"./addons/clutter": "./build/clutter.js",
"./addons/light-bake": "./build/light-bake.js",
+ "./addons/path-tracer": "./build/path-tracer.js",
"./addons/texture-set": "./build/texture-set.js",
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
@@ -103,6 +104,7 @@
"smoke:agent-assets": "node scripts/smoke-agent-assets.mjs",
"smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",
"smoke:render-passes": "node scripts/smoke-render-passes.mjs",
+ "smoke:path-tracer": "node scripts/smoke-path-tracer.mjs",
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
"smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:agent-cloth": "node scripts/smoke-agent-cloth.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 7a57d134..d245ad37 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -441,6 +441,28 @@ window.__agentPreview = {
const info = renderInfo(record.renderer);
return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;
},
+ // Offline path trace of the scene at one instant. The tracer loads here, on first use, and not with the preview.
+ async pathTrace({ sessionId, animation, motionTime, options }) {
+ const record = requireSession(sessionId);
+ if (record.asset && (animation !== undefined || motionTime !== undefined)) {
+ record.scene.sampleFrame({ ...(animation === undefined ? {} : { animation }),
+ ...(motionTime === undefined ? {} : { motionTime }) });
+ } else if (motionTime !== undefined) {
+ record.scene.sampleMotion(motionTime);
+ }
+ const { renderPathTracedImage } = await import('../src/path-tracer.js');
+ const environment = record.scene.environment;
+ const result = await renderPathTracedImage({
+ parts: record.scene.parts,
+ environment: { ...environment, map: agentEnvironmentMap(environment) },
+ camera: record.scene.camera,
+ }, options);
+ const traced = document.createElement('canvas');
+ traced.width = result.width;
+ traced.height = result.height;
+ traced.getContext('2d').putImageData(new ImageData(result.rgba, result.width, result.height), 0, 0);
+ return { data: traced.toDataURL('image/png').split(',')[1], report: result.report };
+ },
create(input) {
if (active) throw new Error('Dispose the current scene before creating another.');
return afterMeshBooleans(input.recipe, () => createPreview(createAgentScene(input.recipe), input));
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 6a0b89c4..84b4c036 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -3,6 +3,7 @@ import { randomUUID, createHash } from 'node:crypto';
import { isAbsolute, join, resolve } from 'node:path';
import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+import { PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';
const UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
const STATES = ['queued', 'running', 'finalizing', 'completed', 'cancelling', 'cancelled', 'failed', 'interrupted'];
@@ -57,7 +58,7 @@ function jsonCopy(value, maximum = MAXIMUM_JSON_BYTES) {
}
function settingsFrom(input, clips, recipe) {
- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes'], 'settings');
+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer'], 'settings');
if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');
const width = boundedNumber(input.width, 64, 1024, 'width', true);
const height = boundedNumber(input.height, 64, 1024, 'height', true);
@@ -68,6 +69,7 @@ function settingsFrom(input, clips, recipe) {
if (frameCount > 900) throw new RangeError('Job exceeds 900 frames.');
const result = { kind: input.kind, width, height, fps, duration, frameCount };
if (input.passes !== undefined) result.passes = passesFrom(input.passes, input.kind);
+ if (input.renderer !== undefined) result.renderer = rendererFrom(input.renderer, input.kind, input.passes);
const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;
if (input.motion !== undefined) {
objectKeys(input.motion, ['start'], 'motion');
@@ -102,6 +104,20 @@ function settingsFrom(input, clips, recipe) {
return result;
}
+function rendererFrom(renderer, kind, passes) {
+ objectKeys(renderer, ['type', 'samples', 'bounces', 'denoise', 'seed', 'maxSeconds'], 'renderer');
+ if (renderer.type !== 'pathTracer') throw new TypeError('renderer.type must be pathTracer.');
+ if (kind !== 'image') throw new RangeError('The path tracer renders one image: use kind image.');
+ if (passes !== undefined) throw new RangeError('The path tracer writes the lit image only: leave passes out.');
+ if (renderer.denoise !== undefined && typeof renderer.denoise !== 'boolean') throw new TypeError('renderer.denoise must be a boolean.');
+ const result = { type: 'pathTracer', denoise: renderer.denoise ?? true };
+ for (const name of Object.keys(PATH_TRACER_JOB_LIMITS)) {
+ const { minimum, maximum, default: fallback } = PATH_TRACER_JOB_LIMITS[name];
+ result[name] = boundedNumber(renderer[name] ?? fallback, minimum, maximum, `renderer ${name}`, name !== 'maxSeconds');
+ }
+ return result;
+}
+
function passesFrom(passes, kind) {
if (kind === 'video') throw new RangeError('Render passes need kind image or stills; a video holds the lit image only.');
if (!Array.isArray(passes) || passes.length < 1 || passes.length > RENDER_PASS_NAMES.length) throw new TypeError(`passes must list 1 to ${RENDER_PASS_NAMES.length} pass names.`);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index f4b82d59..6525269b 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -7,6 +7,7 @@ import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';
+import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-jobs.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
@@ -19,6 +20,8 @@ const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAXIMUM_IMAGE_BYTES = 1024 * 1024;
// The object ID pass lists the part behind each ID in the job metrics; longer lists are cut and flagged.
const MAXIMUM_OBJECT_NAMES = 1000;
+// A path trace shares the machine with the person using it, so it takes half of the eight-thread ceiling.
+const PATH_TRACER_THREADS = 4;
const MAXIMUM_QUEUED_CALLS = 16;
const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;
const MAXIMUM_KEPT_GLBS = 8;
@@ -326,6 +329,19 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
...(settings.motion ? { motionTime: settings.motion.start + elapsed } : {}),
...(settings.animation ? { animation: { clip: settings.animation.clip, time: settings.animation.start + elapsed } } : {}) };
const renderStarted = performance.now();
+ if (settings.renderer) {
+ const traced = await jobPage.evaluate(input => window.__agentPreview.pathTrace(input), { ...frameInput, options: { width, height, ...settings.renderer, threads: PATH_TRACER_THREADS } });
+ metrics.renderSeconds += (performance.now() - renderStarted) / 1000;
+ metrics.width = width;
+ metrics.height = height;
+ metrics.pathTracer = traced.report;
+ const tracedBytes = Buffer.from(traced.data, 'base64');
+ if (tracedBytes.length > MAXIMUM_IMAGE_BYTES) throw new Error('Path traced image exceeded 1 MiB.');
+ await writeFile(join(directory, 'render.png.partial'), tracedBytes, { flag: 'wx' });
+ artifacts.push({ temporary: 'render.png.partial', filename: 'render.png', mimeType: 'image/png' });
+ await progress({ frames: 1, maximumPendingFrames: 1 });
+ continue;
+ }
const rendered = await jobPage.evaluate(input => window.__agentPreview.frame(input), frameInput);
metrics.renderSeconds += (performance.now() - renderStarted) / 1000;
if (backend === 'cpu' && !/swiftshader/i.test(rendered.graphics)) throw new Error('CPU job did not select SwiftShader.');
@@ -421,7 +437,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
maximumVertices: 250000, maximumParts: 4096, maximumTexturePixels: 4194304, maximumJoints: 1024, maximumClips: 256,
commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
},
- jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, maximumActiveJobs: 1,
+ jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1,
maximumDuration: 30, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
encoder: 'CPU H.264', audio: false, previewSuspendedDuringJob: true,
glbExport: { maximumBytes: MAXIMUM_GLB_BYTES, maximumKept: MAXIMUM_KEPT_GLBS, maximumTextureSize: 4096 },
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 997c9e8d..a2765cf0 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -568,6 +568,7 @@ const renderSettings = z.strictObject({
animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),
motion: z.strictObject({ start: z.number().min(0).max(3600).optional() }).optional(),
rendererTime: z.strictObject({ start: z.number().min(0).max(3600).optional(), rate: z.number().min(-16).max(16).optional() }).optional(),
+ renderer: z.strictObject({ type: z.literal('pathTracer'), samples: z.number().int().optional(), bounces: z.number().int().optional(), denoise: z.boolean().optional(), seed: z.number().int().optional(), maxSeconds: z.number().optional() }).optional().describe('image only: offline path tracer instead of the rasterizer; limits and what it skips are in scene_capabilities pathTracer.'),
passes: z.array(z.enum(RENDER_PASS_NAMES)).min(1).max(RENDER_PASS_NAMES.length).optional().describe('image and stills only: also write raw PNGs per frame for these passes; opaque geometry only.'),
}).describe('Immutable snapshot render: one PNG, eight evenly spaced PNGs, or CPU H.264 MP4. Video dimensions must be even. Defaults: 24 fps, one second. Use motion.start for authored recipe tracks, animation for an imported clip, or both to layer them. Omitted motion holds time zero. Nonlooping samples must fit the authored duration.');
const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index e116f161..c6e4b24e 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -43,7 +43,7 @@ const sourceDocuments = [
'retarget.md',
'skeleton-pose.md',
'vehicle.md',
- 'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md',
+ 'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
diff --git a/scripts/smoke-path-tracer.mjs b/scripts/smoke-path-tracer.mjs
new file mode 100644
index 00000000..1f6e7214
--- /dev/null
+++ b/scripts/smoke-path-tracer.mjs
@@ -0,0 +1,106 @@
+// Proves the path tracer through the real MCP runtime: an image job with settings.renderer writes a PNG that differs
+// from the rasterizer's, the same recipe and seed give the same bytes, another seed does not, bad settings are refused,
+// and a job that passes maxSeconds fails without writing an image.
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-path-tracer-'));
+const jobs = join(directory, 'jobs');
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', 'cpu', '--memory', '128', '--jobs', jobs], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-path-tracer-proof', version: '1' });
+const SIZE = 96;
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ return client.callTool({ name, arguments: argumentsValue }, { timeout });
+}
+
+async function finished(jobId) {
+ const deadline = Date.now() + 120000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(200);
+ }
+ throw new Error('Job did not finish within 120 seconds.');
+}
+
+async function submit(sessionId, settings) {
+ return call('scene_render_submit', { sessionId, expectedRevision: 0, settings });
+}
+
+async function renderedBytes(sessionId, settings) {
+ const submitted = await submit(sessionId, settings);
+ assert.equal(submitted.isError, undefined, submitted.content?.[0]?.text);
+ const record = await finished(submitted.structuredContent.jobId);
+ assert.equal(record.state, 'completed', JSON.stringify(record));
+ const result = (await call('scene_render_result', { jobId: submitted.structuredContent.jobId })).structuredContent;
+ const bytes = await readFile(result.artifacts[0].path);
+ assert.equal(createHash('sha256').update(bytes).digest('hex'), result.artifacts[0].sha256);
+ await call('scene_render_release', { jobId: submitted.structuredContent.jobId });
+ return { bytes, metrics: result.metrics ?? record.metrics };
+}
+
+const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments: 24, rings: 16 }],
+ materials: [
+ { id: 'floor', color: [0.5, 0.5, 0.5], roughness: 0.8 },
+ { id: 'glass', color: [1, 1, 1], roughness: 0.05, transmission: 1 },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'box', material: 'floor', translation: [0, -0.1, 0], scale: [12, 0.2, 12] },
+ { id: 'ball', geometry: 'sphere', material: 'glass', translation: [0, 0.5, 0], scale: [1, 1, 1] },
+ ],
+ camera: { eye: [0, 1.6, 6], target: [0, 0.5, 0], fov: 40 },
+};
+
+try {
+ await client.connect(transport);
+ const created = (await call('scene_create', { recipe }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const base = { kind: 'image', width: SIZE, height: SIZE };
+ const tracer = { type: 'pathTracer', samples: 4, bounces: 4 };
+
+ const first = await renderedBytes(sessionId, { ...base, renderer: tracer });
+ assert.equal(first.metrics.pathTracer.samples, 4);
+ assert.equal(first.metrics.pathTracer.threads, 4);
+ const second = await renderedBytes(sessionId, { ...base, renderer: tracer });
+ assert.deepEqual(second.bytes, first.bytes, 'The same recipe and seed must give the same PNG.');
+ const reseeded = await renderedBytes(sessionId, { ...base, renderer: { ...tracer, seed: 5 } });
+ assert.notDeepEqual(reseeded.bytes, first.bytes, 'Another seed must change the noise.');
+ const rasterized = await renderedBytes(sessionId, base);
+ assert.notDeepEqual(rasterized.bytes, first.bytes, 'The path tracer must not return the rasterizer image.');
+
+ for (const [settings, message] of [
+ [{ ...base, renderer: { ...tracer, samples: 99999 } }, /samples/],
+ [{ ...base, renderer: { ...tracer, extra: 1 } }, /extra|Unrecognized|Unknown/],
+ [{ ...base, renderer: tracer, passes: ['albedo'] }, /passes/],
+ [{ ...base, kind: 'stills', renderer: tracer }, /image/],
+ ]) {
+ const refused = await submit(sessionId, settings);
+ assert.equal(refused.isError, true, JSON.stringify(settings));
+ assert.match(refused.content[0].text, message);
+ }
+
+ const slow = await submit(sessionId, { kind: 'image', width: 512, height: 512, renderer: { type: 'pathTracer', samples: 1024, maxSeconds: 1 } });
+ assert.equal(slow.isError, undefined, slow.content?.[0]?.text);
+ const slowRecord = await finished(slow.structuredContent.jobId);
+ assert.equal(slowRecord.state, 'failed', 'A job past maxSeconds must fail.');
+ console.log(`path tracer smoke passed: ${first.bytes.length} byte PNG in ${first.metrics.pathTracer.seconds.toFixed(1)} s on ${first.metrics.pathTracer.threads} threads`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close();
+}
diff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.md
index 47ee5420..c4d3a880 100644
--- a/skills/render-67js-media/SKILL.md
+++ b/skills/render-67js-media/SKILL.md
@@ -16,6 +16,8 @@ For procedural motion, read `docs/agent-motion.md` and select `settings.motion.s
For imported character motion from `0.8.0`, read `docs/agent-character-motion.md`. Use independent `settings.animation` and `settings.motion` clocks.
+For a still that must look like Blender's Cycles (glass, soft indirect light, many lights), read `docs/path-tracer.md` and submit an `image` job with `settings.renderer: { type: "pathTracer" }`. It is slow, bounded and offline: read `scene_capabilities` `pathTracer` for its limits and what it skips, and keep rasterizer jobs for video and passes.
+
## Choose and render
1. Check the available GPU memory before a GPU job on a shared machine.
diff --git a/src/light-bake.js b/src/light-bake.js
index 71c72ee2..94333e17 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -1,5 +1,6 @@
-import { buildTriangleBvh, rayBoxDistance, traverseTriangleBvh } from './triangle-bvh.js';
-import { intersectRayTriangle, readTriangle } from './triangle-math.js';
+import { buildTriangleBvh } from './triangle-bvh.js';
+import { readTriangle } from './triangle-math.js';
+import { createTracer, pointLightFalloff } from './ray-query.js';
import { extractRender } from './mesh-render.js';
import { meshFromGeometry } from './mesh-convert.js';
import { unwrapUv } from './mesh-uv.js';
@@ -152,38 +153,6 @@ function sceneScale(positions) {
return Math.max(largest, 1e-3);
}
-/** Ray queries with preallocated state: the traversal callbacks are built once, not once per ray. */
-function createTracer(world) {
- const origin = new Float64Array(3);
- const direction = new Float64Array(3);
- const triangle = new Float64Array(9);
- const state = { nearestDistance: Infinity, nearestTriangle: -1, stopAtAnyHit: false };
- const scoreBounds = (bounds, offset) => rayBoxDistance(origin, direction, bounds, offset);
- const shouldVisit = score => score < state.nearestDistance;
- const visitTriangle = triangleId => {
- readTriangle(world.positions, world.indices, triangleId, triangle);
- const distance = intersectRayTriangle(origin, direction, triangle);
- if (distance < 0 || distance >= state.nearestDistance) return false;
- state.nearestDistance = distance;
- state.nearestTriangle = triangleId;
- return state.stopAtAnyHit;
- };
- function trace(ox, oy, oz, dx, dy, dz, limit, stopAtAnyHit) {
- origin[0] = ox;
- origin[1] = oy;
- origin[2] = oz;
- direction[0] = dx;
- direction[1] = dy;
- direction[2] = dz;
- state.nearestDistance = limit;
- state.nearestTriangle = -1;
- state.stopAtAnyHit = stopAtAnyHit;
- traverseTriangleBvh(world.bvh, scoreBounds, shouldVisit, visitTriangle);
- return state;
- }
- return { trace };
-}
-
/** Integer hash to [0, 1): the only source of randomness, so a bake repeats exactly. */
function hashUnit(first, second, third) {
let value = Math.imul(first ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(second + 0x7f4a7c15, 0xc2b2ae35) ^ Math.imul(third + 0x165667b1, 0x27d4eb2f);
@@ -228,16 +197,6 @@ function cosineDirection(normal, firstUnit, secondUnit, out) {
out[2] = tangentZ * localX + bitangentZ * localY + normal[2] * localZ;
}
-function pointLightFalloff(distanceSquared, light) {
- let cutoff = 1;
- if (light.range > 0) {
- const ratio = distanceSquared / (light.range * light.range);
- const fade = Math.max(1 - ratio * ratio, 0);
- cutoff = fade * fade;
- }
- return cutoff / Math.max(distanceSquared, light.radius * light.radius);
-}
-
/**
* Builds the function that returns the irradiance (light power per area, before the albedo and 1/pi of a diffuse
* surface) of the direct lights at a point, with shadow rays against the world.
diff --git a/src/path-tracer-capabilities.js b/src/path-tracer-capabilities.js
new file mode 100644
index 00000000..1a0b2b40
--- /dev/null
+++ b/src/path-tracer-capabilities.js
@@ -0,0 +1,16 @@
+// The offline path tracer that a render job selects with settings.renderer, as plain data for the MCP server. The code
+// and its own bounds are src/path-tracer.js; tests/path-tracer.test.js keeps these numbers equal to PATH_TRACER_LIMITS
+// there. It lives apart from agent-scene-capabilities.js so the agent scene bundle does not carry it. maxSeconds stops
+// below the job deadline.
+export const PATH_TRACER_JOB_LIMITS = Object.freeze({
+ samples: Object.freeze({ minimum: 1, maximum: 1024, default: 64 }),
+ bounces: Object.freeze({ minimum: 1, maximum: 16, default: 8 }),
+ maxSeconds: Object.freeze({ minimum: 1, maximum: 240, default: 120 }),
+ seed: Object.freeze({ minimum: 0, maximum: 2147483647, default: 0 }),
+});
+
+export const PATH_TRACER_CAPABILITIES = Object.freeze({
+ setting: 'settings.renderer { type: "pathTracer", samples, bounces, denoise, seed, maxSeconds }; image jobs only, no passes. Past maxSeconds the job fails.',
+ skips: 'volume fog, normal and roughness maps, translucent leaves, liquids, caustics, depth of field, bloom; the job result lists what the scene asked for.',
+ limits: PATH_TRACER_JOB_LIMITS,
+});
diff --git a/src/path-tracer-denoise.js b/src/path-tracer-denoise.js
new file mode 100644
index 00000000..eaa19b59
--- /dev/null
+++ b/src/path-tracer-denoise.js
@@ -0,0 +1,123 @@
+// An edge-avoiding wavelet filter (a-trous, after the SVGF paper without its temporal part) for path traced stills.
+// It filters the light and leaves the texture alone: colour is divided by the first-hit albedo first, and the albedo
+// is multiplied back at the end. Normals, depth and the per-pixel noise estimate stop it at edges and shadows.
+
+const PASS_STEPS = [1, 2, 4, 8, 16];
+const KERNEL = [1 / 16, 1 / 4, 3 / 8, 1 / 4, 1 / 16];
+const NORMAL_POWER = 64;
+const LUMINANCE_SIGMA = 3;
+const ALBEDO_FLOOR = 0.02;
+
+function luminanceOf(buffer, index) {
+ return 0.2126 * buffer[index * 3] + 0.7152 * buffer[index * 3 + 1] + 0.0722 * buffer[index * 3 + 2];
+}
+
+function demodulate(color, albedo, pixelCount) {
+ const light = new Float32Array(color.length);
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ for (let channel = 0; channel < 3; channel++) {
+ light[pixel * 3 + channel] = color[pixel * 3 + channel] / Math.max(albedo[pixel * 3 + channel], ALBEDO_FLOOR);
+ }
+ }
+ return light;
+}
+
+/** The noise of each pixel's mean, as luminance variance in the light (albedo divided out), smoothed over 3 by 3. */
+function smoothedVariance(variance, albedo, width, height) {
+ const scaled = new Float32Array(width * height);
+ for (let pixel = 0; pixel < scaled.length; pixel++) {
+ const brightness = Math.max(luminanceOf(albedo, pixel), ALBEDO_FLOOR);
+ scaled[pixel] = variance[pixel] / (brightness * brightness);
+ }
+ const smoothed = new Float32Array(scaled.length);
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width; column++) {
+ let sum = 0;
+ let count = 0;
+ for (let rowOffset = -1; rowOffset <= 1; rowOffset++) {
+ for (let columnOffset = -1; columnOffset <= 1; columnOffset++) {
+ const neighborRow = row + rowOffset;
+ const neighborColumn = column + columnOffset;
+ if (neighborRow < 0 || neighborRow >= height || neighborColumn < 0 || neighborColumn >= width) continue;
+ sum += scaled[neighborRow * width + neighborColumn];
+ count++;
+ }
+ }
+ smoothed[row * width + column] = sum / count;
+ }
+ }
+ return smoothed;
+}
+
+function depthGradient(depth, width, height, row, column) {
+ const left = depth[row * width + Math.max(column - 1, 0)];
+ const right = depth[row * width + Math.min(column + 1, width - 1)];
+ const above = depth[Math.max(row - 1, 0) * width + column];
+ const below = depth[Math.min(row + 1, height - 1) * width + column];
+ return [(right - left) / 2, (below - above) / 2];
+}
+
+function filterPass({ width, height, light, variance, normal, depth }, step, outputLight, outputVariance) {
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width; column++) {
+ const center = row * width + column;
+ const centerLuminance = luminanceOf(light, center);
+ const [gradientX, gradientY] = depthGradient(depth, width, height, row, column);
+ const luminanceScale = LUMINANCE_SIGMA * Math.sqrt(Math.max(variance[center], 0)) + 1e-4;
+ let weightSum = 0;
+ let squaredWeightSum = 0;
+ let varianceSum = 0;
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+ for (let kernelRow = -2; kernelRow <= 2; kernelRow++) {
+ const neighborRow = row + kernelRow * step;
+ if (neighborRow < 0 || neighborRow >= height) continue;
+ for (let kernelColumn = -2; kernelColumn <= 2; kernelColumn++) {
+ const neighborColumn = column + kernelColumn * step;
+ if (neighborColumn < 0 || neighborColumn >= width) continue;
+ const neighbor = neighborRow * width + neighborColumn;
+ const normalAgreement = Math.max(0, normal[center * 3] * normal[neighbor * 3] + normal[center * 3 + 1] * normal[neighbor * 3 + 1] + normal[center * 3 + 2] * normal[neighbor * 3 + 2]);
+ const depthTolerance = Math.abs(gradientX * kernelColumn * step) + Math.abs(gradientY * kernelRow * step) + 1e-3 * Math.abs(depth[center]) + 1e-5;
+ const depthWeight = Math.exp(-Math.abs(depth[center] - depth[neighbor]) / depthTolerance);
+ const luminanceWeight = Math.exp(-Math.abs(centerLuminance - luminanceOf(light, neighbor)) / luminanceScale);
+ const weight = KERNEL[kernelRow + 2] * KERNEL[kernelColumn + 2] * normalAgreement ** NORMAL_POWER * depthWeight * luminanceWeight;
+ weightSum += weight;
+ squaredWeightSum += weight * weight;
+ varianceSum += weight * weight * variance[neighbor];
+ red += weight * light[neighbor * 3];
+ green += weight * light[neighbor * 3 + 1];
+ blue += weight * light[neighbor * 3 + 2];
+ }
+ }
+ outputLight[center * 3] = red / weightSum;
+ outputLight[center * 3 + 1] = green / weightSum;
+ outputLight[center * 3 + 2] = blue / weightSum;
+ outputVariance[center] = varianceSum / (weightSum * weightSum);
+ }
+ }
+}
+
+/**
+ * Filters a radiance image with the features gathered at each pixel's first hit. All buffers are row-major; colour,
+ * albedo and normal hold three floats per pixel, depth and variance one. Returns a new colour buffer.
+ */
+export function denoiseRadiance({ width, height, color, albedo, normal, depth, variance }) {
+ const pixelCount = width * height;
+ let light = demodulate(color, albedo, pixelCount);
+ let noise = smoothedVariance(variance, albedo, width, height);
+ let nextLight = new Float32Array(light.length);
+ let nextNoise = new Float32Array(noise.length);
+ for (const step of PASS_STEPS) {
+ filterPass({ width, height, light, variance: noise, normal, depth }, step, nextLight, nextNoise);
+ [light, nextLight] = [nextLight, light];
+ [noise, nextNoise] = [nextNoise, noise];
+ }
+ const result = new Float32Array(color.length);
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ for (let channel = 0; channel < 3; channel++) {
+ result[pixel * 3 + channel] = light[pixel * 3 + channel] * Math.max(albedo[pixel * 3 + channel], ALBEDO_FLOOR);
+ }
+ }
+ return result;
+}
diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.js
new file mode 100644
index 00000000..72393ef1
--- /dev/null
+++ b/src/path-tracer-scene.js
@@ -0,0 +1,247 @@
+import { buildTriangleBvh } from './triangle-bvh.js';
+import { createTracer } from './ray-query.js';
+
+// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs
+// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.
+
+export const MAX_TRACE_TRIANGLES = 400_000;
+export const MAX_TRACE_PARTS = 1024;
+export const MAX_TRACE_LIGHTS = 32;
+// A Blender sun of 1 degree, which is what the reference harness gives Cycles.
+export const SUN_ANGULAR_RADIUS = Math.PI / 360;
+
+const IDENTITY_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+const REPEAT_WRAP = 10497;
+
+function addWeightedTransform(output, offset, palette, joint, weight, x, y, z, translationWeight) {
+ const base = joint * 16;
+ output[offset] += weight * (palette[base] * x + palette[base + 4] * y + palette[base + 8] * z + palette[base + 12] * translationWeight);
+ output[offset + 1] += weight * (palette[base + 1] * x + palette[base + 5] * y + palette[base + 9] * z + palette[base + 13] * translationWeight);
+ output[offset + 2] += weight * (palette[base + 2] * x + palette[base + 6] * y + palette[base + 10] * z + palette[base + 14] * translationWeight);
+}
+
+/** The geometry of a skinned part at its current pose, as plain positions and normals. */
+export function skinnedGeometry(part) {
+ const { geometry, skin } = part;
+ const vertexCount = geometry.positions.length / 3;
+ const positions = new Float32Array(geometry.positions.length);
+ const normals = new Float32Array(geometry.normals.length);
+ const influenceCount = geometry.skinWeights.length / vertexCount;
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ const offset = vertex * 3;
+ for (let influence = 0; influence < influenceCount; influence++) {
+ const weight = geometry.skinWeights[vertex * influenceCount + influence];
+ if (weight === 0) continue;
+ const joint = geometry.skinIndices[vertex * influenceCount + influence];
+ addWeightedTransform(positions, offset, skin.jointMatrices, joint, weight, geometry.positions[offset], geometry.positions[offset + 1], geometry.positions[offset + 2], 1);
+ addWeightedTransform(normals, offset, skin.jointMatrices, joint, weight, geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2], 0);
+ }
+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]) || 1;
+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;
+ }
+ return { ...geometry, positions, normals };
+}
+
+/** Normal matrix (cofactors of the upper 3x3, signed so that mirrored parts keep outward normals), row major. */
+function normalMatrix(matrix) {
+ const [a, b, c, , d, e, f, , g, h, i] = matrix;
+ const cofactors = [
+ e * i - f * h, f * g - d * i, d * h - e * g,
+ c * h - b * i, a * i - c * g, b * g - a * h,
+ b * f - c * e, c * d - a * f, a * e - b * d,
+ ];
+ const sign = a * cofactors[0] + b * cofactors[1] + c * cofactors[2] < 0 ? -1 : 1;
+ return cofactors.map(value => value * sign);
+}
+
+function srgbToLinearTable() {
+ const table = new Float32Array(256);
+ for (let value = 0; value < 256; value++) {
+ const encoded = value / 255;
+ table[value] = encoded <= 0.04045 ? encoded / 12.92 : ((encoded + 0.055) / 1.055) ** 2.4;
+ }
+ return table;
+}
+
+const SRGB_TO_LINEAR = srgbToLinearTable();
+
+function resolveTexture(descriptor) {
+ const image = descriptor?.image;
+ if (!image?.data || !image.width || !image.height) return null;
+ return {
+ width: image.width,
+ height: image.height,
+ data: image.data,
+ colorLookup: descriptor.colorSpace === 'linear' ? null : SRGB_TO_LINEAR,
+ repeat: descriptor.wrapS === REPEAT_WRAP,
+ };
+}
+
+function resolveMaterial(material) {
+ const emissionColor = material.emissiveColor ?? material.color;
+ const emissionStrength = material.emission ?? 0;
+ return {
+ color: material.color ?? [1, 1, 1],
+ metallic: material.metallic ?? 0,
+ roughness: material.roughness ?? 0.5,
+ emission: emissionColor.map(channel => channel * emissionStrength),
+ clearcoat: material.clearcoat ?? 0,
+ clearcoatRoughness: material.clearcoatRoughness ?? 0,
+ transmission: material.transmission ?? 0,
+ ior: material.ior ?? 1.5,
+ texture: resolveTexture(material.map),
+ alphaCutoff: material.alphaMode === 'mask' ? material.alphaCutoff ?? 0.5 : 0,
+ };
+}
+
+function requireFiniteNumbers(values, expectedLength, label) {
+ if (!values || (expectedLength !== undefined && values.length !== expectedLength)) throw new TypeError(`${label} must hold ${expectedLength} numbers.`);
+ for (let index = 0; index < values.length; index++) {
+ if (!Number.isFinite(values[index])) throw new RangeError(`${label} must be finite numbers.`);
+ }
+}
+
+function validatePart(part, geometry) {
+ const label = `Part ${part.name ?? ''}`.trim();
+ requireFiniteNumbers(part.matrix ?? IDENTITY_MATRIX, 16, `${label} matrix`);
+ requireFiniteNumbers(geometry.positions, undefined, `${label} positions`);
+ if (geometry.positions.length % 3 !== 0 || geometry.indices.length % 3 !== 0) throw new RangeError(`${label} positions and indices must come in threes.`);
+ const vertexCount = geometry.positions.length / 3;
+ if (geometry.normals?.length !== geometry.positions.length) throw new RangeError(`${label} needs one normal for every position.`);
+ requireFiniteNumbers(geometry.normals, undefined, `${label} normals`);
+ for (let slot = 0; slot < geometry.indices.length; slot++) {
+ if (!(geometry.indices[slot] < vertexCount)) throw new RangeError(`${label} has an index past its last vertex.`);
+ }
+ if (geometry.uvs && geometry.uvs.length !== vertexCount * 2) throw new RangeError(`${label} needs one UV pair for every position.`);
+ if (geometry.colors && geometry.colors.length !== vertexCount * 3) throw new RangeError(`${label} needs one colour for every position.`);
+}
+
+function flattenParts(parts) {
+ let vertexTotal = 0;
+ let indexTotal = 0;
+ const geometries = parts.map(part => (part.skin ? skinnedGeometry(part) : part.geometry));
+ parts.forEach((part, index) => validatePart(part, geometries[index]));
+ for (const geometry of geometries) {
+ vertexTotal += geometry.positions.length / 3;
+ indexTotal += geometry.indices.length;
+ }
+ if (indexTotal / 3 > MAX_TRACE_TRIANGLES) throw new RangeError(`A path trace takes at most ${MAX_TRACE_TRIANGLES} triangles in total.`);
+ const world = {
+ positions: new Float32Array(vertexTotal * 3),
+ normals: new Float32Array(vertexTotal * 3),
+ uvs: new Float32Array(vertexTotal * 2),
+ colors: new Float32Array(vertexTotal * 3).fill(1),
+ indices: new Uint32Array(indexTotal),
+ triangleMaterial: new Uint32Array(indexTotal / 3),
+ };
+ let vertexOffset = 0;
+ let triangleOffset = 0;
+ parts.forEach((part, partIndex) => {
+ const geometry = geometries[partIndex];
+ const matrix = part.matrix ?? IDENTITY_MATRIX;
+ const normals = normalMatrix(matrix);
+ const vertexCount = geometry.positions.length / 3;
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ const x = geometry.positions[vertex * 3];
+ const y = geometry.positions[vertex * 3 + 1];
+ const z = geometry.positions[vertex * 3 + 2];
+ const target = (vertexOffset + vertex) * 3;
+ world.positions[target] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];
+ world.positions[target + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];
+ world.positions[target + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];
+ const normalX = geometry.normals[vertex * 3];
+ const normalY = geometry.normals[vertex * 3 + 1];
+ const normalZ = geometry.normals[vertex * 3 + 2];
+ const worldX = normals[0] * normalX + normals[3] * normalY + normals[6] * normalZ;
+ const worldY = normals[1] * normalX + normals[4] * normalY + normals[7] * normalZ;
+ const worldZ = normals[2] * normalX + normals[5] * normalY + normals[8] * normalZ;
+ const length = Math.hypot(worldX, worldY, worldZ) || 1;
+ world.normals[target] = worldX / length;
+ world.normals[target + 1] = worldY / length;
+ world.normals[target + 2] = worldZ / length;
+ }
+ if (geometry.uvs) world.uvs.set(geometry.uvs, (vertexOffset) * 2);
+ if (geometry.colors) world.colors.set(geometry.colors, vertexOffset * 3);
+ for (let slot = 0; slot < geometry.indices.length; slot++) world.indices[triangleOffset * 3 + slot] = geometry.indices[slot] + vertexOffset;
+ world.triangleMaterial.fill(partIndex, triangleOffset, triangleOffset + geometry.indices.length / 3);
+ vertexOffset += vertexCount;
+ triangleOffset += geometry.indices.length / 3;
+ });
+ return world;
+}
+
+function normalized(vector) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]) || 1;
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+function resolveLights(environment) {
+ const sunPower = Math.max(...(environment.keyColor ?? [0, 0, 0]));
+ const lightCount = (environment.pointLights?.length ?? 0) + (environment.spotLights?.length ?? 0) + (environment.areaLights?.length ?? 0);
+ if (lightCount > MAX_TRACE_LIGHTS) throw new RangeError(`A path trace takes at most ${MAX_TRACE_LIGHTS} point, spot and area lights.`);
+ return {
+ sun: sunPower > 0 ? { direction: normalized(environment.lightDirection ?? [0, 1, 0]), color: environment.keyColor } : null,
+ points: (environment.pointLights ?? []).map(light => ({ position: light.position, color: light.color, intensity: light.intensity, radius: light.radius ?? 0, range: light.range ?? 0 })),
+ spots: (environment.spotLights ?? []).map(light => ({
+ position: light.position, color: light.color, intensity: light.intensity, radius: light.radius ?? 0, range: light.range ?? 0,
+ direction: normalized(light.direction),
+ cosineHalfAngle: Math.cos(light.angle),
+ blend: (1 - Math.cos(light.angle)) * (light.penumbra ?? 0),
+ })),
+ areas: (environment.areaLights ?? []).map(light => {
+ const normal = normalized(light.direction);
+ const guide = normalized(light.up ?? [0, 1, 0]);
+ const across = normalized([guide[1] * normal[2] - guide[2] * normal[1], guide[2] * normal[0] - guide[0] * normal[2], guide[0] * normal[1] - guide[1] * normal[0]]);
+ const along = [normal[1] * across[2] - normal[2] * across[1], normal[2] * across[0] - normal[0] * across[2], normal[0] * across[1] - normal[1] * across[0]];
+ return { position: light.position, color: light.color, intensity: light.intensity, width: light.width, height: light.height, normal, across, along };
+ }),
+ };
+}
+
+/**
+ * The environment map as radiance lookups plus a luminance-weighted table, so a direction can be drawn in proportion
+ * to the light it brings. `pdf` is per steradian.
+ */
+function resolveEnvironment(map) {
+ if (!map) return null;
+ const { width, height, channels, data, intensity, rotation } = map;
+ const cosine = Math.cos(rotation);
+ const sine = Math.sin(rotation);
+ const rowCumulative = new Float64Array(height);
+ const pixelCumulative = new Float64Array(width * height);
+ let total = 0;
+ for (let row = 0; row < height; row++) {
+ const rowWeight = Math.sin(Math.PI * (row + 0.5) / height);
+ let rowTotal = 0;
+ for (let column = 0; column < width; column++) {
+ const base = (row * width + column) * channels;
+ rowTotal += (0.2126 * data[base] + 0.7152 * data[base + 1] + 0.0722 * data[base + 2] + 1e-6) * rowWeight;
+ pixelCumulative[row * width + column] = rowTotal;
+ }
+ total += rowTotal;
+ rowCumulative[row] = total;
+ }
+ return { width, height, channels, data, intensity, cosine, sine, rowCumulative, pixelCumulative, total };
+}
+
+/** A scene that crossed a thread boundary has lost its ray query function: build it again from the arrays. */
+export function attachTracer(scene) {
+ return { ...scene, tracer: createTracer({ positions: scene.positions, indices: scene.indices, bvh: scene.bvh }) };
+}
+
+export function buildTraceScene(parts, environment = {}) {
+ if (!Array.isArray(parts) || parts.length < 1 || parts.length > MAX_TRACE_PARTS) throw new RangeError(`A path trace takes 1 to ${MAX_TRACE_PARTS} parts.`);
+ const geometry = flattenParts(parts);
+ const bvh = buildTriangleBvh(geometry.positions, geometry.indices);
+ let extent = 1e-3;
+ for (let index = 0; index < geometry.positions.length; index++) extent = Math.max(extent, Math.abs(geometry.positions[index]));
+ return attachTracer({
+ ...geometry,
+ bvh,
+ materials: parts.map(part => resolveMaterial(part.material ?? {})),
+ lights: resolveLights(environment),
+ environment: resolveEnvironment(environment.map),
+ surfaceOffset: extent * 1e-5,
+ farDistance: extent * 1e4,
+ });
+}
diff --git a/src/path-tracer-shading.js b/src/path-tracer-shading.js
new file mode 100644
index 00000000..de8a487f
--- /dev/null
+++ b/src/path-tracer-shading.js
@@ -0,0 +1,375 @@
+// Surface and sky shading for the path tracer: the environment map as a light source, and a layered surface model
+// (diffuse, GGX specular with metals, a clear coat, and glass) that matches the Principled BSDF settings of a part.
+
+const TWO_PI = 2 * Math.PI;
+const MINIMUM_ALPHA = 1e-3;
+// Below this GGX width a lobe is a mirror for every practical purpose, so its normal is the surface normal.
+const MIRROR_ALPHA = 2e-3;
+const DIELECTRIC_COAT_REFLECTANCE = 0.04;
+
+export function luminance(red, green, blue) {
+ return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
+}
+
+// ---- Environment map ----
+
+/** Radiance toward `direction` (world space), bilinear, written into `out`. */
+export function environmentRadiance(environment, directionX, directionY, directionZ, out) {
+ const { width, height, channels, data, intensity, cosine, sine } = environment;
+ const mapX = cosine * directionX - sine * directionZ;
+ const mapZ = sine * directionX + cosine * directionZ;
+ const column = (Math.atan2(mapX, -mapZ) / TWO_PI + 0.5) * width - 0.5;
+ const row = Math.acos(Math.max(-1, Math.min(1, directionY))) / Math.PI * height - 0.5;
+ const left = Math.floor(column);
+ const top = Math.floor(row);
+ const shareX = column - left;
+ const shareY = row - top;
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ for (let corner = 0; corner < 4; corner++) {
+ const cornerColumn = ((left + (corner & 1)) % width + width) % width;
+ const cornerRow = Math.max(0, Math.min(height - 1, top + (corner >> 1)));
+ const weight = ((corner & 1) ? shareX : 1 - shareX) * ((corner >> 1) ? shareY : 1 - shareY);
+ const base = (cornerRow * width + cornerColumn) * channels;
+ out[0] += weight * data[base] * intensity;
+ out[1] += weight * data[base + 1] * intensity;
+ out[2] += weight * data[base + 2] * intensity;
+ }
+}
+
+function firstIndexAbove(cumulative, start, end, target) {
+ let low = start;
+ let high = end - 1;
+ while (low < high) {
+ const middle = (low + high) >> 1;
+ if (cumulative[middle] < target) low = middle + 1;
+ else high = middle;
+ }
+ return low;
+}
+
+/** Probability density, per steradian, of drawing the direction that falls in the map pixel of `direction`. */
+export function environmentPdf(environment, directionX, directionY, directionZ) {
+ const { width, height, channels, data, cosine, sine, total } = environment;
+ const mapX = cosine * directionX - sine * directionZ;
+ const mapZ = sine * directionX + cosine * directionZ;
+ const column = Math.min(width - 1, Math.floor((Math.atan2(mapX, -mapZ) / TWO_PI + 0.5) * width));
+ const polar = Math.acos(Math.max(-1, Math.min(1, directionY)));
+ const row = Math.min(height - 1, Math.floor(polar / Math.PI * height));
+ const sinePolar = Math.max(Math.sin(polar), 1e-6);
+ const rowWeight = Math.sin(Math.PI * (row + 0.5) / height);
+ const base = (row * width + column) * channels;
+ const weight = (luminance(data[base], data[base + 1], data[base + 2]) + 1e-6) * rowWeight;
+ return weight / total * width * height / (TWO_PI * Math.PI * sinePolar);
+}
+
+/** Draws a direction in proportion to the map's light; returns its pdf and writes the direction into `out`. */
+export function sampleEnvironment(environment, rowUnit, columnUnit, columnJitter, rowJitter, out) {
+ const { width, height, cosine, sine, rowCumulative, pixelCumulative, total } = environment;
+ const row = firstIndexAbove(rowCumulative, 0, height, rowUnit * total);
+ const rowBase = row * width;
+ const rowTotal = pixelCumulative[rowBase + width - 1];
+ const column = firstIndexAbove(pixelCumulative, rowBase, rowBase + width, columnUnit * rowTotal) - rowBase;
+ const polar = Math.PI * (row + rowJitter) / height;
+ const azimuth = ((column + columnJitter) / width - 0.5) * TWO_PI;
+ const sinePolar = Math.sin(polar);
+ const mapX = sinePolar * Math.sin(azimuth);
+ const mapZ = -sinePolar * Math.cos(azimuth);
+ out[0] = cosine * mapX + sine * mapZ;
+ out[1] = Math.cos(polar);
+ out[2] = -sine * mapX + cosine * mapZ;
+ return environmentPdf(environment, out[0], out[1], out[2]);
+}
+
+// ---- Microfacet pieces ----
+
+function ggxDistribution(alpha, cosineHalf) {
+ const alphaSquared = alpha * alpha;
+ const denominator = cosineHalf * cosineHalf * (alphaSquared - 1) + 1;
+ return alphaSquared / (Math.PI * denominator * denominator);
+}
+
+function smithMasking(alpha, cosine) {
+ const alphaSquared = alpha * alpha;
+ const cosineSquared = cosine * cosine;
+ return 2 * cosine / (cosine + Math.sqrt(alphaSquared + (1 - alphaSquared) * cosineSquared));
+}
+
+function schlick(reflectanceAtNormal, cosine) {
+ const weight = (1 - Math.min(Math.max(cosine, 0), 1)) ** 5;
+ return reflectanceAtNormal + (1 - reflectanceAtNormal) * weight;
+}
+
+/** Heitz's visible-normal sampling: a half vector in the local frame (z along the normal) for a view in the same frame. */
+function sampleVisibleNormal(viewX, viewY, viewZ, alpha, firstUnit, secondUnit, out) {
+ let stretchedX = alpha * viewX;
+ let stretchedY = alpha * viewY;
+ const stretchedZ = viewZ;
+ const stretchedLength = Math.hypot(stretchedX, stretchedY, stretchedZ);
+ stretchedX /= stretchedLength;
+ stretchedY /= stretchedLength;
+ const heightAxis = stretchedZ / stretchedLength;
+ const planeLength = Math.hypot(stretchedX, stretchedY);
+ const tangentX = planeLength > 0 ? -stretchedY / planeLength : 1;
+ const tangentY = planeLength > 0 ? stretchedX / planeLength : 0;
+ const bitangentX = -heightAxis * (planeLength > 0 ? stretchedX / planeLength : 0);
+ const bitangentY = -heightAxis * (planeLength > 0 ? stretchedY / planeLength : 0);
+ const bitangentZ = planeLength;
+ const radius = Math.sqrt(firstUnit);
+ const angle = TWO_PI * secondUnit;
+ const diskX = radius * Math.cos(angle);
+ let diskY = radius * Math.sin(angle);
+ const blend = 0.5 * (1 + heightAxis);
+ diskY = (1 - blend) * Math.sqrt(1 - diskX * diskX) + blend * diskY;
+ const lift = Math.sqrt(Math.max(0, 1 - diskX * diskX - diskY * diskY));
+ const normalX = diskX * tangentX + diskY * bitangentX + lift * stretchedX;
+ const normalY = diskX * tangentY + diskY * bitangentY + lift * stretchedY;
+ const normalZ = diskY * bitangentZ + lift * heightAxis;
+ const unstretchedX = alpha * normalX;
+ const unstretchedY = alpha * normalY;
+ const unstretchedZ = Math.max(0, normalZ);
+ const length = Math.hypot(unstretchedX, unstretchedY, unstretchedZ);
+ out[0] = unstretchedX / length;
+ out[1] = unstretchedY / length;
+ out[2] = unstretchedZ / length;
+}
+
+export function roughnessToAlpha(roughness) {
+ return Math.max(roughness * roughness, MINIMUM_ALPHA);
+}
+
+// ---- Frames ----
+
+/** Fills `frame` with an orthonormal basis around `normal`: tangent, bitangent, normal. */
+export function buildFrame(normal, frame) {
+ const helperIsX = Math.abs(normal[0]) < 0.9;
+ const helperX = helperIsX ? 1 : 0;
+ const helperY = helperIsX ? 0 : 1;
+ let tangentX = normal[1] * 0 - normal[2] * helperY;
+ let tangentY = normal[2] * helperX - normal[0] * 0;
+ let tangentZ = normal[0] * helperY - normal[1] * helperX;
+ const tangentLength = Math.hypot(tangentX, tangentY, tangentZ);
+ tangentX /= tangentLength;
+ tangentY /= tangentLength;
+ tangentZ /= tangentLength;
+ frame[0] = tangentX;
+ frame[1] = tangentY;
+ frame[2] = tangentZ;
+ frame[3] = normal[1] * tangentZ - normal[2] * tangentY;
+ frame[4] = normal[2] * tangentX - normal[0] * tangentZ;
+ frame[5] = normal[0] * tangentY - normal[1] * tangentX;
+ frame[6] = normal[0];
+ frame[7] = normal[1];
+ frame[8] = normal[2];
+}
+
+function localToWorld(frame, x, y, z, out) {
+ out[0] = frame[0] * x + frame[3] * y + frame[6] * z;
+ out[1] = frame[1] * x + frame[4] * y + frame[7] * z;
+ out[2] = frame[2] * x + frame[5] * y + frame[8] * z;
+}
+
+function worldToLocal(frame, x, y, z, out) {
+ out[0] = frame[0] * x + frame[1] * y + frame[2] * z;
+ out[1] = frame[3] * x + frame[4] * y + frame[5] * z;
+ out[2] = frame[6] * x + frame[7] * y + frame[8] * z;
+}
+
+const LOCAL_VIEW = new Float64Array(3);
+const LOCAL_HALF = new Float64Array(3);
+const LOCAL_LIGHT = new Float64Array(3);
+
+// ---- The layered surface ----
+
+export function createSurface() {
+ return {
+ frame: new Float64Array(9),
+ view: new Float64Array(3),
+ viewCosine: 0,
+ diffuseColor: new Float64Array(3),
+ specularNormalReflectance: new Float64Array(3),
+ specularWeight: 1,
+ specularAlpha: MINIMUM_ALPHA,
+ coatWeight: 0,
+ coatChance: 0,
+ sampledCoat: false,
+ coatAlpha: MINIMUM_ALPHA,
+ diffuseChance: 1,
+ specularChance: 0,
+ // Outputs of evaluate().
+ value: new Float64Array(3),
+ pdf: 0,
+ };
+}
+
+/**
+ * Sets the lobes of a hit. `view` points from the surface toward the viewer and `normal` faces it. A dielectric keeps
+ * the light its reflection did not take, so the diffuse colour shrinks with the Fresnel term, and a clear coat takes
+ * its share from both lobes below it.
+ */
+export function prepareSurface(surface, material, baseColor, normal, viewX, viewY, viewZ) {
+ buildFrame(normal, surface.frame);
+ surface.view[0] = viewX;
+ surface.view[1] = viewY;
+ surface.view[2] = viewZ;
+ const viewCosine = Math.max(normal[0] * viewX + normal[1] * viewY + normal[2] * viewZ, 1e-4);
+ surface.viewCosine = viewCosine;
+ const ratio = (material.ior - 1) / (material.ior + 1);
+ const dielectricNormalReflectance = ratio * ratio;
+ const dielectricFresnel = schlick(dielectricNormalReflectance, viewCosine);
+ surface.coatWeight = material.clearcoat > 0 ? material.clearcoat * schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine) : 0;
+ const underCoat = 1 - surface.coatWeight;
+ const diffuseShare = (1 - material.metallic) * (1 - dielectricFresnel) * underCoat;
+ for (let channel = 0; channel < 3; channel++) {
+ surface.diffuseColor[channel] = baseColor[channel] * diffuseShare;
+ const normalReflectance = dielectricNormalReflectance * (1 - material.metallic) + baseColor[channel] * material.metallic;
+ surface.specularNormalReflectance[channel] = normalReflectance;
+ }
+ const specularLuminance = luminance(surface.specularNormalReflectance[0], surface.specularNormalReflectance[1], surface.specularNormalReflectance[2]);
+ surface.specularWeight = underCoat;
+ surface.specularAlpha = roughnessToAlpha(material.roughness);
+ surface.coatAlpha = roughnessToAlpha(material.clearcoatRoughness);
+ const diffuseLuminance = luminance(surface.diffuseColor[0], surface.diffuseColor[1], surface.diffuseColor[2]);
+ const specularChance = schlick(specularLuminance, viewCosine) * underCoat;
+ const coatChance = surface.coatWeight;
+ const sum = diffuseLuminance + specularChance + coatChance;
+ surface.diffuseChance = sum > 0 ? diffuseLuminance / sum : 1;
+ surface.specularChance = sum > 0 ? specularChance / sum : 0;
+ surface.coatChance = sum > 0 ? coatChance / sum : 0;
+}
+
+function microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) {
+ return ggxDistribution(alpha, halfCosine) * smithMasking(alpha, viewCosine) * smithMasking(alpha, lightCosine) / (4 * viewCosine * lightCosine);
+}
+
+/**
+ * The surface's value (BSDF, without the cosine) and sampling density for a light direction, in `surface.value` and
+ * `surface.pdf`. A mirror lobe reports zero, because a light sample can never hit it.
+ */
+export function evaluateSurface(surface, lightX, lightY, lightZ) {
+ surface.value[0] = 0;
+ surface.value[1] = 0;
+ surface.value[2] = 0;
+ surface.pdf = 0;
+ const { frame, view, viewCosine } = surface;
+ const lightCosine = frame[6] * lightX + frame[7] * lightY + frame[8] * lightZ;
+ if (lightCosine <= 0) return;
+ let halfX = view[0] + lightX;
+ let halfY = view[1] + lightY;
+ let halfZ = view[2] + lightZ;
+ const halfLength = Math.hypot(halfX, halfY, halfZ) || 1;
+ halfX /= halfLength;
+ halfY /= halfLength;
+ halfZ /= halfLength;
+ const halfCosine = frame[6] * halfX + frame[7] * halfY + frame[8] * halfZ;
+ const viewHalfCosine = Math.max(view[0] * halfX + view[1] * halfY + view[2] * halfZ, 0);
+ surface.pdf += surface.diffuseChance * lightCosine / Math.PI;
+ for (let channel = 0; channel < 3; channel++) surface.value[channel] += surface.diffuseColor[channel] / Math.PI;
+ if (surface.specularChance > 0 && surface.specularAlpha > MIRROR_ALPHA) {
+ const alpha = surface.specularAlpha;
+ const term = microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * surface.specularWeight;
+ for (let channel = 0; channel < 3; channel++) surface.value[channel] += schlick(surface.specularNormalReflectance[channel], viewHalfCosine) * term;
+ surface.pdf += surface.specularChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4 * viewCosine);
+ }
+ if (surface.coatChance > 0 && surface.coatAlpha > MIRROR_ALPHA) {
+ const alpha = surface.coatAlpha;
+ const reflectance = schlick(DIELECTRIC_COAT_REFLECTANCE, viewHalfCosine) * microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * (surface.coatWeight / Math.max(schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), 1e-6));
+ for (let channel = 0; channel < 3; channel++) surface.value[channel] += reflectance;
+ surface.pdf += surface.coatChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4 * viewCosine);
+ }
+}
+
+function reflectAbout(halfX, halfY, halfZ, viewX, viewY, viewZ, out) {
+ const projection = 2 * (viewX * halfX + viewY * halfY + viewZ * halfZ);
+ out[0] = projection * halfX - viewX;
+ out[1] = projection * halfY - viewY;
+ out[2] = projection * halfZ - viewZ;
+}
+
+/**
+ * Draws the next direction of a path. Mirror lobes are followed exactly: the result's `mirror` is true and
+ * `weight` is already the throughput factor. Other lobes leave `weight` to the caller, from evaluateSurface().
+ */
+export function sampleSurface(surface, lobeUnit, firstUnit, secondUnit, out) {
+ const { frame, view } = surface;
+ if (lobeUnit < surface.diffuseChance) {
+ const radius = Math.sqrt(firstUnit);
+ const angle = TWO_PI * secondUnit;
+ localToWorld(frame, radius * Math.cos(angle), radius * Math.sin(angle), Math.sqrt(Math.max(0, 1 - firstUnit)), out);
+ return false;
+ }
+ const isCoat = lobeUnit >= surface.diffuseChance + surface.specularChance;
+ surface.sampledCoat = isCoat;
+ const alpha = isCoat ? surface.coatAlpha : surface.specularAlpha;
+ worldToLocal(frame, view[0], view[1], view[2], LOCAL_VIEW);
+ if (alpha <= MIRROR_ALPHA) {
+ out[0] = 2 * surface.viewCosine * frame[6] - view[0];
+ out[1] = 2 * surface.viewCosine * frame[7] - view[1];
+ out[2] = 2 * surface.viewCosine * frame[8] - view[2];
+ return true;
+ }
+ sampleVisibleNormal(LOCAL_VIEW[0], LOCAL_VIEW[1], LOCAL_VIEW[2], alpha, firstUnit, secondUnit, LOCAL_HALF);
+ reflectAbout(LOCAL_HALF[0], LOCAL_HALF[1], LOCAL_HALF[2], LOCAL_VIEW[0], LOCAL_VIEW[1], LOCAL_VIEW[2], LOCAL_LIGHT);
+ localToWorld(frame, LOCAL_LIGHT[0], LOCAL_LIGHT[1], LOCAL_LIGHT[2], out);
+ return false;
+}
+
+/** The throughput factor of a followed mirror lobe: its Fresnel share over the chance of having picked it. */
+export function mirrorWeight(surface, out) {
+ if (surface.sampledCoat) {
+ out[0] = out[1] = out[2] = surface.coatWeight / surface.coatChance;
+ return;
+ }
+ for (let channel = 0; channel < 3; channel++) {
+ out[channel] = schlick(surface.specularNormalReflectance[channel], surface.viewCosine) * surface.specularWeight / surface.specularChance;
+ }
+}
+
+// ---- Glass ----
+
+function dielectricFresnel(cosineIncident, relativeIndex) {
+ const sineSquared = relativeIndex * relativeIndex * (1 - cosineIncident * cosineIncident);
+ if (sineSquared >= 1) return 1;
+ const cosineTransmitted = Math.sqrt(1 - sineSquared);
+ const parallel = (relativeIndex * cosineIncident - cosineTransmitted) / (relativeIndex * cosineIncident + cosineTransmitted);
+ const perpendicular = (cosineIncident - relativeIndex * cosineTransmitted) / (cosineIncident + relativeIndex * cosineTransmitted);
+ return 0.5 * (parallel * parallel + perpendicular * perpendicular);
+}
+
+/**
+ * A dielectric interface: reflects with the Fresnel chance and refracts otherwise, through a GGX normal for rough
+ * glass. `normal` faces the viewer. Writes the new direction into `out` and returns false when it ends inside the
+ * surface (the path is dropped).
+ */
+export function sampleGlass(normal, viewX, viewY, viewZ, entering, ior, alpha, selectionUnit, firstUnit, secondUnit, out) {
+ const frame = GLASS_FRAME;
+ buildFrame(normal, frame);
+ let halfX = normal[0];
+ let halfY = normal[1];
+ let halfZ = normal[2];
+ if (alpha > MIRROR_ALPHA) {
+ worldToLocal(frame, viewX, viewY, viewZ, LOCAL_VIEW);
+ sampleVisibleNormal(LOCAL_VIEW[0], LOCAL_VIEW[1], LOCAL_VIEW[2], alpha, firstUnit, secondUnit, LOCAL_HALF);
+ localToWorld(frame, LOCAL_HALF[0], LOCAL_HALF[1], LOCAL_HALF[2], GLASS_HALF);
+ halfX = GLASS_HALF[0];
+ halfY = GLASS_HALF[1];
+ halfZ = GLASS_HALF[2];
+ }
+ const relativeIndex = entering ? 1 / ior : ior;
+ const cosineIncident = Math.max(viewX * halfX + viewY * halfY + viewZ * halfZ, 1e-6);
+ const reflectChance = dielectricFresnel(cosineIncident, relativeIndex);
+ if (selectionUnit < reflectChance) {
+ reflectAbout(halfX, halfY, halfZ, viewX, viewY, viewZ, out);
+ return out[0] * normal[0] + out[1] * normal[1] + out[2] * normal[2] > 0;
+ }
+ const cosineTransmitted = Math.sqrt(Math.max(0, 1 - relativeIndex * relativeIndex * (1 - cosineIncident * cosineIncident)));
+ const bend = relativeIndex * cosineIncident - cosineTransmitted;
+ out[0] = bend * halfX - relativeIndex * viewX;
+ out[1] = bend * halfY - relativeIndex * viewY;
+ out[2] = bend * halfZ - relativeIndex * viewZ;
+ return out[0] * normal[0] + out[1] * normal[1] + out[2] * normal[2] < 0;
+}
+
+const GLASS_FRAME = new Float64Array(9);
+const GLASS_HALF = new Float64Array(3);
diff --git a/src/path-tracer-worker.js b/src/path-tracer-worker.js
new file mode 100644
index 00000000..3cb64b9e
--- /dev/null
+++ b/src/path-tracer-worker.js
@@ -0,0 +1,21 @@
+import { attachTracer } from './path-tracer-scene.js';
+import { renderBand } from './path-tracer.js';
+
+// One thread of a path trace: receives the flattened scene once, then draws the bands it is given.
+
+let scene = null;
+let camera = null;
+let options = null;
+
+self.onmessage = (event) => {
+ const message = event.data;
+ if (message.type === 'scene') {
+ scene = attachTracer(message.scene);
+ camera = message.camera;
+ options = message.options;
+ self.postMessage({ type: 'ready' });
+ return;
+ }
+ const band = renderBand(scene, camera, options, message.rowStart, message.rowEnd);
+ self.postMessage({ type: 'band', rowStart: message.rowStart, band }, Object.values(band).map(buffer => buffer.buffer));
+};
diff --git a/src/path-tracer.js b/src/path-tracer.js
new file mode 100644
index 00000000..0fbc85b7
--- /dev/null
+++ b/src/path-tracer.js
@@ -0,0 +1,727 @@
+import { pointLightFalloff } from './ray-query.js';
+import { buildTraceScene, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';
+import { denoiseRadiance } from './path-tracer-denoise.js';
+import {
+ buildFrame, createSurface, environmentPdf, environmentRadiance, evaluateSurface, luminance, mirrorWeight, prepareSurface,
+ roughnessToAlpha, sampleEnvironment, sampleGlass, sampleSurface,
+} from './path-tracer-shading.js';
+
+// Offline still renderer: unidirectional path tracing on the CPU with next-event estimation for every light, the
+// environment map drawn by importance, and a wavelet denoiser. It reads the same parts, materials, lights and camera
+// as the rasterizer. Same input gives the same bytes: random numbers come from a hash of pixel, sample and seed, and
+// the clock only decides whether a render is allowed to finish.
+
+export const PATH_TRACER_LIMITS = Object.freeze({
+ width: Object.freeze({ minimum: 16, maximum: 4096, fallback: 960 }),
+ height: Object.freeze({ minimum: 16, maximum: 4096, fallback: 540 }),
+ samples: Object.freeze({ minimum: 1, maximum: 1024, fallback: 64 }),
+ bounces: Object.freeze({ minimum: 1, maximum: 16, fallback: 8 }),
+ maxSeconds: Object.freeze({ minimum: 1, maximum: 1800, fallback: 300 }),
+ fireflyClamp: Object.freeze({ minimum: 1, maximum: 1000, fallback: 20 }),
+ seed: Object.freeze({ minimum: 0, maximum: 2 ** 31 - 1, fallback: 0 }),
+ threads: Object.freeze({ minimum: 1, maximum: 8, fallback: 4 }),
+});
+export const MAX_TRACE_PIXELS = 2_073_600;
+export const MAX_TRACE_RAY_WORK = 4_000_000_000;
+const ALPHA_STEP_LIMIT = 8;
+const WORKER_BAND_ROWS = 8;
+// Held in a constant so the bundler leaves the URL alone: the worker is its own package entry, built beside this file.
+const WORKER_FILE = './path-tracer-worker.js';
+const RUSSIAN_ROULETTE_START = 3;
+const IGNORED_MAP_FIELDS = ['normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
+
+function boundedInteger(options, name) {
+ const limit = PATH_TRACER_LIMITS[name];
+ const value = options[name] ?? limit.fallback;
+ if (!Number.isInteger(value) || value < limit.minimum || value > limit.maximum) {
+ throw new RangeError(`Path tracer ${name} must be an integer from ${limit.minimum} to ${limit.maximum}.`);
+ }
+ return value;
+}
+
+function boundedNumber(options, name) {
+ const limit = PATH_TRACER_LIMITS[name];
+ const value = options[name] ?? limit.fallback;
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < limit.minimum || value > limit.maximum) {
+ throw new RangeError(`Path tracer ${name} must be a number from ${limit.minimum} to ${limit.maximum}.`);
+ }
+ return value;
+}
+
+export function normalizePathTracerOptions(options = {}) {
+ if (options === null || typeof options !== 'object') throw new TypeError('Path tracer options must be an object.');
+ const result = {
+ width: boundedInteger(options, 'width'),
+ height: boundedInteger(options, 'height'),
+ samples: boundedInteger(options, 'samples'),
+ bounces: boundedInteger(options, 'bounces'),
+ seed: boundedInteger(options, 'seed'),
+ threads: boundedInteger(options, 'threads'),
+ maxSeconds: boundedNumber(options, 'maxSeconds'),
+ fireflyClamp: boundedNumber(options, 'fireflyClamp'),
+ denoise: options.denoise ?? true,
+ };
+ if (typeof result.denoise !== 'boolean') throw new TypeError('Path tracer denoise must be a boolean.');
+ if (result.width * result.height > MAX_TRACE_PIXELS) throw new RangeError(`A path trace takes at most ${MAX_TRACE_PIXELS} pixels.`);
+ if (result.width * result.height * result.samples * (result.bounces + 1) > MAX_TRACE_RAY_WORK) throw new RangeError('This path trace would need too much ray work: lower the size, samples or bounces.');
+ return result;
+}
+
+function finiteVector(value, name) {
+ if (!Array.isArray(value) || value.length !== 3 || value.some(entry => typeof entry !== 'number' || !Number.isFinite(entry))) {
+ throw new TypeError(`Path tracer camera ${name} must be three finite numbers.`);
+ }
+ return value;
+}
+
+function createCamera(camera, width, height) {
+ const eye = finiteVector(camera.eye, 'eye');
+ const target = finiteVector(camera.target, 'target');
+ const up = finiteVector(camera.up ?? [0, 1, 0], 'up');
+ if (typeof camera.fov !== 'number' || !(camera.fov > 1 && camera.fov < 170)) throw new RangeError('Path tracer camera fov must be between 1 and 170 degrees.');
+ const forward = [target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]];
+ const forwardLength = Math.hypot(...forward);
+ if (forwardLength === 0) throw new RangeError('Path tracer camera eye and target must differ.');
+ for (let axis = 0; axis < 3; axis++) forward[axis] /= forwardLength;
+ const right = [forward[1] * up[2] - forward[2] * up[1], forward[2] * up[0] - forward[0] * up[2], forward[0] * up[1] - forward[1] * up[0]];
+ const rightLength = Math.hypot(...right);
+ if (rightLength === 0) throw new RangeError('Path tracer camera up must not be parallel to its view.');
+ for (let axis = 0; axis < 3; axis++) right[axis] /= rightLength;
+ const above = [right[1] * forward[2] - right[2] * forward[1], right[2] * forward[0] - right[0] * forward[2], right[0] * forward[1] - right[1] * forward[0]];
+ const halfHeight = Math.tan(camera.fov * Math.PI / 360);
+ return { eye, forward, right, above, halfHeight, halfWidth: halfHeight * width / height };
+}
+
+// ---- Random numbers ----
+
+function createRandom() {
+ let state = 1;
+ return {
+ reset(pixel, sample, seed) {
+ let mixed = Math.imul(pixel + 0x9e3779b9, 0x85ebca6b) ^ Math.imul(sample + 0x7f4a7c15, 0xc2b2ae35) ^ Math.imul(seed + 0x165667b1, 0x27d4eb2f);
+ mixed = Math.imul(mixed ^ (mixed >>> 15), 0x2c1b3c6d);
+ mixed = Math.imul(mixed ^ (mixed >>> 12), 0x297a2d39);
+ mixed ^= mixed >>> 15;
+ state = mixed === 0 ? 1 : mixed;
+ },
+ // PCG (RXS-M-XS): successive values are independent enough for light and lobe choices that share one path.
+ next() {
+ state = (Math.imul(state, 747796405) + 2891336453) >>> 0;
+ const word = Math.imul((state >>> ((state >>> 28) + 4)) ^ state, 277803737);
+ return (((word >>> 22) ^ word) >>> 0) / 4294967296;
+ },
+ };
+}
+
+// ---- Hits ----
+
+function createHit() {
+ return {
+ distance: 0, material: null,
+ point: new Float64Array(3), normal: new Float64Array(3), color: new Float64Array(3),
+ texel: new Float64Array(4),
+ };
+}
+
+function sampleTexture(texture, u, v, out) {
+ const { width, height, data, colorLookup, repeat } = texture;
+ const x = u * width - 0.5;
+ const y = v * height - 0.5;
+ const left = Math.floor(x);
+ const top = Math.floor(y);
+ const shareX = x - left;
+ const shareY = y - top;
+ out[0] = 0;
+ out[1] = 0;
+ out[2] = 0;
+ out[3] = 0;
+ for (let corner = 0; corner < 4; corner++) {
+ let column = left + (corner & 1);
+ let row = top + (corner >> 1);
+ column = repeat ? ((column % width) + width) % width : Math.max(0, Math.min(width - 1, column));
+ row = repeat ? ((row % height) + height) % height : Math.max(0, Math.min(height - 1, row));
+ const weight = ((corner & 1) ? shareX : 1 - shareX) * ((corner >> 1) ? shareY : 1 - shareY);
+ const base = (row * width + column) * 4;
+ for (let channel = 0; channel < 3; channel++) out[channel] += weight * (colorLookup ? colorLookup[data[base + channel]] : data[base + channel] / 255);
+ out[3] += weight * data[base + 3] / 255;
+ }
+}
+
+const CORNER_VERTICES = new Uint32Array(3);
+const CORNER_WEIGHTS = new Float64Array(3);
+
+/** Interpolates the surface at a hit: position, facing-corrected normal is left to the caller, colour and alpha. */
+function fillHit(scene, triangleId, originX, originY, originZ, directionX, directionY, directionZ, distance, hit) {
+ const { positions, normals, uvs, colors, indices } = scene;
+ const first = indices[triangleId * 3];
+ const second = indices[triangleId * 3 + 1];
+ const third = indices[triangleId * 3 + 2];
+ hit.distance = distance;
+ hit.point[0] = originX + directionX * distance;
+ hit.point[1] = originY + directionY * distance;
+ hit.point[2] = originZ + directionZ * distance;
+ const edgeOneX = positions[second * 3] - positions[first * 3];
+ const edgeOneY = positions[second * 3 + 1] - positions[first * 3 + 1];
+ const edgeOneZ = positions[second * 3 + 2] - positions[first * 3 + 2];
+ const edgeTwoX = positions[third * 3] - positions[first * 3];
+ const edgeTwoY = positions[third * 3 + 1] - positions[first * 3 + 1];
+ const edgeTwoZ = positions[third * 3 + 2] - positions[first * 3 + 2];
+ const offsetX = hit.point[0] - positions[first * 3];
+ const offsetY = hit.point[1] - positions[first * 3 + 1];
+ const offsetZ = hit.point[2] - positions[first * 3 + 2];
+ const oneOne = edgeOneX * edgeOneX + edgeOneY * edgeOneY + edgeOneZ * edgeOneZ;
+ const oneTwo = edgeOneX * edgeTwoX + edgeOneY * edgeTwoY + edgeOneZ * edgeTwoZ;
+ const twoTwo = edgeTwoX * edgeTwoX + edgeTwoY * edgeTwoY + edgeTwoZ * edgeTwoZ;
+ const offsetOne = offsetX * edgeOneX + offsetY * edgeOneY + offsetZ * edgeOneZ;
+ const offsetTwo = offsetX * edgeTwoX + offsetY * edgeTwoY + offsetZ * edgeTwoZ;
+ const denominator = oneOne * twoTwo - oneTwo * oneTwo || 1;
+ const secondWeight = (twoTwo * offsetOne - oneTwo * offsetTwo) / denominator;
+ const thirdWeight = (oneOne * offsetTwo - oneTwo * offsetOne) / denominator;
+ const firstWeight = 1 - secondWeight - thirdWeight;
+ let normalX = 0;
+ let normalY = 0;
+ let normalZ = 0;
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+ let u = 0;
+ let v = 0;
+ CORNER_VERTICES[0] = first;
+ CORNER_VERTICES[1] = second;
+ CORNER_VERTICES[2] = third;
+ CORNER_WEIGHTS[0] = firstWeight;
+ CORNER_WEIGHTS[1] = secondWeight;
+ CORNER_WEIGHTS[2] = thirdWeight;
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = CORNER_VERTICES[corner];
+ const weight = CORNER_WEIGHTS[corner];
+ normalX += weight * normals[vertex * 3];
+ normalY += weight * normals[vertex * 3 + 1];
+ normalZ += weight * normals[vertex * 3 + 2];
+ red += weight * colors[vertex * 3];
+ green += weight * colors[vertex * 3 + 1];
+ blue += weight * colors[vertex * 3 + 2];
+ u += weight * uvs[vertex * 2];
+ v += weight * uvs[vertex * 2 + 1];
+ }
+ const length = Math.hypot(normalX, normalY, normalZ) || 1;
+ hit.normal[0] = normalX / length;
+ hit.normal[1] = normalY / length;
+ hit.normal[2] = normalZ / length;
+ const material = scene.materials[scene.triangleMaterial[triangleId]];
+ hit.material = material;
+ let alpha = 1;
+ hit.color[0] = material.color[0] * red;
+ hit.color[1] = material.color[1] * green;
+ hit.color[2] = material.color[2] * blue;
+ if (material.texture) {
+ sampleTexture(material.texture, u, v, hit.texel);
+ hit.color[0] *= hit.texel[0];
+ hit.color[1] *= hit.texel[1];
+ hit.color[2] *= hit.texel[2];
+ alpha = hit.texel[3];
+ }
+ return alpha;
+}
+
+/** The nearest solid hit along a ray, stepping through the transparent texels of cutout materials. */
+function intersect(scene, originX, originY, originZ, directionX, directionY, directionZ, hit) {
+ let startX = originX;
+ let startY = originY;
+ let startZ = originZ;
+ let travelled = 0;
+ for (let attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
+ const found = scene.tracer.trace(startX, startY, startZ, directionX, directionY, directionZ, scene.farDistance, false);
+ if (found.nearestTriangle < 0) return false;
+ const alpha = fillHit(scene, found.nearestTriangle, startX, startY, startZ, directionX, directionY, directionZ, found.nearestDistance, hit);
+ if (hit.material.alphaCutoff === 0 || alpha >= hit.material.alphaCutoff) {
+ hit.distance += travelled;
+ return true;
+ }
+ const advance = found.nearestDistance + scene.surfaceOffset;
+ travelled += advance;
+ startX += directionX * advance;
+ startY += directionY * advance;
+ startZ += directionZ * advance;
+ }
+ return false;
+}
+
+function occluded(scene, originX, originY, originZ, directionX, directionY, directionZ, limit, hit) {
+ let startX = originX;
+ let startY = originY;
+ let startZ = originZ;
+ let remaining = limit;
+ for (let attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
+ const found = scene.tracer.trace(startX, startY, startZ, directionX, directionY, directionZ, remaining, true);
+ if (found.nearestTriangle < 0) return false;
+ const alpha = fillHit(scene, found.nearestTriangle, startX, startY, startZ, directionX, directionY, directionZ, found.nearestDistance, hit);
+ if (hit.material.alphaCutoff === 0 || alpha >= hit.material.alphaCutoff) return true;
+ const advance = found.nearestDistance + scene.surfaceOffset;
+ remaining -= advance;
+ if (remaining <= 0) return false;
+ startX += directionX * advance;
+ startY += directionY * advance;
+ startZ += directionZ * advance;
+ }
+ return true;
+}
+
+// ---- One path ----
+
+function smoothstep(value) {
+ return value * value * (3 - 2 * value);
+}
+
+function createPathTracer(scene, options) {
+ const surface = createSurface();
+ const hit = createHit();
+ const shadowHit = createHit();
+ const throughput = new Float64Array(3);
+ const radiance = new Float64Array(3);
+ const direction = new Float64Array(3);
+ const lightDirection = new Float64Array(3);
+ const lightRadiance = new Float64Array(3);
+ const sky = new Float64Array(3);
+ const sunFrame = new Float64Array(9);
+ const mirror = new Float64Array(3);
+ const normal = new Float64Array(3);
+ const features = { albedo: new Float64Array(3), normal: new Float64Array(3), depth: 0 };
+ const random = createRandom();
+ const { lights, environment } = scene;
+ if (lights.sun) buildFrame(lights.sun.direction, sunFrame);
+ const sunCosineMax = Math.cos(SUN_ANGULAR_RADIUS);
+
+ function addRadiance(depth, red, green, blue) {
+ let clampedRed = red;
+ let clampedGreen = green;
+ let clampedBlue = blue;
+ if (depth > 0) {
+ const peak = Math.max(red, green, blue);
+ if (peak > options.fireflyClamp) {
+ const scale = options.fireflyClamp / peak;
+ clampedRed *= scale;
+ clampedGreen *= scale;
+ clampedBlue *= scale;
+ }
+ }
+ radiance[0] += clampedRed;
+ radiance[1] += clampedGreen;
+ radiance[2] += clampedBlue;
+ }
+
+ /** Adds the light from one sampled direction: surface value, cosine, shadow ray. `weight` carries MIS and sampling. */
+ function addDirect(depth, normal, distance, weight) {
+ const cosine = normal[0] * lightDirection[0] + normal[1] * lightDirection[1] + normal[2] * lightDirection[2];
+ if (cosine <= 0) return;
+ evaluateSurface(surface, lightDirection[0], lightDirection[1], lightDirection[2]);
+ const value = surface.value;
+ if (value[0] + value[1] + value[2] <= 0) return;
+ const originX = hit.point[0] + normal[0] * scene.surfaceOffset;
+ const originY = hit.point[1] + normal[1] * scene.surfaceOffset;
+ const originZ = hit.point[2] + normal[2] * scene.surfaceOffset;
+ if (occluded(scene, originX, originY, originZ, lightDirection[0], lightDirection[1], lightDirection[2], distance, shadowHit)) return;
+ const scale = cosine * weight(surface);
+ addRadiance(
+ depth,
+ throughput[0] * value[0] * lightRadiance[0] * scale,
+ throughput[1] * value[1] * lightRadiance[1] * scale,
+ throughput[2] * value[2] * lightRadiance[2] * scale,
+ );
+ }
+
+ const fullWeight = () => 1;
+
+ function sampleSun(depth, normal) {
+ const cosineTheta = 1 - random.next() * (1 - sunCosineMax);
+ const sineTheta = Math.sqrt(Math.max(0, 1 - cosineTheta * cosineTheta));
+ const phi = 2 * Math.PI * random.next();
+ const across = sineTheta * Math.cos(phi);
+ const along = sineTheta * Math.sin(phi);
+ for (let axis = 0; axis < 3; axis++) lightDirection[axis] = sunFrame[axis] * across + sunFrame[3 + axis] * along + sunFrame[6 + axis] * cosineTheta;
+ for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = lights.sun.color[channel];
+ addDirect(depth, normal, scene.farDistance, fullWeight);
+ }
+
+ function aimAt(targetX, targetY, targetZ) {
+ const deltaX = targetX - hit.point[0];
+ const deltaY = targetY - hit.point[1];
+ const deltaZ = targetZ - hit.point[2];
+ const distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
+ const distance = Math.sqrt(distanceSquared);
+ lightDirection[0] = deltaX / distance;
+ lightDirection[1] = deltaY / distance;
+ lightDirection[2] = deltaZ / distance;
+ return { distance, distanceSquared };
+ }
+
+ function randomOnSphere(radius, out) {
+ const height = 2 * random.next() - 1;
+ const angle = 2 * Math.PI * random.next();
+ const ring = Math.sqrt(1 - height * height);
+ out[0] = radius * ring * Math.cos(angle);
+ out[1] = radius * height;
+ out[2] = radius * ring * Math.sin(angle);
+ }
+
+ const jitter = new Float64Array(3);
+
+ function samplePointLight(depth, normal, light) {
+ randomOnSphere(light.radius, jitter);
+ const { distance, distanceSquared } = aimAt(light.position[0] + jitter[0], light.position[1] + jitter[1], light.position[2] + jitter[2]);
+ if (distance < 1e-6) return;
+ const strength = light.intensity * pointLightFalloff(distanceSquared, light);
+ for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = light.color[channel] * strength;
+ addDirect(depth, normal, distance - scene.surfaceOffset, fullWeight);
+ }
+
+ function sampleSpotLight(depth, normal, light) {
+ randomOnSphere(light.radius, jitter);
+ const { distance, distanceSquared } = aimAt(light.position[0] + jitter[0], light.position[1] + jitter[1], light.position[2] + jitter[2]);
+ if (distance < 1e-6) return;
+ const axisCosine = -(light.direction[0] * lightDirection[0] + light.direction[1] * lightDirection[1] + light.direction[2] * lightDirection[2]);
+ const inside = axisCosine - light.cosineHalfAngle;
+ if (inside <= 0) return;
+ const mask = light.blend > 0 && inside < light.blend ? smoothstep(inside / light.blend) : 1;
+ const strength = light.intensity * pointLightFalloff(distanceSquared, light) * mask;
+ for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = light.color[channel] * strength;
+ addDirect(depth, normal, distance - scene.surfaceOffset, fullWeight);
+ }
+
+ function sampleAreaLight(depth, normal, light) {
+ const across = (random.next() - 0.5) * light.width;
+ const along = (random.next() - 0.5) * light.height;
+ const pointX = light.position[0] + light.across[0] * across + light.along[0] * along;
+ const pointY = light.position[1] + light.across[1] * across + light.along[1] * along;
+ const pointZ = light.position[2] + light.across[2] * across + light.along[2] * along;
+ const { distance, distanceSquared } = aimAt(pointX, pointY, pointZ);
+ if (distance < 1e-6) return;
+ const emitCosine = -(light.normal[0] * lightDirection[0] + light.normal[1] * lightDirection[1] + light.normal[2] * lightDirection[2]);
+ if (emitCosine <= 0) return;
+ const strength = light.intensity * emitCosine / distanceSquared;
+ for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = light.color[channel] * strength;
+ addDirect(depth, normal, distance - scene.surfaceOffset, fullWeight);
+ }
+
+ let environmentSampledPdf = 0;
+ const environmentWeight = candidate => {
+ const total = environmentSampledPdf * environmentSampledPdf + candidate.pdf * candidate.pdf;
+ return environmentSampledPdf * environmentSampledPdf / total / environmentSampledPdf;
+ };
+
+ function sampleEnvironmentLight(depth, normal) {
+ environmentSampledPdf = sampleEnvironment(environment, random.next(), random.next(), random.next(), random.next(), lightDirection);
+ if (!(environmentSampledPdf > 0)) return;
+ environmentRadiance(environment, lightDirection[0], lightDirection[1], lightDirection[2], lightRadiance);
+ addDirect(depth, normal, scene.farDistance, environmentWeight);
+ }
+
+ function addLights(depth, normal) {
+ if (lights.sun) sampleSun(depth, normal);
+ for (const light of lights.points) samplePointLight(depth, normal, light);
+ for (const light of lights.spots) sampleSpotLight(depth, normal, light);
+ for (const light of lights.areas) sampleAreaLight(depth, normal, light);
+ if (environment) sampleEnvironmentLight(depth, normal);
+ }
+
+ function addEscape(depth, previousPdf, afterMirror) {
+ if (!environment) return;
+ environmentRadiance(environment, direction[0], direction[1], direction[2], sky);
+ let weight = 1;
+ if (!afterMirror) {
+ const environmentSide = environmentPdf(environment, direction[0], direction[1], direction[2]);
+ weight = previousPdf * previousPdf / (previousPdf * previousPdf + environmentSide * environmentSide);
+ }
+ addRadiance(depth, throughput[0] * sky[0] * weight, throughput[1] * sky[1] * weight, throughput[2] * sky[2] * weight);
+ }
+
+ function recordFeatures(normal, isGlass) {
+ features.albedo[0] = isGlass ? 1 : hit.color[0];
+ features.albedo[1] = isGlass ? 1 : hit.color[1];
+ features.albedo[2] = isGlass ? 1 : hit.color[2];
+ features.normal[0] = normal[0];
+ features.normal[1] = normal[1];
+ features.normal[2] = normal[2];
+ features.depth = hit.distance;
+ }
+
+ /** Follows one camera ray. Leaves the radiance in `radiance` and the first-hit features in `features`. */
+ function trace(originX, originY, originZ, directionX, directionY, directionZ, pixel, sample) {
+ random.reset(pixel, sample, options.seed);
+ radiance[0] = 0;
+ radiance[1] = 0;
+ radiance[2] = 0;
+ throughput[0] = 1;
+ throughput[1] = 1;
+ throughput[2] = 1;
+ features.albedo.fill(1);
+ // A ray that finds nothing has the sky as its feature: one fixed normal and depth, so the filter treats sky as one surface.
+ features.normal[0] = 0;
+ features.normal[1] = 0;
+ features.normal[2] = 1;
+ features.depth = 0;
+ direction[0] = directionX;
+ direction[1] = directionY;
+ direction[2] = directionZ;
+ let positionX = originX;
+ let positionY = originY;
+ let positionZ = originZ;
+ let previousPdf = 0;
+ let afterMirror = true;
+ for (let depth = 0; depth <= options.bounces; depth++) {
+ if (!intersect(scene, positionX, positionY, positionZ, direction[0], direction[1], direction[2], hit)) {
+ addEscape(depth, previousPdf, afterMirror);
+ break;
+ }
+ const material = hit.material;
+ const entering = hit.normal[0] * direction[0] + hit.normal[1] * direction[1] + hit.normal[2] * direction[2] < 0;
+ const facing = entering ? 1 : -1;
+ normal[0] = hit.normal[0] * facing;
+ normal[1] = hit.normal[1] * facing;
+ normal[2] = hit.normal[2] * facing;
+ const isGlass = material.transmission > 0 && random.next() < material.transmission;
+ if (depth === 0) recordFeatures(normal, isGlass);
+ addRadiance(depth, throughput[0] * material.emission[0], throughput[1] * material.emission[1], throughput[2] * material.emission[2]);
+ const viewX = -direction[0];
+ const viewY = -direction[1];
+ const viewZ = -direction[2];
+ if (isGlass) {
+ const alpha = roughnessToAlpha(material.roughness);
+ if (!sampleGlass(normal, viewX, viewY, viewZ, entering, material.ior, alpha, random.next(), random.next(), random.next(), direction)) break;
+ const refracted = direction[0] * normal[0] + direction[1] * normal[1] + direction[2] * normal[2] < 0;
+ if (refracted) {
+ throughput[0] *= hit.color[0];
+ throughput[1] *= hit.color[1];
+ throughput[2] *= hit.color[2];
+ }
+ afterMirror = true;
+ } else {
+ prepareSurface(surface, material, hit.color, normal, viewX, viewY, viewZ);
+ addLights(depth, normal);
+ const lobeUnit = random.next();
+ const isMirror = sampleSurface(surface, lobeUnit, random.next(), random.next(), direction);
+ const cosine = direction[0] * normal[0] + direction[1] * normal[1] + direction[2] * normal[2];
+ if (cosine <= 0) break;
+ if (isMirror) {
+ mirrorWeight(surface, mirror);
+ for (let channel = 0; channel < 3; channel++) throughput[channel] *= mirror[channel];
+ afterMirror = true;
+ } else {
+ evaluateSurface(surface, direction[0], direction[1], direction[2]);
+ if (!(surface.pdf > 0)) break;
+ for (let channel = 0; channel < 3; channel++) throughput[channel] *= surface.value[channel] * cosine / surface.pdf;
+ previousPdf = surface.pdf;
+ afterMirror = false;
+ }
+ }
+ positionX = hit.point[0] + direction[0] * scene.surfaceOffset;
+ positionY = hit.point[1] + direction[1] * scene.surfaceOffset;
+ positionZ = hit.point[2] + direction[2] * scene.surfaceOffset;
+ if (depth >= RUSSIAN_ROULETTE_START) {
+ const survival = Math.min(0.95, Math.max(0.05, Math.max(throughput[0], throughput[1], throughput[2])));
+ if (random.next() >= survival) break;
+ for (let channel = 0; channel < 3; channel++) throughput[channel] /= survival;
+ }
+ }
+ }
+
+ return { trace, radiance, features };
+}
+
+// ---- Image ----
+
+function toneMap(linear) {
+ const color = Math.max(linear, 0);
+ const mapped = Math.min(1, Math.max(0, (color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14)));
+ return mapped ** (1 / 2.2);
+}
+
+/** The display transform of the rasterizer's post pass (filmic curve and gamma 2.2) applied to linear pixels. */
+export function toneMapToRgba8(linear, width, height) {
+ const rgba = new Uint8ClampedArray(width * height * 4);
+ for (let pixel = 0; pixel < width * height; pixel++) {
+ for (let channel = 0; channel < 3; channel++) rgba[pixel * 4 + channel] = Math.round(toneMap(linear[pixel * 3 + channel]) * 255);
+ rgba[pixel * 4 + 3] = 255;
+ }
+ return rgba;
+}
+
+/** Names what this scene asks for that the path tracer does not draw, so a result never claims more than it traced. */
+export function describeIgnoredFeatures(parts, environment) {
+ const notes = new Set();
+ if (environment?.volumeFog) notes.add('volumeFog is not traced.');
+ if (!environment?.map) notes.add('There is no environment map, so the sky is black and only the lights shine.');
+ for (const part of parts) {
+ const material = part.material ?? {};
+ for (const field of IGNORED_MAP_FIELDS) if (material[field]) notes.add(`${field} is ignored.`);
+ if (material.tag && material.tag !== 'surface') notes.add(`${material.tag} materials are traced as plain surfaces.`);
+ if (material.alphaMode === 'blend') notes.add('Blended transparency is traced as opaque.');
+ }
+ return [...notes];
+}
+
+/**
+ * Renders rows `rowStart` up to `rowEnd` and returns their buffers (colour, albedo, normal, depth, variance), row
+ * major from the band's first row. A pixel's random numbers depend only on its place in the whole image, so bands
+ * can be drawn in any order, on any thread, and give the same pixels.
+ */
+export function renderBand(scene, camera, options, rowStart, rowEnd, shouldStop = () => {}) {
+ const tracer = createPathTracer(scene, options);
+ const { width, height, samples } = options;
+ const pixelCount = (rowEnd - rowStart) * width;
+ const color = new Float32Array(pixelCount * 3);
+ const albedo = new Float32Array(pixelCount * 3);
+ const normal = new Float32Array(pixelCount * 3);
+ const depth = new Float32Array(pixelCount);
+ const variance = new Float32Array(pixelCount);
+ for (let row = rowStart; row < rowEnd; row++) {
+ shouldStop();
+ for (let column = 0; column < width; column++) {
+ const pixel = row * width + column;
+ const slot = (row - rowStart) * width + column;
+ let sumLuminance = 0;
+ let sumLuminanceSquares = 0;
+ for (let sample = 0; sample < samples; sample++) {
+ const jitterX = hashJitter(pixel, sample, options.seed, 1);
+ const jitterY = hashJitter(pixel, sample, options.seed, 2);
+ const screenX = ((column + jitterX) / width * 2 - 1) * camera.halfWidth;
+ const screenY = (1 - (row + jitterY) / height * 2) * camera.halfHeight;
+ const directionX = camera.forward[0] + camera.right[0] * screenX + camera.above[0] * screenY;
+ const directionY = camera.forward[1] + camera.right[1] * screenX + camera.above[1] * screenY;
+ const directionZ = camera.forward[2] + camera.right[2] * screenX + camera.above[2] * screenY;
+ const length = Math.hypot(directionX, directionY, directionZ);
+ tracer.trace(camera.eye[0], camera.eye[1], camera.eye[2], directionX / length, directionY / length, directionZ / length, pixel, sample);
+ const { radiance, features } = tracer;
+ const sampleLuminance = luminance(radiance[0], radiance[1], radiance[2]);
+ sumLuminance += sampleLuminance;
+ sumLuminanceSquares += sampleLuminance * sampleLuminance;
+ for (let channel = 0; channel < 3; channel++) {
+ color[slot * 3 + channel] += radiance[channel];
+ albedo[slot * 3 + channel] += features.albedo[channel];
+ normal[slot * 3 + channel] += features.normal[channel];
+ }
+ depth[slot] += features.depth;
+ }
+ for (let channel = 0; channel < 3; channel++) {
+ color[slot * 3 + channel] /= samples;
+ albedo[slot * 3 + channel] /= samples;
+ normal[slot * 3 + channel] /= samples;
+ }
+ depth[slot] /= samples;
+ const meanLuminance = sumLuminance / samples;
+ variance[slot] = Math.max(0, sumLuminanceSquares / samples - meanLuminance * meanLuminance) / Math.max(samples - 1, 1);
+ }
+ }
+ return { color, albedo, normal, depth, variance };
+}
+
+function hashJitter(pixel, sample, seed, dimension) {
+ let mixed = Math.imul(pixel ^ 0x51ed270b, 0x9e3779b1) ^ Math.imul(sample + dimension * 0x632be5ab, 0x85ebca6b) ^ Math.imul(seed + 0x1b873593, 0xc2b2ae35);
+ mixed = Math.imul(mixed ^ (mixed >>> 16), 0x7feb352d);
+ mixed = Math.imul(mixed ^ (mixed >>> 15), 0x846ca68b);
+ mixed ^= mixed >>> 16;
+ return (mixed >>> 0) / 4294967296;
+}
+
+function normalizeNormals(normal, pixelCount) {
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ const length = Math.hypot(normal[pixel * 3], normal[pixel * 3 + 1], normal[pixel * 3 + 2]);
+ if (length === 0) continue;
+ for (let axis = 0; axis < 3; axis++) normal[pixel * 3 + axis] /= length;
+ }
+}
+
+function copyBand(buffers, band, rowStart, width) {
+ const pixelOffset = rowStart * width;
+ for (const name of ['color', 'albedo', 'normal']) buffers[name].set(band[name], pixelOffset * 3);
+ for (const name of ['depth', 'variance']) buffers[name].set(band[name], pixelOffset);
+}
+
+/** Draws bands on a pool of module workers, handing the next band to whichever worker finishes first. */
+function renderBandsInWorkers(scene, camera, options, buffers, shouldStop) {
+ const bandCount = Math.ceil(options.height / WORKER_BAND_ROWS);
+ const workerCount = Math.min(options.threads, bandCount);
+ const workers = [];
+ const { tracer: _tracer, ...transferableScene } = scene;
+ return new Promise((resolve, reject) => {
+ let nextBand = 0;
+ let finishedBands = 0;
+ let settled = false;
+ const finish = (error) => {
+ if (settled) return;
+ settled = true;
+ clearInterval(clock);
+ for (const worker of workers) worker.terminate();
+ if (error) reject(error);
+ else resolve();
+ };
+ const clock = setInterval(() => {
+ try {
+ shouldStop();
+ } catch (error) {
+ finish(error);
+ }
+ }, 250);
+ const assign = (worker) => {
+ if (nextBand >= bandCount) return;
+ const rowStart = nextBand * WORKER_BAND_ROWS;
+ nextBand++;
+ worker.postMessage({ type: 'band', rowStart, rowEnd: Math.min(rowStart + WORKER_BAND_ROWS, options.height) });
+ };
+ for (let index = 0; index < workerCount; index++) {
+ const worker = new Worker(new URL(WORKER_FILE, import.meta.url), { type: 'module' });
+ workers.push(worker);
+ worker.onerror = (event) => finish(new Error(`Path tracer worker failed: ${event.message}`));
+ worker.onmessage = (event) => {
+ if (event.data.type === 'ready') {
+ assign(worker);
+ return;
+ }
+ copyBand(buffers, event.data.band, event.data.rowStart, options.width);
+ finishedBands++;
+ if (finishedBands === bandCount) finish();
+ else assign(worker);
+ };
+ worker.postMessage({ type: 'scene', scene: transferableScene, camera, options });
+ }
+ });
+}
+
+/**
+ * Renders one still. `scene` is `{ parts, environment, camera }` as the rasterizer takes them. Resolves with the linear
+ * pixels, the tone-mapped RGBA bytes, and a report. Rejects, and returns nothing, when `maxSeconds` runs out.
+ * `threads` above 1 uses module workers where the platform has them; the pixels are the same either way.
+ */
+export async function renderPathTracedImage({ parts, environment = {}, camera }, rawOptions = {}) {
+ const options = normalizePathTracerOptions(rawOptions);
+ const started = performance.now();
+ const shouldStop = () => {
+ if ((performance.now() - started) / 1000 > options.maxSeconds) throw new Error(`The path trace passed its ${options.maxSeconds} second limit and was stopped.`);
+ };
+ const { width, height } = options;
+ const view = createCamera(camera, width, height);
+ const scene = buildTraceScene(parts, environment);
+ const pixelCount = width * height;
+ const buffers = {
+ color: new Float32Array(pixelCount * 3), albedo: new Float32Array(pixelCount * 3), normal: new Float32Array(pixelCount * 3),
+ depth: new Float32Array(pixelCount), variance: new Float32Array(pixelCount),
+ };
+ const threads = typeof Worker === 'function' ? options.threads : 1;
+ if (threads > 1) {
+ await renderBandsInWorkers(scene, view, { ...options, threads }, buffers, shouldStop);
+ } else {
+ copyBand(buffers, renderBand(scene, view, options, 0, height, shouldStop), 0, width);
+ }
+ shouldStop();
+ const tracedSeconds = (performance.now() - started) / 1000;
+ normalizeNormals(buffers.normal, pixelCount);
+ const linear = options.denoise ? denoiseRadiance({ width, height, ...buffers }) : buffers.color;
+ return {
+ width, height, linear, rgba: toneMapToRgba8(linear, width, height),
+ report: {
+ width, height, samples: options.samples, bounces: options.bounces, seed: options.seed, denoised: options.denoise, threads,
+ triangles: scene.indices.length / 3, tracedSeconds, seconds: (performance.now() - started) / 1000,
+ ignored: describeIgnoredFeatures(parts, environment),
+ },
+ };
+}
diff --git a/src/ray-query.js b/src/ray-query.js
new file mode 100644
index 00000000..52923102
--- /dev/null
+++ b/src/ray-query.js
@@ -0,0 +1,48 @@
+import { rayBoxDistance, traverseTriangleBvh } from './triangle-bvh.js';
+import { intersectRayTriangle, readTriangle } from './triangle-math.js';
+
+/**
+ * Ray queries against a triangle world ({ positions, indices, bvh }) with preallocated state: the traversal callbacks
+ * are built once, not once per ray. `trace` returns a shared state object, so read it before the next query.
+ */
+export function createTracer(world) {
+ const origin = new Float64Array(3);
+ const direction = new Float64Array(3);
+ const triangle = new Float64Array(9);
+ const state = { nearestDistance: Infinity, nearestTriangle: -1, stopAtAnyHit: false };
+ const scoreBounds = (bounds, offset) => rayBoxDistance(origin, direction, bounds, offset);
+ const shouldVisit = score => score < state.nearestDistance;
+ const visitTriangle = triangleId => {
+ readTriangle(world.positions, world.indices, triangleId, triangle);
+ const distance = intersectRayTriangle(origin, direction, triangle);
+ if (distance < 0 || distance >= state.nearestDistance) return false;
+ state.nearestDistance = distance;
+ state.nearestTriangle = triangleId;
+ return state.stopAtAnyHit;
+ };
+ function trace(originX, originY, originZ, directionX, directionY, directionZ, limit, stopAtAnyHit) {
+ origin[0] = originX;
+ origin[1] = originY;
+ origin[2] = originZ;
+ direction[0] = directionX;
+ direction[1] = directionY;
+ direction[2] = directionZ;
+ state.nearestDistance = limit;
+ state.nearestTriangle = -1;
+ state.stopAtAnyHit = stopAtAnyHit;
+ traverseTriangleBvh(world.bvh, scoreBounds, shouldVisit, visitTriangle);
+ return state;
+ }
+ return { trace };
+}
+
+/** Inverse-square falloff of a point or spot light, with the optional smooth range cutoff and a floor at its radius. */
+export function pointLightFalloff(distanceSquared, light) {
+ let cutoff = 1;
+ if (light.range > 0) {
+ const ratio = distanceSquared / (light.range * light.range);
+ const fade = Math.max(1 - ratio * ratio, 0);
+ cutoff = fade * fade;
+ }
+ return cutoff / Math.max(distanceSquared, light.radius * light.radius);
+}
diff --git a/tests/path-tracer.test.js b/tests/path-tracer.test.js
new file mode 100644
index 00000000..142caf55
--- /dev/null
+++ b/tests/path-tracer.test.js
@@ -0,0 +1,177 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { box, sphere } from '../src/geometry.js';
+import { createEnvironmentMap } from '../src/environment.js';
+import { PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';
+import {
+ describeIgnoredFeatures, MAX_TRACE_PIXELS, normalizePathTracerOptions, PATH_TRACER_LIMITS, renderPathTracedImage, toneMapToRgba8,
+} from '../src/path-tracer.js';
+import { attachTracer, buildTraceScene } from '../src/path-tracer-scene.js';
+
+function placed(translation, scale) {
+ return new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]);
+}
+
+function surface(color, extra = {}) {
+ return { tag: 'surface', metallic: 0, roughness: 0.5, emission: 0, color, ...extra };
+}
+
+const FLOOR_ALBEDO = 0.5;
+const SUN_STRENGTH = 3;
+const FLOOR_ONLY = [{ name: 'floor', geometry: box(0, 1), matrix: placed([0, -0.05, 0], [40, 0.1, 40]), material: surface([FLOOR_ALBEDO, FLOOR_ALBEDO, FLOOR_ALBEDO], { roughness: 1 }) }];
+const OVERHEAD_SUN = { keyColor: [SUN_STRENGTH, SUN_STRENGTH, SUN_STRENGTH], lightDirection: [0, 1, 0] };
+const LOOKING_DOWN = { eye: [0, 3, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 40 };
+const SMALL = { width: 32, height: 24, samples: 4, bounces: 3, threads: 1 };
+
+function checkerScene() {
+ return {
+ parts: [
+ ...FLOOR_ONLY,
+ { name: 'ball', geometry: sphere(24, 16), matrix: placed([0, 0.6, 0], [0.6, 0.6, 0.6]), material: surface([0.8, 0.3, 0.2], { metallic: 0.5, clearcoat: 0.5 }) },
+ { name: 'glass', geometry: sphere(24, 16), matrix: placed([1.2, 0.5, 0], [0.5, 0.5, 0.5]), material: surface([1, 1, 1], { transmission: 1, roughness: 0.05 }) },
+ ],
+ environment: {
+ ...OVERHEAD_SUN,
+ pointLights: [{ position: [0, 2, 1], color: [1, 1, 1], intensity: 4, radius: 0.1 }],
+ map: createEnvironmentMap({ width: 8, height: 4, data: new Float32Array(8 * 4 * 3).fill(0.4) }),
+ },
+ camera: { eye: [0, 2, 5], target: [0, 0.5, 0], up: [0, 1, 0], fov: 40 },
+ };
+}
+
+test('the job limits listed for agents match the limits the tracer enforces', () => {
+ for (const name of ['samples', 'bounces', 'seed']) {
+ assert.equal(PATH_TRACER_JOB_LIMITS[name].minimum, PATH_TRACER_LIMITS[name].minimum, name);
+ assert.equal(PATH_TRACER_JOB_LIMITS[name].maximum, PATH_TRACER_LIMITS[name].maximum, name);
+ assert.equal(PATH_TRACER_JOB_LIMITS[name].default, PATH_TRACER_LIMITS[name].fallback, name);
+ }
+ assert.ok(PATH_TRACER_JOB_LIMITS.maxSeconds.maximum <= PATH_TRACER_LIMITS.maxSeconds.maximum);
+});
+
+test('options are validated with their bounds', () => {
+ assert.equal(normalizePathTracerOptions().samples, 64);
+ assert.equal(normalizePathTracerOptions().width, 960);
+ const refused = [
+ { samples: 0 }, { samples: 1025 }, { samples: 1.5 }, { samples: Number.NaN }, { samples: '8' }, { bounces: 17 }, { bounces: 0 },
+ { width: 4097 }, { width: 8 }, { height: -1 }, { seed: -1 }, { seed: 2 ** 31 }, { threads: 9 }, { threads: 0 },
+ { maxSeconds: 0 }, { maxSeconds: 1801 }, { maxSeconds: Infinity }, { fireflyClamp: 0 }, { denoise: 'yes' },
+ { width: 4096, height: 4096 },
+ { width: 2000, height: 1000, samples: 1024, bounces: 16 },
+ ];
+ for (const options of refused) assert.throws(() => normalizePathTracerOptions(options), /Path tracer|too much|at most/, JSON.stringify(options));
+ assert.throws(() => normalizePathTracerOptions(null), TypeError);
+ assert.ok(MAX_TRACE_PIXELS >= 1920 * 1080);
+});
+
+test('hostile cameras and scenes are refused before any ray is traced', async () => {
+ const { parts, environment } = checkerScene();
+ const badCameras = [
+ undefined,
+ { eye: [0, 0, 0], target: [0, 0, 0], up: [0, 1, 0], fov: 40 },
+ { eye: [0, 0, 5], target: [0, 0, 0], up: [0, 0, 1], fov: 40 },
+ { eye: [0, 0, Number.NaN], target: [0, 0, 0], up: [0, 1, 0], fov: 40 },
+ { eye: [0, 0, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 0 },
+ { eye: [0, 0, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 179 },
+ { eye: [0, 0, 5, 1], target: [0, 0, 0], up: [0, 1, 0], fov: 40 },
+ ];
+ for (const camera of badCameras) await assert.rejects(renderPathTracedImage({ parts, environment, camera }, SMALL), /camera|Cannot read/i);
+ const camera = checkerScene().camera;
+ await assert.rejects(renderPathTracedImage({ parts: [], environment, camera }, SMALL), /1 to/);
+ await assert.rejects(renderPathTracedImage({ parts: 'floor', environment, camera }, SMALL), /1 to/);
+ const nonFinite = [{ ...parts[0], matrix: placed([Number.NaN, 0, 0], [1, 1, 1]) }];
+ await assert.rejects(renderPathTracedImage({ parts: nonFinite, environment, camera }, SMALL), /finite/);
+ const brokenIndices = [{ ...parts[0], geometry: { ...parts[0].geometry, indices: new Uint32Array([0, 1, 999999]) } }];
+ await assert.rejects(renderPathTracedImage({ parts: brokenIndices, environment, camera }, SMALL), /index/i);
+ const flooded = { ...environment, pointLights: Array.from({ length: 40 }, () => ({ position: [0, 2, 0], color: [1, 1, 1], intensity: 1 })) };
+ await assert.rejects(renderPathTracedImage({ parts, environment: flooded, camera }, SMALL), /at most/);
+});
+
+test('the same scene and seed give the same bytes, and another seed does not', async () => {
+ const first = await renderPathTracedImage(checkerScene(), SMALL);
+ const second = await renderPathTracedImage(checkerScene(), SMALL);
+ assert.deepEqual(first.rgba, second.rgba);
+ assert.deepEqual(first.linear, second.linear);
+ const other = await renderPathTracedImage(checkerScene(), { ...SMALL, seed: 7 });
+ assert.notDeepEqual(first.rgba, other.rgba);
+ assert.ok(first.linear.every(Number.isFinite));
+ assert.equal(first.report.width, SMALL.width);
+ assert.equal(first.report.threads, 1);
+});
+
+test('a floor lit by an overhead sun matches the diffuse closed form', async () => {
+ const { linear } = await renderPathTracedImage(
+ { parts: FLOOR_ONLY, environment: OVERHEAD_SUN, camera: LOOKING_DOWN },
+ { width: 16, height: 16, samples: 32, bounces: 1, denoise: false, threads: 1 },
+ );
+ const centre = (8 * 16 + 8) * 3;
+ // Radiance of a diffuse surface under irradiance E is albedo * E / pi, shrunk by the Fresnel share the specular lobe
+ // takes (4 percent at normal incidence). That lobe adds F0 * D(0) / 4 * E, and a fully rough GGX has D(0) = 1 / pi.
+ const expected = FLOOR_ALBEDO * (1 - 0.04) * SUN_STRENGTH / Math.PI + 0.04 / (4 * Math.PI) * SUN_STRENGTH;
+ assert.ok(Math.abs(linear[centre] - expected) / expected < 0.05, `got ${linear[centre]}, expected near ${expected}`);
+});
+
+test('a block between the sun and the floor leaves a shadow', async () => {
+ const blocker = { name: 'block', geometry: box(0, 1), matrix: placed([0, 1, 0], [2, 0.2, 2]), material: surface([0.5, 0.5, 0.5]) };
+ // Sun from +x at 45 degrees: the block (x from -1 to 1, 1 m up) shades the floor from x = -2 to 0. Seen from above,
+ // the floor at x = -1.5 is clear of the block's top and inside its shadow.
+ const slantedSun = { keyColor: [3, 3, 3], lightDirection: [1, 1, 0] };
+ const render = parts => renderPathTracedImage({ parts, environment: slantedSun, camera: { eye: [0, 8, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 30 } },
+ { width: 16, height: 16, samples: 16, bounces: 1, denoise: false, threads: 1 });
+ const lit = await render(FLOOR_ONLY);
+ const shaded = await render([...FLOOR_ONLY, blocker]);
+ const pixel = (8 * 16 + 2) * 3;
+ assert.ok(lit.linear[pixel] > 0.2, `unshaded floor: ${lit.linear[pixel]}`);
+ assert.ok(shaded.linear[pixel] < 0.01, `shaded floor: ${shaded.linear[pixel]}`);
+});
+
+test('a render that runs out of time throws and returns nothing', async () => {
+ await assert.rejects(
+ renderPathTracedImage(checkerScene(), { width: 256, height: 256, samples: 1024, bounces: 4, maxSeconds: 1, threads: 1 }),
+ /1 second limit/,
+ );
+});
+
+test('denoising keeps the mean of a noisy image and removes some of its noise', async () => {
+ const scene = checkerScene();
+ const options = { width: 48, height: 32, samples: 2, bounces: 3, threads: 1 };
+ const noisy = await renderPathTracedImage(scene, { ...options, denoise: false });
+ const clean = await renderPathTracedImage(scene, { ...options, denoise: true });
+ const mean = buffer => buffer.reduce((sum, value) => sum + value, 0) / buffer.length;
+ const roughness = buffer => {
+ let total = 0;
+ for (let index = 3; index < buffer.length; index++) total += Math.abs(buffer[index] - buffer[index - 3]);
+ return total / buffer.length;
+ };
+ assert.ok(Math.abs(mean(clean.linear) - mean(noisy.linear)) / mean(noisy.linear) < 0.1);
+ assert.ok(roughness(clean.linear) < roughness(noisy.linear));
+ assert.ok(clean.linear.every(Number.isFinite));
+});
+
+test('the display transform matches the rasterizer post pass at known values', () => {
+ const pixels = toneMapToRgba8(new Float32Array([0, 0, 0, 1, 1, 1]), 2, 1);
+ assert.deepEqual([...pixels.slice(0, 4)], [0, 0, 0, 255]);
+ // (1 * (2.51 + 0.03)) / (1 * (2.43 + 0.59) + 0.14) = 0.8038, then 0.8038 ^ (1 / 2.2) = 0.9055.
+ assert.equal(pixels[4], Math.round(0.9055 * 255));
+});
+
+test('what the tracer does not draw is named in the report', () => {
+ const notes = describeIgnoredFeatures(
+ [{ material: { normalMap: {}, tag: 'liquid' } }, { material: { alphaMode: 'blend' } }],
+ { volumeFog: { density: 1 } },
+ );
+ assert.ok(notes.some(note => note.includes('volumeFog')));
+ assert.ok(notes.some(note => note.includes('normalMap')));
+ assert.ok(notes.some(note => note.includes('liquid')));
+ assert.ok(notes.some(note => note.includes('Blended')));
+ assert.ok(notes.some(note => note.includes('environment map')));
+});
+
+test('a scene sent to a worker gets its ray query back from the arrays', () => {
+ const { parts, environment } = checkerScene();
+ const scene = buildTraceScene(parts, environment);
+ const { tracer: _removed, ...sent } = scene;
+ const revived = attachTracer(structuredClone(sent));
+ const hit = revived.tracer.trace(0, 5, 0, 0, -1, 0, 100, false);
+ assert.ok(hit.nearestTriangle >= 0);
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index f347aaa9..4611299f 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -35,6 +35,8 @@ export default defineConfig({
grass: 'src/grass.js',
clutter: 'src/clutter.js',
'light-bake': 'src/light-bake.js',
+ 'path-tracer': 'src/path-tracer.js',
+ 'path-tracer-worker': 'src/path-tracer-worker.js',
'texture-set': 'src/texture-set.js',
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',