Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Native tracer: fog, subsurface and noiseThreshold, plus a fallback job test (issue #626)

Nguyen Xuan Andda4e5c6032d
diff --git a/bench/native-tracer/scenes-flip.py b/bench/native-tracer/scenes-flip.py
new file mode 100644
index 00000000..7ec31fc7
--- /dev/null
+++ b/bench/native-tracer/scenes-flip.py
@@ -0,0 +1,27 @@
+# Mean FLIP (LDR) between the WebGPU and native image of every scene that bench/native-tracer/scenes.mjs drew.
+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/native-tracer/scenes-flip.py <directory>
+import json
+import sys
+from pathlib import Path
+
+import flip_evaluator
+import numpy as np
+from PIL import Image
+
+
+def load(path):
+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255
+
+
+directory = Path(sys.argv[1])
+records = json.loads((directory / "scenes.json").read_text())["records"]
+scores = {}
+for scene, record in records.items():
+ if "error" in record:
+ print(f"{scene}: skipped ({record['error']})")
+ continue
+ _, mean_error, _ = flip_evaluator.evaluate(load(directory / f"{scene}-webgpu.png"), load(directory / f"{scene}-native.png"), "LDR", inputsRGB=True)
+ scores[scene] = round(float(mean_error), 4)
+ print(f"{scene}: FLIP {scores[scene]} native {record['nativeTracedSeconds']:.2f} s webgpu {record['webgpuTracedSeconds']:.2f} s")
+worst = max(scores, key=scores.get)
+print(f"{len(scores)} scenes, worst {worst} {scores[worst]}, mean {sum(scores.values()) / len(scores):.4f}")
diff --git a/bench/native-tracer/scenes.mjs b/bench/native-tracer/scenes.mjs
new file mode 100644
index 00000000..514faf9a
--- /dev/null
+++ b/bench/native-tracer/scenes.mjs
@@ -0,0 +1,88 @@
+// Draws reference scenes with the native ray query tracer and with the browser's WebGPU megakernel, same seed and no
+// denoiser, and writes both images plus their timings. Score each pair with bench/webgpu-tracer/flip.py. Run it through gpu-lock.
+// node bench/native-tracer/scenes.mjs <output directory> [--scenes a,b,c] [--samples 64] [--width 960] [--height 540]
+// [--bounces 8] [--noise-threshold 0]
+// Without --scenes it draws every reference scene. Files: <scene>-native.png, <scene>-webgpu.png and scenes.json.
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+import { createNativeTracerLocator, traceFrameNative } from '../../scripts/agent-native-trace.mjs';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const argumentsGiven = process.argv.slice(2);
+const outputDirectory = resolve(argumentsGiven[0]);
+
+function valueAfter(flag, fallback) {
+ const index = argumentsGiven.indexOf(flag);
+ return index >= 0 ? argumentsGiven[index + 1] : fallback;
+}
+
+const options = {
+ width: Number(valueAfter('--width', 960)),
+ height: Number(valueAfter('--height', 540)),
+ samples: Number(valueAfter('--samples', 64)),
+ bounces: Number(valueAfter('--bounces', 8)),
+ seed: 0,
+ noiseThreshold: Number(valueAfter('--noise-threshold', 0)),
+};
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir(outputDirectory, { recursive: true });
+const found = await createNativeTracerLocator().find();
+if (!found.tracer) throw new Error(found.reason);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0, fs: { strict: false } }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true,
+ args: ['--enable-webgl', '--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'] });
+const records = {};
+try {
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));
+ page.setDefaultTimeout(0);
+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: 180000 });
+ await page.waitForFunction(() => window.loadTraceSceneFor && window.referenceSceneIds, null, { timeout: 180000 });
+ const sceneIds = valueAfter('--scenes', null)?.split(',') ?? await page.evaluate(() => window.referenceSceneIds);
+ for (const id of sceneIds) {
+ try {
+ const exported = await page.evaluate(async ([sceneId, tracerOptions]) => {
+ const [{ createCamera }, { buildTraceScene }, pack, { buildNativeInput }, { encodeNativeTables }] = await Promise.all([
+ import('/src/path-tracer.js'), import('/src/path-tracer-scene.js'), import('/src/path-tracer-gpu-pack.js'),
+ import('/packages/render-native/pack-input.mjs'), import('/scripts/native-bake-page.js'),
+ ]);
+ const source = await window.loadTraceSceneFor(sceneId);
+ const traceScene = buildTraceScene(source.parts, source.environment);
+ const camera = createCamera(source.camera, tracerOptions.width, tracerOptions.height);
+ const input = buildNativeInput(traceScene, camera, { ...tracerOptions, fireflyClamp: 20 }, pack);
+ return { tables: encodeNativeTables(input), triangleCount: input.triangleCount, triangles: traceScene.indices.length / 3, ignored: [] };
+ }, [id, options]);
+ const native = await traceFrameNative({ tracer: found.tracer, exported, width: options.width, height: options.height,
+ samples: options.samples, bounces: options.bounces, seed: options.seed, denoise: 'none', noiseThreshold: options.noiseThreshold });
+ await writeFile(`${outputDirectory}/${id}-native.png`, Buffer.from(native.data, 'base64'));
+ const webgpu = await page.evaluate(async ([sceneId, tracerOptions]) => {
+ const { renderPathTracedImage } = await import('/src/path-tracer.js');
+ const source = await window.loadTraceSceneFor(sceneId);
+ const result = await renderPathTracedImage(source, { ...tracerOptions, backend: 'webgpu', denoise: false });
+ 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 };
+ }, [id, { ...options, threads: 1, maxSeconds: 600 }]);
+ await writeFile(`${outputDirectory}/${id}-webgpu.png`, Buffer.from(webgpu.image, 'base64'));
+ records[id] = { nativeTracedSeconds: native.report.tracedSeconds, nativeAverageSamples: native.report.averageSamples,
+ webgpuTracedSeconds: webgpu.report.tracedSeconds, webgpuAverageSamples: webgpu.report.averageSamples, triangles: native.report.triangles };
+ console.log(id, JSON.stringify(records[id]));
+ } catch (error) {
+ // A reference scene the path tracer cannot take (no parts, for one) is recorded and the run goes on.
+ records[id] = { error: error.message.split(String.fromCharCode(10))[0] };
+ console.log(id, JSON.stringify(records[id]));
+ }
+ }
+} finally {
+ await writeFile(`${outputDirectory}/scenes.json`, JSON.stringify({ options, records }, null, 1));
+ await browser.close();
+ await server.close();
+}
diff --git a/changes/626-finish.md b/changes/626-finish.md
new file mode 100644
index 00000000..2c664e1e
--- /dev/null
+++ b/changes/626-finish.md
@@ -0,0 +1 @@
+- The native tracer (renderer.backend "native", recipe bakes) now traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, compiled in only for a scene that uses them, and honours `noiseThreshold` on the GPU: after 16 samples, and then every 8, a converged pixel draws no more, and `metrics.pathTracer.averageSamples` reports the mean a pixel drew. `JS67_NATIVE_TRACER=off` keeps a job on the gpu or cpu backend whatever is installed; a native job without the package gives the cpu backend's bytes and report fields (#626)
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index 92ce1894..58b5142e 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -134,7 +134,7 @@ An `image`, `stills` or `video` job can ask for the offline [path tracer](https:
"renderer": { "type": "pathTracer", "backend": "gpu", "samples": 64, "bounces": 8, "denoise": true, "seed": 0, "maxSeconds": 120 } }
```
-Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/67js-render-native` package. A native job exports the scene from the job page, traces it in the job runner, then denoises (wavelet or OIDN) and writes the PNG as the other backends do. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native draws no volume fog or subsurface scattering (listed in `ignored`), and `noiseThreshold` and `maxSeconds` do not apply to it. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it. The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), 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.
+Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/67js-render-native` package. A native job exports the scene from the job page, traces it in the job runner, then denoises (wavelet or OIDN) and writes the PNG as the other backends do. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, honours `maxSeconds`, and honours `noiseThreshold` on the GPU (after 16 samples, and then every 8, a converged pixel draws no more; `report.averageSamples` is the mean a pixel drew). The `gpu` fallback ignores `noiseThreshold`. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it. The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), 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
diff --git a/docs/light-bake.md b/docs/light-bake.md
index 700643f8..ce521c55 100644
--- a/docs/light-bake.md
+++ b/docs/light-bake.md
@@ -58,7 +58,7 @@ Not baked: the environment map (it already lights every surface at run time) and
### Recipe bakes choose the backend themselves
-A recipe `bake` built in a runtime on the GPU backend (the MCP server's default, `scene_inspect`, render jobs) traces its lightmaps first on the native ray query tracer when [`packages/render-native`](../packages/render-native/README.md) is installed and built (`bake.backend` is `native`; its texel entry is `bakeTexels` in the same Vulkan kernel as the render jobs, and a failed native bake falls back to the page's GPU kernel with `bake.backendNote`). On `lit-interior` (28,784 texels, 256 samples, `bench/reference/bake-compare.mjs` with a `native` variant, 2026-11-09) the native bake took 0.26 s against 0.30 s on WebGPU and 0.42 s on WebGL2 once compiled, its kernel compiles in 4 ms against 0.36 s and 8.2 s, and the mean light is 0.12 percent above WebGL2 (gap share 0.0032; the first leg of a bake counts as one bounce, so the kernel runs `bounces - 1`). The native bake has no fog or subsurface, as the native render job. Without it the bake traces on the GPU when the page has WebGL2 with `EXT_color_buffer_float` and `EXT_float_blend`, and on the CPU worker otherwise: SwiftShader runtimes (`--backend cpu`), a recipe whose lights use `affects`, or a GPU bake that fails. `scene_inspect` reports `bake.backend` (`cpu` or `gpu`) and, for the GPU, `bake.gpu` and `bake.gpuCompileSeconds`. The CPU path is unchanged, so the same recipe gives the same bytes there. The irradiance grid and probes still trace on the CPU.
+A recipe `bake` built in a runtime on the GPU backend (the MCP server's default, `scene_inspect`, render jobs) traces its lightmaps first on the native ray query tracer when [`packages/render-native`](../packages/render-native/README.md) is installed and built (`bake.backend` is `native`; its texel entry is `bakeTexels` in the same Vulkan kernel as the render jobs, and a failed native bake falls back to the page's GPU kernel with `bake.backendNote`). On `lit-interior` (28,784 texels, 256 samples, `bench/reference/bake-compare.mjs` with a `native` variant, 2026-11-09) the native bake took 0.26 s against 0.30 s on WebGPU and 0.42 s on WebGL2 once compiled, its kernel compiles in 4 ms against 0.36 s and 8.2 s, and the mean light is 0.12 percent above WebGL2 (gap share 0.0032; the first leg of a bake counts as one bounce, so the kernel runs `bounces - 1`). The native bake traces fog and subsurface scattering as the native render job does. Without it the bake traces on the GPU when the page has WebGL2 with `EXT_color_buffer_float` and `EXT_float_blend`, and on the CPU worker otherwise: SwiftShader runtimes (`--backend cpu`), a recipe whose lights use `affects`, or a GPU bake that fails. `scene_inspect` reports `bake.backend` (`cpu` or `gpu`) and, for the GPU, `bake.gpu` and `bake.gpuCompileSeconds`. The CPU path is unchanged, so the same recipe gives the same bytes there. The irradiance grid and probes still trace on the CPU.
## How a part draws it
diff --git a/docs/path-tracer.md b/docs/path-tracer.md
index 133cfc2c..9efd4db3 100644
--- a/docs/path-tracer.md
+++ b/docs/path-tracer.md
@@ -58,7 +58,7 @@ The same scene and options give the same bytes. Random numbers come from a hash
## Choosing a backend
-`backend: "native"` is an agent render job setting, not a `renderPathTracedImage` option: [`packages/render-native`](../packages/render-native/README.md) runs the same kernel on Vulkan ray queries. On the demo room at 1920 by 1080 and 64 samples an MCP image job took 25 to 35 s with native against 58 s with gpu (trace alone 2.7 to 3.1 s against 38.8 s; the rest is the page export, the wavelet denoise and the PNG), FLIP 0.0047 between them. A missing package, binary or adapter falls back to gpu with a note in the job report. `maxSeconds` is honoured: past it the native trace stops and the job fails, as on the other backends, instead of rerunning on gpu; `noiseThreshold` is not (the native trace always runs its samples). Alpha cutouts (`alphaMode: "mask"`) work: cutout triangles are their own geometry and the kernel confirms a hit only when the colour map alpha reaches the cutoff, with no step limit. In a dense cutout scene native is the more correct tracer: the CPU and WebGL2 shadow ray takes the first hit the traversal finds, not the nearest, and when that hit is a transparent texel it skips occluders it had not reached yet, so those backends leak light (300 leaf cards: native vs cpu FLIP 0.043, and 0.0002 once the CPU shadow ray takes the nearest hit; bench/native-tracer/cutout-bisect.mjs shows one card agrees exactly). The steps before: up to 8 layers deep (`bench/native-tracer/cutout.mjs`: 300 masked leaf cards trace in 0.1 s at 640 by 360 and 64 samples). See [agent-render-jobs.md](agent-render-jobs.md#path-tracer).
+`backend: "native"` is an agent render job setting, not a `renderPathTracedImage` option: [`packages/render-native`](../packages/render-native/README.md) runs the same kernel on Vulkan ray queries. On the demo room at 1920 by 1080 and 64 samples an MCP image job took 25 to 35 s with native against 58 s with gpu (trace alone 2.7 to 3.1 s against 38.8 s; the rest is the page export, the wavelet denoise and the PNG), FLIP 0.0047 between them. A missing package, binary or adapter falls back to gpu with a note in the job report. `maxSeconds` is honoured: past it the native trace stops and the job fails, as on the other backends, instead of rerunning on gpu; `noiseThreshold` is too (the kernel applies the CPU stop rule per pixel, so `averageSamples` falls below `samples`; the `gpu` and `webgpu` backends still draw every sample). Volume fog and subsurface scattering are in the native kernel, compiled in only for a scene that uses them; `bench/native-tracer/scenes.mjs` draws the reference scenes on native and on the WebGPU megakernel for a FLIP comparison. Alpha cutouts (`alphaMode: "mask"`) work: cutout triangles are their own geometry and the kernel confirms a hit only when the colour map alpha reaches the cutoff, with no step limit. In a dense cutout scene native is the more correct tracer: the CPU and WebGL2 shadow ray takes the first hit the traversal finds, not the nearest, and when that hit is a transparent texel it skips occluders it had not reached yet, so those backends leak light (300 leaf cards: native vs cpu FLIP 0.043, and 0.0002 once the CPU shadow ray takes the nearest hit; bench/native-tracer/cutout-bisect.mjs shows one card agrees exactly). The steps before: up to 8 layers deep (`bench/native-tracer/cutout.mjs`: 300 masked leaf cards trace in 0.1 s at 640 by 360 and 64 samples). See [agent-render-jobs.md](agent-render-jobs.md#path-tracer).
`backend: 'cpu'` (the default) is the reference: it reuses `src/triangle-bvh.js` and `src/ray-query.js`, runs on workers in the job page next to the scene, needs no GPU, and gives the same bytes for the same scene and options. 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`).
diff --git a/packages/render-native/README.md b/packages/render-native/README.md
index f35d023b..f8ac633e 100644
--- a/packages/render-native/README.md
+++ b/packages/render-native/README.md
@@ -19,7 +19,7 @@ const { rgba, adapter, tracedSeconds } = traceNative(input, options);
`rgba` is linear float RGBA, rows from the top, averaged over the samples. `albedo` and `normal` (three floats per pixel, normalise the normal), `depth` and `variance` (one float) are the first-hit features the wavelet and OIDN denoisers read. `pack-input.mjs` holds `buildNativeInput` without Node imports, so the job page packs the scene itself. `bench/native-tracer` compares it with the browser kernel.
-`traceNative` also takes `maxSeconds`: the trace stops with an error ("passed its time limit") once it has run that long. Alpha cutouts are traced by stepping through transparent texels in the kernel (the acceleration structure is opaque).
+Fog (`scene.volume`), subsurface scattering and `options.noiseThreshold` (the CPU tracer's stop rule: converged pixels draw no more samples, `averageSamples` in the result is the mean drawn) are in the kernel. `traceNative` also takes `maxSeconds`: the trace stops with an error ("passed its time limit") once it has run that long. Alpha cutouts are traced by stepping through transparent texels in the kernel (the acceleration structure is opaque).
The light bake uses the texel entry of the same kernel:
diff --git a/packages/render-native/pack-input.mjs b/packages/render-native/pack-input.mjs
index a0a04edc..fe7200b6 100644
--- a/packages/render-native/pack-input.mjs
+++ b/packages/render-native/pack-input.mjs
@@ -1,8 +1,9 @@
// Packs a trace scene into the tables the native kernel reads. It imports nothing from Node, so the job page can run it too.
-const PARAMETER_BYTES = 12 * 16;
+// 16 vectors: the 12 of the camera, lights and seed, the fog box and medium, and the subsurface table's first vector index.
+const PARAMETER_BYTES = 16 * 16;
const SUN_CONE_COSINE = Math.cos(Math.PI / 360);
-function writeParameters(scene, camera, options, lightCount, atlasWidth) {
+function writeParameters(scene, camera, options, lightCount, atlasWidth, subsurfaceOffset) {
const buffer = new ArrayBuffer(PARAMETER_BYTES);
const floats = new Float32Array(buffer);
const integers = new Int32Array(buffer);
@@ -17,10 +18,16 @@ function writeParameters(scene, camera, options, lightCount, atlasWidth) {
floats.set([...(sun?.color ?? [0, 0, 0]), SUN_CONE_COSINE], 20);
floats.set([environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1], 24);
floats.set([environment?.cosine ?? 1, environment?.sine ?? 0, scene.surfaceOffset, scene.farDistance], 28);
- floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp ?? 20, 0], 32);
+ // The fourth float is the noise threshold: pixels under it stop early, and 0 draws every sample.
+ floats.set([camera.halfWidth, camera.halfHeight, options.fireflyClamp ?? 20, options.noiseThreshold ?? 0], 32);
integers.set([options.width, options.height, options.bounces, lightCount], 36);
integers.set([(sun ? 1 : 0) + lightCount + (environment ? 1 : 0), sun ? 1 : 0, environment ? 1 : 0, 0], 40);
words.set([options.seed >>> 0, atlasWidth, 0, 0], 44);
+ const { volume } = scene;
+ floats.set([...(volume?.minimum ?? [0, 0, 0]), volume?.density ?? 0], 48);
+ floats.set([...(volume?.maximum ?? [0, 0, 0]), volume?.anisotropy ?? 0], 52);
+ floats.set([...(volume?.albedo ?? [1, 1, 1]), volume?.maxDistance ?? 0], 56);
+ words.set([subsurfaceOffset, 0, 0, 0], 60);
return new Uint8Array(buffer);
}
@@ -37,15 +44,23 @@ export function buildNativeInput(scene, camera, options, pack) {
environmentTables.set(environment.rows.data.subarray(0, environment.height), 0);
environmentTables.set(environment.pixels.data.subarray(0, environment.width * environment.height), environment.height);
}
+ // The subsurface table (two vectors per material) follows the material table in the same buffer; its offset is 0 when no
+ // material scatters light under its surface, which keeps the walk out of the kernel.
+ const materialData = pack.packMaterials(scene.materials, atlas).data;
+ const usesSubsurface = pack.sceneUsesSubsurface(scene.materials);
+ const subsurfaceData = usesSubsurface ? pack.packSubsurface(scene.materials).data : new Float32Array(0);
+ const materials = new Float32Array(materialData.length + subsurfaceData.length);
+ materials.set(materialData);
+ materials.set(subsurfaceData, materialData.length);
return {
triangles: pack.packTriangles(scene).data,
triangleCount: scene.bvh.triangleOrder.length,
- materials: pack.packMaterials(scene.materials, atlas).data,
+ materials,
lights: lights.table.data,
atlas: new Uint32Array(atlas.data.buffer, atlas.data.byteOffset, Math.floor(atlas.data.byteLength / 4)),
environmentColors: environment?.colors ?? new Float32Array(4),
environmentTables,
- parameters: writeParameters(scene, camera, options, lights.count, atlas.width),
+ parameters: writeParameters(scene, camera, options, lights.count, atlas.width, usesSubsurface ? materialData.length / 4 : 0),
};
}
diff --git a/packages/render-native/src/kernel.wgsl b/packages/render-native/src/kernel.wgsl
index cc8389f8..0af9a1d1 100644
--- a/packages/render-native/src/kernel.wgsl
+++ b/packages/render-native/src/kernel.wgsl
@@ -9,6 +9,12 @@ const RUSSIAN_ROULETTE_START: i32 = 3;
const MINIMUM_ALPHA: f32 = 1e-3;
const MIRROR_ALPHA: f32 = 2e-3;
const DIELECTRIC_COAT_REFLECTANCE: f32 = 0.04;
+const ADAPTIVE_MINIMUM_SAMPLES: u32 = 16u;
+const ADAPTIVE_BATCH_SAMPLES: u32 = 8u;
+const CONVERGENCE_LUMINANCE_FLOOR: f32 = 0.05;
+// The host sets these two before it compiles the kernel, so a scene without fog or subsurface scattering carries neither.
+const HAS_VOLUME: bool = false;
+const HAS_SUBSURFACE: bool = false;
struct Params {
eye: vec4<f32>,
@@ -23,6 +29,12 @@ struct Params {
sizeBouncesLights: vec4<i32>,
emittersFlagsSample: vec4<i32>,
seedAndAtlas: vec4<u32>,
+ // Fog box minimum and density, box maximum and anisotropy, albedo and the longest distance.
+ volumeMinimumDensity: vec4<f32>,
+ volumeMaximumAnisotropy: vec4<f32>,
+ volumeAlbedoDistance: vec4<f32>,
+ // x is the vector index where the subsurface table starts in the materials buffer.
+ extras: vec4<u32>,
}
@group(0) @binding(0) var<uniform> params: Params;
@@ -33,7 +45,7 @@ struct Params {
@group(0) @binding(5) var<storage, read> atlas: array<u32>;
@group(0) @binding(6) var<storage, read> environmentColors: array<vec4<f32>>;
@group(0) @binding(7) var<storage, read> environmentTables: array<f32>;
-// Four planes of pixelCount vec4 each: radiance and depth, albedo, normal, luminance statistics.
+// Four planes of pixelCount vec4 each: radiance and depth, albedo, normal, then the luminance sum, its square sum, the first-ray escape count and the samples drawn.
@group(0) @binding(8) var<storage, read_write> accumulation: array<vec4<f32>>;
@group(0) @binding(9) var<storage, read> primitiveSlots: array<u32>;
@@ -139,6 +151,7 @@ var<private> hitTransmission: f32;
var<private> hitIor: f32;
var<private> hitCutoff: f32;
var<private> hitMask: u32;
+var<private> hitMaterialIndex: i32;
fn srgbToLinear(encoded: vec3<f32>) -> vec3<f32> {
return select(pow((encoded + 0.055) / 1.055, vec3<f32>(2.4)), encoded / 12.92, encoded <= vec3<f32>(0.04045));
@@ -226,7 +239,8 @@ fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {
hitNormal = normal / select(normalLength, 1.0, normalLength == 0.0);
let vertexColor = firstWeight * colorOneData.xyz + secondWeight * colorTwoData.xyz + thirdWeight * colorThreeData.xyz;
let uv = firstWeight * vec2<f32>(normalOneData.w, colorOneData.w) + secondWeight * vec2<f32>(normalTwoData.w, colorTwoData.w) + thirdWeight * vec2<f32>(normalThreeData.w, colorThreeData.w);
- let material = i32(cornerData.w) * MATERIAL_TEXELS;
+ hitMaterialIndex = i32(cornerData.w);
+ let material = hitMaterialIndex * MATERIAL_TEXELS;
let colorMetallic = materials[material];
let emissionRoughness = materials[material + 1];
let coating = materials[material + 2];
@@ -438,6 +452,7 @@ var<private> surfaceCoatChance: f32;
var<private> surfaceSampledCoat: bool;
var<private> surfaceCoatAlpha: f32;
var<private> surfaceDiffuseChance: f32;
+var<private> surfaceDiffuseShare: f32;
var<private> surfaceSpecularChance: f32;
var<private> surfaceValue: vec3<f32>;
var<private> surfacePdf: f32;
@@ -462,6 +477,7 @@ fn prepareSurface(normal: vec3<f32>, view: vec3<f32>) {
let underCoat = 1.0 - surfaceCoatWeight;
let diffuseShare = (1.0 - hitMetallic) * (1.0 - dielectricFresnel) * underCoat;
surfaceDiffuse = hitColor * diffuseShare;
+ surfaceDiffuseShare = diffuseShare;
surfaceSpecularNormal = vec3<f32>(dielectricNormalReflectance * (1.0 - hitMetallic)) + hitColor * hitMetallic;
let specularLuminance = luminance(surfaceSpecularNormal);
surfaceSpecularWeight = underCoat;
@@ -579,6 +595,7 @@ var<private> featureAlbedo: vec3<f32>;
var<private> featureNormal: vec3<f32>;
var<private> featureDepth: f32;
var<private> firstLegEscaped: f32 = 0.0;
+var<private> inMedium: bool = false;
fn addRadiance(depth: i32, amountIn: vec3<f32>) {
var amount = amountIn;
@@ -610,20 +627,79 @@ var<private> shadowDepth: i32;
var<private> shadowPending: bool = false;
fn addDirect(depth: i32, normal: vec3<f32>, distance: f32, weightMode: i32) {
- let cosine = dot(normal, lightDirection);
- if (cosine <= 0.0) { return; }
- evaluateSurface(lightDirection);
- let value = surfaceValue;
- if (value.x + value.y + value.z <= 0.0) { return; }
- shadowOrigin = hitPoint + normal * params.environmentRotationAndRays.z;
- let scale = cosine * directWeight(weightMode, surfacePdf);
- shadowAmount = throughput * value * lightRadiance * scale;
- shadowDepth = depth;
+ if (HAS_VOLUME && inMedium) {
+ let phase = henyeyGreensteinPhase(params.volumeMaximumAnisotropy.w, dot(lightDirection, direction));
+ let scale = phase * fogTransmittance(hitPoint, distance) * directWeight(weightMode, phase);
+ shadowOrigin = hitPoint;
+ shadowAmount = throughput * lightRadiance * scale;
+ shadowDepth = depth + 1;
+ } else {
+ let cosine = dot(normal, lightDirection);
+ if (cosine <= 0.0) { return; }
+ evaluateSurface(lightDirection);
+ let value = surfaceValue;
+ if (value.x + value.y + value.z <= 0.0) { return; }
+ shadowOrigin = hitPoint + normal * params.environmentRotationAndRays.z;
+ var transmittance = 1.0;
+ if (HAS_VOLUME) { transmittance = fogTransmittance(shadowOrigin, distance); }
+ let scale = cosine * directWeight(weightMode, surfacePdf) * transmittance;
+ shadowAmount = throughput * value * lightRadiance * scale;
+ shadowDepth = depth;
+ }
shadowDirection = lightDirection;
shadowLimit = distance;
shadowPending = true;
}
+
+var<private> volumeSpan: vec2<f32>;
+
+fn clipAxis(origin: f32, axisDirection: f32, minimum: f32, maximum: f32, span: ptr<function, vec2<f32>>) -> bool {
+ if (axisDirection == 0.0) { return origin >= minimum && origin <= maximum; }
+ let first = (minimum - origin) / axisDirection;
+ let second = (maximum - origin) / axisDirection;
+ (*span).x = max((*span).x, min(first, second));
+ (*span).y = min((*span).y, max(first, second));
+ return true;
+}
+
+fn volumeInterval(origin: vec3<f32>, rayDirection: vec3<f32>, limit: f32) -> bool {
+ var span = vec2<f32>(0.0, min(limit, params.volumeAlbedoDistance.w));
+ let minimum = params.volumeMinimumDensity.xyz;
+ let maximum = params.volumeMaximumAnisotropy.xyz;
+ if (!clipAxis(origin.x, rayDirection.x, minimum.x, maximum.x, &span)) { return false; }
+ if (!clipAxis(origin.y, rayDirection.y, minimum.y, maximum.y, &span)) { return false; }
+ if (!clipAxis(origin.z, rayDirection.z, minimum.z, maximum.z, &span)) { return false; }
+ if (!(span.x < span.y)) { return false; }
+ volumeSpan = span;
+ return true;
+}
+
+fn henyeyGreensteinPhase(anisotropy: f32, cosine: f32) -> f32 {
+ let squared = anisotropy * anisotropy;
+ return (1.0 - squared) / (4.0 * PI * pow(1.0 + squared - 2.0 * anisotropy * cosine, 1.5));
+}
+
+fn sampleHenyeyGreensteinCosine(anisotropy: f32, unit: f32) -> f32 {
+ if (abs(anisotropy) < 1e-3) { return 1.0 - 2.0 * unit; }
+ let squared = anisotropy * anisotropy;
+ let ratio = (1.0 - squared) / (1.0 - anisotropy + 2.0 * anisotropy * unit);
+ return clamp((1.0 + squared - ratio * ratio) / (2.0 * anisotropy), -1.0, 1.0);
+}
+
+fn fogTransmittance(origin: vec3<f32>, distance: f32) -> f32 {
+ if (!volumeInterval(origin, lightDirection, distance)) { return 1.0; }
+ return exp(-params.volumeMinimumDensity.w * (volumeSpan.y - volumeSpan.x));
+}
+
+// Draws the next scattering event along the segment; when there is one it becomes hitPoint.
+fn scatterInFog(origin: vec3<f32>, segmentLength: f32) -> bool {
+ if (!volumeInterval(origin, direction, segmentLength)) { return false; }
+ let eventDistance = volumeSpan.x - log(1.0 - nextRandom()) / params.volumeMinimumDensity.w;
+ if (eventDistance >= volumeSpan.y) { return false; }
+ hitPoint = origin + direction * eventDistance;
+ return true;
+}
fn flushShadowRay() {
if (!shadowPending) { return; }
shadowPending = false;
@@ -631,7 +707,7 @@ fn flushShadowRay() {
}
fn reaches(bit: i32) -> bool {
- return ((hitMask >> u32(bit)) & 1u) == 1u;
+ return inMedium || ((hitMask >> u32(bit)) & 1u) == 1u;
}
// Aims lightDirection at the target and returns the distance; distanceSquared goes into aimedDistanceSquared.
@@ -763,6 +839,112 @@ fn survivesRoulette(depth: i32) -> bool {
return true;
}
+
+const WALK_STEPS: i32 = 32;
+const WALK_EXIT: i32 = 0;
+const WALK_THIN: i32 = 1;
+const WALK_LOST: i32 = 2;
+const SUBSURFACE_TEXELS: i32 = 2;
+
+var<private> subsurfaceWeight: f32 = 0.0;
+var<private> surfaceSubsurfaceChance: f32 = 0.0;
+var<private> walkWeight: vec3<f32>;
+var<private> walkDirection: vec3<f32>;
+var<private> subsurfaceNormal: vec3<f32>;
+
+fn subsurfaceVector(material: i32, offset: i32) -> vec4<f32> {
+ return materials[i32(params.extras.x) + material * SUBSURFACE_TEXELS + offset];
+}
+
+// Moves the subsurface share of the diffuse lobe to the walk; returns the material's weight.
+fn splitSubsurface() -> f32 {
+ let weight = subsurfaceVector(hitMaterialIndex, 0).x;
+ surfaceSubsurfaceChance = surfaceDiffuseChance * weight;
+ surfaceDiffuseChance -= surfaceSubsurfaceChance;
+ surfaceDiffuse *= 1.0 - weight;
+ return weight;
+}
+
+fn singleScatterAlbedo(multipleScatterAlbedo: f32) -> f32 {
+ let albedo = clamp(multipleScatterAlbedo, 0.0, 1.0);
+ let root = sqrt(9.59217 + 41.6808 * albedo + 17.7126 * albedo * albedo);
+ let offset = 4.09712 + 4.20863 * albedo - root;
+ return clamp(1.0 - offset * offset, 0.0, 1.0);
+}
+
+// Walks inward from the entry point until the walk meets the part's own surface; leaves its throughput in walkWeight.
+fn randomWalk(point: vec3<f32>, normal: vec3<f32>, meanFreePath: vec3<f32>, color: vec3<f32>, material: i32) -> i32 {
+ let extinction = 1.0 / meanFreePath;
+ let albedo = vec3<f32>(singleScatterAlbedo(color.r), singleScatterAlbedo(color.g), singleScatterAlbedo(color.b));
+ var position = point - normal * params.environmentRotationAndRays.z;
+ let frame = buildFrame(normal);
+ let radius = sqrt(nextRandom());
+ let angle = TWO_PI * nextRandom();
+ let height = sqrt(max(0.0, 1.0 - radius * radius));
+ walkDirection = frame[0] * (radius * cos(angle)) + frame[1] * (radius * sin(angle)) - normal * height;
+ for (var scatters = 0; scatters <= WALK_STEPS; scatters++) {
+ let found = intersectScene(position, walkDirection);
+ if (!found || hitMaterialIndex != material) { return select(WALK_LOST, WALK_THIN, scatters == 0); }
+ // One channel draws the distance; weighting by the mean density over the three channels keeps every channel unbiased.
+ let hero = min(2, i32(floor(nextRandom() * 3.0)));
+ let distance = -log(1.0 - nextRandom()) / extinction[hero];
+ if (distance >= hitDistance) {
+ let attenuation = exp(-extinction * hitDistance);
+ let survival = (attenuation.x + attenuation.y + attenuation.z) / 3.0;
+ if (!(survival > 0.0)) { return WALK_LOST; }
+ walkWeight *= attenuation / survival;
+ return WALK_EXIT;
+ }
+ if (scatters == WALK_STEPS) { return WALK_LOST; }
+ let falloff = exp(-extinction * distance);
+ let scatterDensity = extinction * falloff;
+ let density = (scatterDensity.x + scatterDensity.y + scatterDensity.z) / 3.0;
+ if (!(density > 0.0)) { return WALK_LOST; }
+ walkWeight *= albedo * scatterDensity / density;
+ position += walkDirection * distance;
+ let up = 2.0 * nextRandom() - 1.0;
+ let azimuth = TWO_PI * nextRandom();
+ let ring = sqrt(max(0.0, 1.0 - up * up));
+ walkDirection = vec3<f32>(ring * cos(azimuth), up, ring * sin(azimuth));
+ }
+ return WALK_LOST;
+}
+
+// Sends the diffuse light of the hit through its walk. On success the path stands where the walk left, subsurfaceNormal
+// faces out of that point, the surface is white diffuse there with its lights added, and the throughput carries the walk.
+// False when the walk ended inside the part.
+fn enterSubsurface(depth: i32, entryNormal: vec3<f32>) -> bool {
+ let block = subsurfaceVector(hitMaterialIndex, 0);
+ let colorBlock = subsurfaceVector(hitMaterialIndex, 1);
+ let color = select(colorBlock.rgb, hitColor, colorBlock.x < 0.0);
+ let material = hitMaterialIndex;
+ let entryPoint = hitPoint;
+ let entryMask = hitMask;
+ let entryScale = surfaceDiffuseShare * block.x / surfaceSubsurfaceChance;
+ walkWeight = vec3<f32>(1.0);
+ subsurfaceNormal = entryNormal;
+ let outcome = randomWalk(entryPoint, entryNormal, block.yzw, color, material);
+ if (outcome == WALK_LOST) { return false; }
+ if (outcome == WALK_EXIT) {
+ subsurfaceNormal = hitNormal * select(1.0, -1.0, dot(hitNormal, walkDirection) < 0.0);
+ throughput *= walkWeight * entryScale;
+ } else {
+ // A card: half of the colour is reflected on the side the ray came from and half is transmitted diffusely through it.
+ hitPoint = entryPoint;
+ hitMask = entryMask;
+ if (nextRandom() < 0.5) { subsurfaceNormal = -entryNormal; }
+ throughput *= color * entryScale;
+ }
+ surfaceFrame = buildFrame(subsurfaceNormal);
+ surfaceDiffuse = vec3<f32>(1.0);
+ surfaceDiffuseChance = 1.0;
+ surfaceSubsurfaceChance = 0.0;
+ surfaceSpecularChance = 0.0;
+ surfaceCoatChance = 0.0;
+ surfaceCoatWeight = 0.0;
+ addLights(depth, subsurfaceNormal);
+ return true;
+}
fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleIndex: u32) {
resetRandom(pixel, sampleIndex, params.seedAndAtlas.x);
radiance = vec3<f32>(0.0);
@@ -780,24 +962,49 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleInd
let surfaceOffset = params.environmentRotationAndRays.z;
for (var depth = 0; depth <= bounces; depth++) {
let found = intersectScene(position, direction);
- if (!found) {
+ var inFog = false;
+ if (HAS_VOLUME) { inFog = scatterInFog(position, select(params.environmentRotationAndRays.w, hitDistance, found)); }
+ if (!inFog && !found) {
if (depth == 0) { firstLegEscaped = 1.0; }
addEscape(depth, previousPdf, afterMirror);
break;
}
- let entering = dot(hitNormal, direction) < 0.0;
- normal = select(-hitNormal, hitNormal, entering);
- let isGlass = hitTransmission > 0.0 && nextRandom() < hitTransmission;
- if (!featuresRecorded) {
- featureAlbedo = select(hitColor, vec3<f32>(1.0), isGlass);
- featureNormal = normal;
- featureDepth = hitDistance;
- featuresRecorded = true;
+ var isGlass = false;
+ var entering = true;
+ var needsLights = true;
+ if (inFog) {
+ throughput *= params.volumeAlbedoDistance.xyz;
+ inMedium = true;
+ } else {
+ entering = dot(hitNormal, direction) < 0.0;
+ normal = select(-hitNormal, hitNormal, entering);
+ isGlass = hitTransmission > 0.0 && nextRandom() < hitTransmission;
+ if (!featuresRecorded) {
+ featureAlbedo = select(hitColor, vec3<f32>(1.0), isGlass);
+ featureNormal = normal;
+ featureDepth = hitDistance;
+ featuresRecorded = true;
+ }
+ addRadiance(depth, throughput * hitEmission);
+ needsLights = !isGlass;
+ if (needsLights) {
+ prepareSurface(normal, -direction);
+ if (HAS_SUBSURFACE) { subsurfaceWeight = splitSubsurface(); }
+ }
}
- addRadiance(depth, throughput * hitEmission);
- if (!isGlass) {
- prepareSurface(normal, -direction);
- addLights(depth, normal);
+ if (needsLights) { addLights(depth, normal); }
+ inMedium = false;
+ if (inFog) {
+ let phaseCosine = sampleHenyeyGreensteinCosine(params.volumeMaximumAnisotropy.w, nextRandom());
+ let phaseSine = sqrt(max(0.0, 1.0 - phaseCosine * phaseCosine));
+ let azimuth = TWO_PI * nextRandom();
+ let frame = buildFrame(direction);
+ direction = frame[0] * phaseSine * cos(azimuth) + frame[1] * phaseSine * sin(azimuth) + frame[2] * phaseCosine;
+ previousPdf = henyeyGreensteinPhase(params.volumeMaximumAnisotropy.w, phaseCosine);
+ afterMirror = false;
+ position = hitPoint;
+ if (!survivesRoulette(depth)) { break; }
+ continue;
}
if (isGlass) {
let alpha = roughnessToAlpha(hitRoughness);
@@ -809,7 +1016,16 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleInd
if (dot(direction, normal) < 0.0) { throughput *= hitColor; }
afterMirror = true;
} else {
- let lobeUnit = nextRandom();
+ var lobeUnit = nextRandom();
+ if (HAS_SUBSURFACE && subsurfaceWeight > 0.0) {
+ if (lobeUnit < surfaceSubsurfaceChance) {
+ if (!enterSubsurface(depth, normal)) { break; }
+ normal = subsurfaceNormal;
+ lobeUnit = 0.0;
+ } else {
+ lobeUnit -= surfaceSubsurfaceChance;
+ }
+ }
let firstUnit = nextRandom();
let secondUnit = nextRandom();
let isMirror = sampleSurface(lobeUnit, firstUnit, secondUnit);
@@ -832,12 +1048,26 @@ fn tracePath(origin: vec3<f32>, startDirection: vec3<f32>, pixel: u32, sampleInd
}
}
+// The same stop rule as the CPU tracer: after 16 samples, and then every 8, a pixel whose standard error of the mean luminance is
+// under the threshold times the mean plus a small floor draws no more samples. It reads only the pixel's own sums.
+fn pixelHasConverged(statistics: vec4<f32>, threshold: f32) -> bool {
+ let taken = u32(statistics.w);
+ if (taken < ADAPTIVE_MINIMUM_SAMPLES || (taken - ADAPTIVE_MINIMUM_SAMPLES) % ADAPTIVE_BATCH_SAMPLES != 0u) { return false; }
+ let count = f32(taken);
+ let mean = statistics.x / count;
+ let sampleVariance = max(0.0, statistics.y / count - mean * mean) * count / (count - 1.0);
+ return sqrt(sampleVariance / count) < threshold * (mean + CONVERGENCE_LUMINANCE_FLOOR);
+}
+
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
let width = params.sizeBouncesLights.x;
let height = params.sizeBouncesLights.y;
if (i32(id.x) >= width || i32(id.y) >= height) { return; }
let pixel = id.y * u32(width) + id.x;
+ let pixelCount = u32(width * height);
+ let noiseThreshold = params.cameraAndClamp.w;
+ if (noiseThreshold > 0.0 && pixelHasConverged(accumulation[3u * pixelCount + pixel], noiseThreshold)) { return; }
let sampleIndex = u32(params.emittersFlagsSample.w);
let seed = params.seedAndAtlas.x;
if (params.emittersFlagsSample.y != 0) { sunFrame = buildFrame(params.sunDirection.xyz); }
@@ -852,9 +1082,8 @@ fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (!(all(featureNormal >= vec3<f32>(-1.5)) && all(featureNormal < vec3<f32>(1.5)))) { featureNormal = vec3<f32>(0.0, 0.0, 1.0); }
if (!(all(featureAlbedo >= vec3<f32>(0.0)) && all(featureAlbedo < vec3<f32>(1e30)))) { featureAlbedo = vec3<f32>(1.0); }
let sampleLuminance = luminance(radiance);
- let pixelCount = u32(width * height);
accumulation[pixel] += vec4<f32>(radiance, featureDepth);
accumulation[pixelCount + pixel] += vec4<f32>(featureAlbedo, 0.0);
accumulation[2u * pixelCount + pixel] += vec4<f32>(featureNormal, 0.0);
- accumulation[3u * pixelCount + pixel] += vec4<f32>(sampleLuminance, sampleLuminance * sampleLuminance, firstLegEscaped, 0.0);
+ accumulation[3u * pixelCount + pixel] += vec4<f32>(sampleLuminance, sampleLuminance * sampleLuminance, firstLegEscaped, 1.0);
}
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
index ee9cf4f5..7c398eb6 100644
--- a/packages/render-native/src/lib.rs
+++ b/packages/render-native/src/lib.rs
@@ -19,6 +19,11 @@ const TEXEL_WORKGROUP_SIZE: u32 = 64;
/// A dispatch is at most 65535 workgroups wide; a larger bake wraps onto the second dimension.
const MAXIMUM_TEXEL_GROUPS_X: u32 = 4096;
const TRIANGLE_FLOATS: usize = 9 * 4;
+/// The parameter block is 16 vec4s: the 12 of the kernel, the fog box and medium, and the subsurface table offset.
+const PARAMETER_BYTES: usize = 16 * 16;
+/// Byte offsets of the fog density (the fourth float of the first fog vector) and of the subsurface table's vector index.
+const VOLUME_DENSITY_BYTE_OFFSET: usize = 51 * 4;
+const SUBSURFACE_OFFSET_BYTE_OFFSET: usize = 60 * 4;
/// Byte offset of the sample index inside the parameter block (`emittersFlagsSample.w`).
const SAMPLE_INDEX_BYTE_OFFSET: u64 = 43 * 4;
/// Samples submitted before the CPU waits, so a long trace never queues thousands of dispatches.
@@ -36,7 +41,7 @@ pub struct NativeTraceInput {
pub atlas: Uint32Array,
pub environment_colors: Float32Array,
pub environment_tables: Float32Array,
- /// The 12 vec4 parameter block, exactly as the browser harness writes it, as bytes.
+ /// The 16 vec4 parameter block of `packages/render-native/pack-input.mjs`, as bytes.
pub parameters: Uint8Array,
}
@@ -91,8 +96,12 @@ pub struct NativeTraceResult {
pub normal: Float32Array,
pub depth: Float32Array,
pub variance: Float32Array,
+ /// The mean number of samples a pixel drew: below the requested count when `noise_threshold` stopped converged pixels.
+ pub average_samples: f64,
pub adapter: String,
pub backend: String,
+ /// "EXPERIMENTAL_RAY_QUERY" when the device the trace ran on was opened with ray queries (the tracer needs them).
+ pub features: String,
pub setup_seconds: f64,
pub compile_seconds: f64,
pub upload_seconds: f64,
@@ -144,6 +153,7 @@ struct PreparedScene {
parameters: wgpu::Buffer,
adapter_name: String,
backend_name: String,
+ features: String,
setup_seconds: f64,
compile_seconds: f64,
upload_seconds: f64,
@@ -212,16 +222,23 @@ fn prepare_scene(input: &NativeTraceInput, shape: JobShape) -> Result<PreparedSc
return Err(failure("The triangle table must hold triangle_count triangles of 9 texels."));
}
let triangle_data: &[f32] = &input.triangles[..triangle_count * TRIANGLE_FLOATS];
- if input.parameters.len() != 12 * 16 {
- return Err(failure("The parameter block must be 192 bytes."));
+ if input.parameters.len() != PARAMETER_BYTES {
+ return Err(failure("The parameter block must be 256 bytes."));
}
let (device, queue, adapter_info) = open_device()?;
let setup_seconds = setup_started.elapsed().as_secs_f64();
let compile_started = Instant::now();
+ // Fog and subsurface scattering compile in only for a scene that uses them: the kernel declares both as false constants.
+ let fog_density = f32::from_le_bytes(input.parameters[VOLUME_DENSITY_BYTE_OFFSET..VOLUME_DENSITY_BYTE_OFFSET + 4].try_into().unwrap());
+ let subsurface_offset = u32::from_le_bytes(input.parameters[SUBSURFACE_OFFSET_BYTE_OFFSET..SUBSURFACE_OFFSET_BYTE_OFFSET + 4].try_into().unwrap());
+ let source = shape
+ .source
+ .replace("const HAS_VOLUME: bool = false;", &format!("const HAS_VOLUME: bool = {};", fog_density > 0.0))
+ .replace("const HAS_SUBSURFACE: bool = false;", &format!("const HAS_SUBSURFACE: bool = {};", subsurface_offset > 0));
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("path tracer"),
- source: wgpu::ShaderSource::Wgsl(shape.source.into()),
+ source: wgpu::ShaderSource::Wgsl(source.into()),
});
let mut layout_entries = vec![
layout_entry(
@@ -401,6 +418,7 @@ fn prepare_scene(input: &NativeTraceInput, shape: JobShape) -> Result<PreparedSc
layout: &bind_group_layout,
entries: &entries,
});
+ let features = if device.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) { "EXPERIMENTAL_RAY_QUERY" } else { "" };
Ok(PreparedScene {
device,
queue,
@@ -410,6 +428,7 @@ fn prepare_scene(input: &NativeTraceInput, shape: JobShape) -> Result<PreparedSc
parameters,
adapter_name: adapter_info.name,
backend_name: format!("{:?}", adapter_info.backend),
+ features: features.to_string(),
setup_seconds,
compile_seconds,
upload_seconds,
@@ -477,8 +496,7 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
let groups = (options.width.div_ceil(WORKGROUP_SIZE), options.height.div_ceil(WORKGROUP_SIZE));
let (sums, traced_seconds) = trace_samples(&prepared, options.samples, groups, accumulation_bytes, options.max_seconds)?;
let plane_length = pixel_count as usize * 4;
- let sample_scale = 1.0 / options.samples.max(1) as f32;
- let variance_divisor = options.samples.saturating_sub(1).max(1) as f32;
+ let mut taken_total = 0.0f64;
let mut rgba = Vec::with_capacity(pixel_count as usize * 4);
let mut albedo = Vec::with_capacity(pixel_count as usize * 3);
let mut normal = Vec::with_capacity(pixel_count as usize * 3);
@@ -488,7 +506,12 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
let radiance = &sums[pixel * 4..pixel * 4 + 4];
let albedo_sum = &sums[plane_length + pixel * 4..plane_length + pixel * 4 + 3];
let normal_sum = &sums[2 * plane_length + pixel * 4..2 * plane_length + pixel * 4 + 3];
- let statistics = &sums[3 * plane_length + pixel * 4..3 * plane_length + pixel * 4 + 2];
+ let statistics = &sums[3 * plane_length + pixel * 4..3 * plane_length + pixel * 4 + 4];
+ // A pixel that converged early drew fewer samples; its sums are divided by its own count.
+ let taken = statistics[3].max(1.0);
+ taken_total += taken as f64;
+ let sample_scale = 1.0 / taken;
+ let variance_divisor = (taken - 1.0).max(1.0);
rgba.extend_from_slice(&[radiance[0] * sample_scale, radiance[1] * sample_scale, radiance[2] * sample_scale, 1.0]);
depth.push(radiance[3] * sample_scale);
albedo.extend(albedo_sum.iter().map(|value| value * sample_scale));
@@ -502,8 +525,10 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
normal: Float32Array::new(normal),
depth: Float32Array::new(depth),
variance: Float32Array::new(variance),
+ average_samples: taken_total / pixel_count.max(1) as f64,
adapter: prepared.adapter_name,
backend: prepared.backend_name,
+ features: prepared.features,
setup_seconds: prepared.setup_seconds,
compile_seconds: prepared.compile_seconds,
upload_seconds: prepared.upload_seconds,
diff --git a/scripts/agent-native-trace.mjs b/scripts/agent-native-trace.mjs
index cdf756d1..ff1f39a1 100644
--- a/scripts/agent-native-trace.mjs
+++ b/scripts/agent-native-trace.mjs
@@ -38,6 +38,8 @@ export function createNativeTracerLocator({ importPackage = specifier => import(
let unusableReason = null;
return {
async find() {
+ // JS67_NATIVE_TRACER=off keeps a job on the gpu or cpu backend whatever is installed, which is also how the fallback is tested.
+ if (process.env.JS67_NATIVE_TRACER === 'off') return { reason: 'renderer.backend "native" is switched off by JS67_NATIVE_TRACER=off.' };
lookup ??= importNativePackage(importPackage).then(tracer => {
if (!tracer) return { reason: `renderer.backend "native" needs ${NATIVE_PACKAGE}.` };
if (!tracer.findNativeAddon()) return { reason: `renderer.backend "native" needs the built binary of ${NATIVE_PACKAGE} (npm run build in that package).` };
@@ -100,7 +102,7 @@ function withoutAlpha(rgba, pixelCount) {
* Traces one frame the page exported and returns the PNG (base64) with the job report. `denoise` is "none", "wavelet" or
* "oidn"; `denoiser` is the loaded OIDN package for "oidn". Throws when the tracer cannot run, so the caller can fall back.
*/
-export async function traceFrameNative({ tracer, exported, width, height, samples, bounces, seed, denoise, denoiser, maxSeconds }) {
+export async function traceFrameNative({ tracer, exported, width, height, samples, bounces, seed, denoise, denoiser, maxSeconds, noiseThreshold = 0 }) {
const started = performance.now();
const traced = tracer.traceNative(decodeTables(exported), { width, height, samples, maxSeconds });
const tracedSeconds = (performance.now() - started) / 1000;
@@ -109,9 +111,9 @@ export async function traceFrameNative({ tracer, exported, width, height, sample
depth: traced.depth, variance: traced.variance };
normalizeNormals(features.normal);
const report = { width, height, samples, bounces, seed, denoised: false, denoiser: 'none', threads: 1, backend: 'native',
- gpu: traced.adapter, nativeBackend: traced.backend, setupSeconds: traced.setupSeconds, compileSeconds: traced.compileSeconds,
+ gpu: traced.adapter, nativeBackend: traced.backend, nativeFeatures: traced.features, setupSeconds: traced.setupSeconds, compileSeconds: traced.compileSeconds,
uploadSeconds: traced.uploadSeconds, accelerationBuildSeconds: traced.accelerationBuildSeconds,
- averageSamples: samples, triangles: exported.triangles, tracedSeconds, ignored: exported.ignored };
+ averageSamples: traced.averageSamples ?? samples, noiseThreshold, triangles: exported.triangles, tracedSeconds, ignored: exported.ignored };
let linear = features.color;
const denoiseStarted = performance.now();
if (denoise === 'oidn') {
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index ae859d47..1fae93e1 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -805,15 +805,11 @@ window.__agentPreview = {
import('../packages/render-native/pack-input.mjs'),
]);
const environment = { ...record.scene.environment, map: agentEnvironmentMap(record.scene.environment) };
- const { sceneUsesSubsurface } = pack;
const traceScene = buildTraceScene(record.scene.parts, environment);
const camera = createCamera(record.scene.camera, options.width, options.height);
const input = buildNativeInput(traceScene, camera, options, pack);
const tables = encodeNativeTables(input);
- // The native kernel has no participating media yet, so say so instead of claiming a fog or a subsurface look it did not trace.
const ignored = describeIgnoredFeatures(record.scene.parts, environment);
- if (environment.volumeFog?.density > 0) ignored.push('volumeFog is not traced by the native backend.');
- if (sceneUsesSubsurface(traceScene.materials)) ignored.push('subsurface is not traced by the native backend.');
return { tables, triangleCount: input.triangleCount, triangles: traceScene.indices.length / 3, ignored };
},
// The PNG of linear pixels (three floats each, base64) that a denoiser outside the page returned, or of the wavelet
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 03bd715a..189caede 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -485,10 +485,10 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
let backendNote = trace.note;
if (trace.backend === 'native') {
try {
- const exported = await jobPage.evaluate(input => window.__agentPreview.exportNativeScene(input), { ...frameInput, options: { width, height, bounces: tracerOptions.bounces, seed: tracerOptions.seed, fireflyClamp: 20 } });
+ const exported = await jobPage.evaluate(input => window.__agentPreview.exportNativeScene(input), { ...frameInput, options: { width, height, bounces: tracerOptions.bounces, seed: tracerOptions.seed, fireflyClamp: 20, noiseThreshold: tracerOptions.noiseThreshold } });
traced = await traceFrameNative({ tracer: trace.tracer, exported, width, height, samples: tracerOptions.samples, bounces: tracerOptions.bounces,
seed: tracerOptions.seed, denoise: choice.denoise === true ? 'wavelet' : choice.denoise === false ? 'none' : choice.denoise, denoiser: choice.denoiser,
- maxSeconds: tracerOptions.maxSeconds });
+ maxSeconds: tracerOptions.maxSeconds, noiseThreshold: tracerOptions.noiseThreshold });
} catch (error) {
// Past maxSeconds the job fails as it does on every backend; falling back would only run it twice as long.
if (isNativeTimeLimitError(error)) throw error;
diff --git a/scripts/native-bake-page.js b/scripts/native-bake-page.js
index 16ec44dc..70a5d838 100644
--- a/scripts/native-bake-page.js
+++ b/scripts/native-bake-page.js
@@ -44,7 +44,6 @@ function floatsToBase64(values) {
*/
export async function traceTexelsOnNative(scene, texels, options) {
const [pack, { buildNativeTexelInput }] = await Promise.all([import('../src/path-tracer-gpu-pack.js'), import('../packages/render-native/pack-input.mjs')]);
- if (pack.sceneUsesSubsurface(scene.materials)) throw new Error('subsurface is not traced by the native backend');
const input = buildNativeTexelInput(scene, { texelCount: texels.count, samples: options.samples, bounces: options.bounces, seed: options.seed, fireflyClamp: options.fireflyClamp }, pack);
const answer = await globalThis.__67jsNativeBake({
action: 'trace',
diff --git a/src/path-tracer-capabilities.js b/src/path-tracer-capabilities.js
index d1ac573e..b8fcf9ca 100644
--- a/src/path-tracer-capabilities.js
+++ b/src/path-tracer-capabilities.js
@@ -16,7 +16,7 @@ export const PATH_TRACER_DENOISERS = Object.freeze(['wavelet', 'oidn', 'none']);
export const OIDN_DEFAULT_SAMPLES = 16;
export const PATH_TRACER_CAPABILITIES = Object.freeze({
- setting: 'settings.renderer { type: "pathTracer", backend ("cpu" default | "gpu" | "native"), samples, bounces, denoise (true | false | "wavelet" | "oidn" | "none"), seed, maxSeconds, noiseThreshold }; image, stills and video jobs, no passes. backend gpu needs a runtime on the GPU backend; backend native uses hardware ray queries through the optional @codepawlhq/67js-render-native package and falls back to gpu (cpu on a cpu runtime) with metrics.pathTracer.backendNote when the package, its binary or a Vulkan ray query adapter is missing (it draws no volume fog or subsurface, named in report.ignored); the report names backend, gpuCompileSeconds and gpuKernelCompiles (1 for a whole film). Past maxSeconds on one frame the job fails.',
+ setting: 'settings.renderer { type: "pathTracer", backend ("cpu" default | "gpu" | "native"), samples, bounces, denoise (true | false | "wavelet" | "oidn" | "none"), seed, maxSeconds, noiseThreshold }; image, stills and video jobs, no passes. backend gpu needs a runtime on the GPU backend; backend native uses hardware ray queries through the optional @codepawlhq/67js-render-native package and falls back to gpu (cpu on a cpu runtime) with metrics.pathTracer.backendNote when the package, its binary or a Vulkan ray query adapter is missing; it traces volume fog, subsurface and noiseThreshold; the report names backend, gpuCompileSeconds and gpuKernelCompiles (1 for a whole film). Past maxSeconds on one frame the job fails.',
noiseThreshold: 'Default 0 draws every sample. Above 0 a pixel stops once its standard error relative to its mean is under the value, checked from 16 samples on: faster and noisier, and it cost quality on spot-area (score 0.0658 at 0, 0.0900 at 0.03). docs/path-tracer.md has the table.',
traces: 'emissive maps and strength; volume fog as a uniform medium (density, colour, anisotropy, box; noise, drift and ambient are not used); the material subsurface block as a bounded random walk on the cpu and gpu backends (at most 32 scattering events, mean free path radius times scale in metres), and a card with nothing behind it as thin translucency.',
skips: 'occlusion maps, liquids, anisotropy, iridescence, sheen, caustics, depth of field, bloom; metrics.pathTracer.ignored in the job result lists what the scene asked for.',
diff --git a/tests/native-fallback-job.test.js b/tests/native-fallback-job.test.js
new file mode 100644
index 00000000..8f0446c3
--- /dev/null
+++ b/tests/native-fallback-job.test.js
@@ -0,0 +1,68 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync } from 'node:fs';
+import { copyFile, mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+// End to end: a real render job through the MCP server on a SwiftShader runtime, asked for the native backend while the
+// package is switched off (JS67_NATIVE_TRACER=off, the same answer as a missing package or an adapter without ray queries).
+// The job must run the cpu backend and give the bytes and report fields of a job that asked for cpu.
+const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');
+const recipeUrl = new URL('./fixtures/demo-room.recipe.json', import.meta.url);
+const hasBuild = existsSync(new URL('../build/mcp/server.mjs', import.meta.url));
+const chromePath = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const hasBrowser = existsSync(chromePath) || Boolean(process.env.CI);
+const DETERMINISTIC_FIELDS = ['width', 'height', 'samples', 'bounces', 'seed', 'denoised', 'denoiser', 'threads', 'backend', 'triangles', 'averageSamples', 'ignored'];
+
+async function renderDemoRoom(requestedBackend, workDirectory) {
+ const transport = new StdioClientTransport({
+ command: process.execPath,
+ args: [serverEntry, '--backend', 'cpu', '--memory', '384', '--jobs', join(workDirectory, `jobs-${requestedBackend}`)],
+ cwd: workDirectory,
+ env: { ...process.env, JS67_NATIVE_TRACER: 'off' },
+ stderr: 'ignore',
+ });
+ const client = new Client({ name: 'native-fallback-test', version: '1.0.0' });
+ await client.connect(transport);
+ try {
+ const call = (name, toolArguments) => client.callTool({ name, arguments: toolArguments }, { timeout: 300000 });
+ const recipe = JSON.parse(await readFile(recipeUrl, 'utf8'));
+ const created = (await call('scene_create', { recipe })).structuredContent;
+ const settings = { kind: 'image', width: 64, height: 64, renderer: { type: 'pathTracer', backend: requestedBackend, samples: 2, bounces: 2, denoise: false, seed: 3, maxSeconds: 120 } };
+ const submitted = await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: 0, settings });
+ assert.notEqual(submitted.isError, true, submitted.content?.[0]?.text);
+ const { jobId } = submitted.structuredContent;
+ let record;
+ for (;;) {
+ record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) break;
+ await delay(200);
+ }
+ assert.equal(record.state, 'completed', record.error);
+ const result = (await call('scene_render_result', { jobId })).structuredContent;
+ const imagePath = join(workDirectory, `${requestedBackend}.png`);
+ await copyFile(result.artifacts[0].path, imagePath);
+ return { png: await readFile(imagePath), report: (result.metrics ?? record.metrics).pathTracer };
+ } finally {
+ await client.close();
+ }
+}
+
+test('a native job without the native tracer runs the cpu backend with the same image and report fields',
+ { skip: (!hasBuild && 'run npm run build:lib first') || (!hasBrowser && 'no Chrome'), timeout: 600000 }, async context => {
+ const workDirectory = await mkdtemp(join(tmpdir(), '67js-native-fallback-'));
+ context.after(() => rm(workDirectory, { recursive: true, force: true }));
+ const cpu = await renderDemoRoom('cpu', workDirectory);
+ const native = await renderDemoRoom('native', workDirectory);
+ assert.equal(native.report.backend, 'cpu');
+ assert.match(native.report.backendNote, /switched off by JS67_NATIVE_TRACER=off.*cpu backend ran instead/);
+ assert.equal(cpu.report.backendNote, undefined);
+ assert.ok(native.png.equals(cpu.png), 'the fallback image is byte-identical to the cpu backend');
+ for (const field of DETERMINISTIC_FIELDS) assert.deepEqual(native.report[field], cpu.report[field], field);
+ const reportKeys = report => Object.keys(report).filter(key => key !== 'backendNote').sort();
+ assert.deepEqual(reportKeys(native.report), reportKeys(cpu.report));
+ });
diff --git a/tests/native-pack-input.test.js b/tests/native-pack-input.test.js
new file mode 100644
index 00000000..c3bc15b7
--- /dev/null
+++ b/tests/native-pack-input.test.js
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { readFileSync } from 'node:fs';
+import { buildNativeInput } from '../packages/render-native/pack-input.mjs';
+import { createCamera } from '../src/path-tracer.js';
+import { buildTraceScene } from '../src/path-tracer-scene.js';
+import * as pack from '../src/path-tracer-gpu-pack.js';
+
+function floor() {
+ return {
+ positions: new Float32Array([-1, 0, 1, 1, 0, 1, 1, 0, -1, -1, 0, -1]),
+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ };
+}
+
+const camera = createCamera({ eye: [0, 1, 4], target: [0, 1, 0], fov: 50 }, 16, 16);
+const options = { width: 16, height: 16, samples: 1, bounces: 2, seed: 0 };
+const plainParts = [{ name: 'floor', geometry: floor(), material: { color: [0.5, 0.5, 0.5] } }];
+const subsurfaceParts = [{ name: 'skin', geometry: floor(), material: { color: [0.7, 0.4, 0.3], subsurface: { weight: 1, radius: [1, 0.2, 0.1], scale: 0.05 } } }];
+const fog = { volumeFog: { minimum: [-30, 1, -30], maximum: [30, 2, 30], density: 0.5 } };
+
+function floatWords(input) {
+ return new Float32Array(input.parameters.buffer, input.parameters.byteOffset, input.parameters.byteLength / 4);
+}
+
+function unsignedWords(input) {
+ return new Uint32Array(input.parameters.buffer, input.parameters.byteOffset, input.parameters.byteLength / 4);
+}
+
+test('a plain scene packs no fog and no subsurface table, so the kernel compiles without either', () => {
+ const input = buildNativeInput(buildTraceScene(plainParts, {}), camera, options, pack);
+ assert.equal(input.parameters.byteLength, 16 * 16);
+ assert.equal(floatWords(input)[51], 0, 'fog density');
+ assert.equal(unsignedWords(input)[60], 0, 'subsurface offset');
+ assert.equal(floatWords(input)[35], 0, 'noise threshold');
+});
+
+test('fog packs its box, medium and density where the kernel reads them', () => {
+ const input = buildNativeInput(buildTraceScene(plainParts, fog), camera, options, pack);
+ const words = floatWords(input);
+ assert.deepEqual([...words.subarray(48, 51)], [-30, 1, -30]);
+ assert.equal(words[51], 0.5);
+ assert.deepEqual([...words.subarray(52, 55)], [30, 2, 30]);
+});
+
+test('subsurface appends its table after the materials and points the kernel at it', () => {
+ const scene = buildTraceScene(subsurfaceParts, {});
+ const plainMaterials = pack.packMaterials(scene.materials, pack.packAtlas(scene.materials)).data;
+ const input = buildNativeInput(scene, camera, options, pack);
+ const offset = unsignedWords(input)[60];
+ assert.equal(offset, plainMaterials.length / 4);
+ assert.equal(input.materials.length, plainMaterials.length + pack.packSubsurface(scene.materials).data.length);
+ assert.equal(input.materials[offset * 4], 1, 'the subsurface weight of the first material');
+});
+
+test('noiseThreshold lands in the parameter block and defaults to drawing every sample', () => {
+ const input = buildNativeInput(buildTraceScene(plainParts, {}), camera, { ...options, noiseThreshold: 0.02 }, pack);
+ assert.ok(Math.abs(floatWords(input)[35] - 0.02) < 1e-7);
+});
+
+test('the kernel declares the two constants the host rewrites and reads the vectors the packer writes', () => {
+ const kernel = readFileSync(new URL('../packages/render-native/src/kernel.wgsl', import.meta.url), 'utf8');
+ assert.match(kernel, /const HAS_VOLUME: bool = false;/);
+ assert.match(kernel, /const HAS_SUBSURFACE: bool = false;/);
+ assert.match(kernel, /volumeMinimumDensity: vec4<f32>,\s+volumeMaximumAnisotropy: vec4<f32>,\s+volumeAlbedoDistance: vec4<f32>,\s+\/\/[^\n]*\n\s+extras: vec4<u32>,/);
+});