Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an optional native ray query tracer and a bench against the browser kernel (issue #626)

Nguyen Xuan An0f55655779fb
diff --git a/bench/native-tracer/compare.sh b/bench/native-tracer/compare.sh
new file mode 100644
index 00000000..5b44c65f
--- /dev/null
+++ b/bench/native-tracer/compare.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# Alternates the native tracer and the browser WGSL kernel three times at 1920 by 1080 and 64 samples, each trace as its own
+# gpu-lock job, then scores FLIP between each pair. It needs bench/webgpu-tracer from issue #625 (pull request #629).
+# bash bench/native-tracer/compare.sh <output directory>
+set -u
+OUT="${1:?output directory}"
+for RUN in 1 2 3; do
+ bash ~/.agents/tools/gpu-lock.sh node bench/native-tracer/run.mjs "$OUT" --label "run$RUN" 2>&1 | cut -c1-1500
+ bash ~/.agents/tools/gpu-lock.sh node bench/webgpu-tracer/run.mjs "$OUT" webgpu --label "run$RUN" 2>&1 | cut -c1-1500
+done
+for RUN in 1 2 3; do
+ echo "flip run$RUN native vs webgpu: $(uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/webgpu-tracer/flip.py "$OUT/webgpu-run$RUN.png" "$OUT/native-run$RUN.png")"
+done
diff --git a/bench/native-tracer/run.mjs b/bench/native-tracer/run.mjs
new file mode 100644
index 00000000..cdccdb4a
--- /dev/null
+++ b/bench/native-tracer/run.mjs
@@ -0,0 +1,63 @@
+// One timed trace of the demo room with the native ray query tracer (packages/render-native). Run it through gpu-lock.
+// node bench/native-tracer/run.mjs <output directory> [--samples 64] [--width 1920] [--height 1080] [--label run1]
+// Writes native-<label>.png (tone mapped as the browser harness does) and native-<label>.json.
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import { buildNativeInput, traceNative } from '../../packages/render-native/index.mjs';
+import { createAgentScene, loadAllAgentSceneModules, loadMeshBooleans, needsMeshBooleans, setManifoldModuleLoader } from '../../src/agent-scene.js';
+import { agentEnvironmentMap } from '../../src/agent-look.js';
+import { encodePng } from '../../src/export-png.js';
+import * as pack from '../../src/path-tracer-gpu-pack.js';
+import { createCamera, toneMapToRgba8 } from '../../src/path-tracer.js';
+import { buildTraceScene } from '../../src/path-tracer-scene.js';
+
+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', 1920)),
+ height: Number(valueAfter('--height', 1080)),
+ samples: Number(valueAfter('--samples', 64)),
+ bounces: 8,
+ seed: 0,
+ fireflyClamp: 20,
+};
+const label = valueAfter('--label', 'run1');
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir(outputDirectory, { recursive: true });
+const recipe = JSON.parse(await readFile('tests/fixtures/demo-room.recipe.json', 'utf8'));
+await loadAllAgentSceneModules();
+if (needsMeshBooleans(recipe)) {
+ setManifoldModuleLoader(() => import('manifold-3d'));
+ await loadMeshBooleans();
+}
+const agentScene = createAgentScene(recipe);
+const environment = { ...agentScene.environment, map: agentEnvironmentMap(agentScene.environment) };
+const buildStarted = performance.now();
+const scene = buildTraceScene(agentScene.parts, environment);
+const camera = createCamera(agentScene.camera, options.width, options.height);
+const input = buildNativeInput(scene, camera, options, pack);
+const buildSeconds = (performance.now() - buildStarted) / 1000;
+
+const traceStarted = performance.now();
+const result = traceNative(input, options);
+const wallSeconds = (performance.now() - traceStarted) / 1000;
+
+const { rgba, ...numbers } = result;
+const linear = new Float32Array(options.width * options.height * 3);
+for (let pixel = 0; pixel < options.width * options.height; pixel++) {
+ linear.set(rgba.subarray(pixel * 4, pixel * 4 + 3), pixel * 3);
+}
+const toneMapped = toneMapToRgba8(linear, options.width, options.height, { viewTransform: 'aces', look: null });
+await writeFile(`${outputDirectory}/native-${label}.png`, encodePng(toneMapped, options.width, options.height));
+const record = { variant: 'native', label, ...options, triangles: scene.indices.length / 3, buildSeconds, wallSeconds, ...numbers };
+record.pathsPerSecond = (options.width * options.height * options.samples) / record.tracedSeconds;
+await writeFile(`${outputDirectory}/native-${label}.json`, JSON.stringify(record, null, 1));
+console.log(JSON.stringify(record));
diff --git a/changes/626.md b/changes/626.md
new file mode 100644
index 00000000..8c9ff131
--- /dev/null
+++ b/changes/626.md
@@ -0,0 +1 @@
+- `@codepawlhq/67js-render-native` is an optional Rust addon that traces a scene on the GPU with Vulkan ray queries, with a bench against the browser WGSL kernel (#626)
diff --git a/packages/render-native/.gitignore b/packages/render-native/.gitignore
new file mode 100644
index 00000000..6438f1c0
--- /dev/null
+++ b/packages/render-native/.gitignore
@@ -0,0 +1,2 @@
+target/
+build/
diff --git a/packages/render-native/Cargo.lock b/packages/render-native/Cargo.lock
new file mode 100644
index 00000000..92bfa1a1
--- /dev/null
+++ b/packages/render-native/Cargo.lock
@@ -0,0 +1,1034 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
+
+[[package]]
+name = "ash"
+version = "0.38.0+1.3.281"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
+dependencies = [
+ "libloading 0.8.9",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "bit-set"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+dependencies = [
+ "bytemuck_derive",
+]
+
+[[package]]
+name = "bytemuck_derive"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "codespan-reporting"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
+dependencies = [
+ "unicode-width",
+]
+
+[[package]]
+name = "convert_case"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1af709f1f33454bf52eadfc8c78b3b9ef9cb26fb54d16dc9cd9a7299f899fd1b"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "ctor"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
+
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags",
+ "objc2",
+]
+
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "futures"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gpu-allocator"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"
+dependencies = [
+ "ash",
+ "hashbrown 0.16.1",
+ "log",
+ "presser",
+ "thiserror",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "num-traits",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "allocator-api2",
+ "equivalent",
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "libloading"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libloading"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "litrs"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "naga"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bitflags",
+ "cfg-if",
+ "cfg_aliases",
+ "codespan-reporting",
+ "half",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "libm",
+ "log",
+ "naga-types",
+ "num-traits",
+ "once_cell",
+ "rustc-hash 1.1.0",
+ "spirv",
+ "thiserror",
+ "unicode-ident",
+]
+
+[[package]]
+name = "naga-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
+dependencies = [
+ "hashbrown 0.17.1",
+ "indexmap",
+ "rustc-hash 1.1.0",
+ "thiserror",
+]
+
+[[package]]
+name = "napi"
+version = "3.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "907ff7366fb7182e28edd0f08ef8ac5d6b13b8d65a3c0b3a10bf3ac092437d6b"
+dependencies = [
+ "bitflags",
+ "ctor",
+ "futures",
+ "libc",
+ "napi-build",
+ "napi-sys",
+ "nohash-hasher",
+ "rustc-hash 2.1.3",
+]
+
+[[package]]
+name = "napi-build"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b899b545d3aa6dca985939059f258c5488d34e4ecf39c274e20009748f4b846d"
+
+[[package]]
+name = "napi-derive"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d32eb00f92f84cf462fc328f49082b29c2a7d2eebeb1d447d19c1f9fdd9f89ee"
+dependencies = [
+ "convert_case",
+ "ctor",
+ "napi-derive-backend",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "napi-derive-backend"
+version = "7.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1fe28c64d8fc12e69f9b817d0febdbe7914555760f1e353106281b8ff99cc90"
+dependencies = [
+ "convert_case",
+ "proc-macro2",
+ "quote",
+ "semver",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "napi-sys"
+version = "3.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d153beb7d5c973f4b9395be8a83054a28968b61188f1dd1a2cc2321af22daea2"
+dependencies = [
+ "libloading 0.9.0",
+]
+
+[[package]]
+name = "nohash-hasher"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-metal"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"
+dependencies = [
+ "bitflags",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-metal",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "ordered-float"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pollster"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
+
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "presser"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "raw-window-metal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135"
+dependencies = [
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-quartz-core",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "render-native"
+version = "0.1.0"
+dependencies = [
+ "bytemuck",
+ "napi",
+ "napi-build",
+ "napi-derive",
+ "pollster",
+ "wgpu",
+]
+
+[[package]]
+name = "renderdoc-sys"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"
+
+[[package]]
+name = "spirv"
+version = "0.4.0+sdk-1.4.341.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-width"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
+
+[[package]]
+name = "wgpu"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e"
+dependencies = [
+ "arrayvec",
+ "bitflags",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "log",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "smallvec",
+ "static_assertions",
+ "wgpu-core",
+ "wgpu-hal",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"
+dependencies = [
+ "arrayvec",
+ "bit-set",
+ "bit-vec",
+ "bitflags",
+ "bytemuck",
+ "cfg_aliases",
+ "document-features",
+ "hashbrown 0.17.1",
+ "indexmap",
+ "log",
+ "naga",
+ "naga-types",
+ "once_cell",
+ "parking_lot",
+ "portable-atomic",
+ "profiling",
+ "raw-window-handle",
+ "rustc-hash 1.1.0",
+ "smallvec",
+ "thiserror",
+ "wgpu-core-deps-windows-linux-android",
+ "wgpu-hal",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-core-deps-windows-linux-android"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f"
+dependencies = [
+ "wgpu-hal",
+]
+
+[[package]]
+name = "wgpu-hal"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58"
+dependencies = [
+ "android_system_properties",
+ "arrayvec",
+ "ash",
+ "bitflags",
+ "bytemuck",
+ "cfg-if",
+ "cfg_aliases",
+ "gpu-allocator",
+ "hashbrown 0.17.1",
+ "libc",
+ "libloading 0.8.9",
+ "log",
+ "naga",
+ "naga-types",
+ "ordered-float",
+ "parking_lot",
+ "portable-atomic",
+ "portable-atomic-util",
+ "profiling",
+ "raw-window-handle",
+ "raw-window-metal",
+ "renderdoc-sys",
+ "smallvec",
+ "static_assertions",
+ "thiserror",
+ "wgpu-naga-bridge",
+ "wgpu-types",
+ "windows",
+]
+
+[[package]]
+name = "wgpu-naga-bridge"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081"
+dependencies = [
+ "naga",
+ "wgpu-types",
+]
+
+[[package]]
+name = "wgpu-types"
+version = "30.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286"
+dependencies = [
+ "bitflags",
+ "bytemuck",
+ "log",
+ "naga-types",
+ "raw-window-handle",
+ "static_assertions",
+]
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections",
+ "windows-core",
+ "windows-future",
+ "windows-numerics",
+]
+
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core",
+ "windows-link",
+ "windows-threading",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core",
+ "windows-link",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
diff --git a/packages/render-native/Cargo.toml b/packages/render-native/Cargo.toml
new file mode 100644
index 00000000..6caa593e
--- /dev/null
+++ b/packages/render-native/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "render-native"
+version = "0.1.0"
+edition = "2021"
+description = "Hardware ray traced stills for 67js: the WGSL path tracer with ray queries on wgpu and Vulkan."
+license = "MIT"
+publish = false
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+bytemuck = "1"
+napi = { version = "3", default-features = false, features = ["napi6"] }
+napi-derive = "3"
+pollster = "0.4"
+wgpu = { version = "30.0.1", default-features = false, features = ["vulkan", "wgsl"] }
+
+[build-dependencies]
+napi-build = "2"
+
+[profile.release]
+lto = true
+opt-level = 3
diff --git a/packages/render-native/README.md b/packages/render-native/README.md
new file mode 100644
index 00000000..6f2146e6
--- /dev/null
+++ b/packages/render-native/README.md
@@ -0,0 +1,20 @@
+# @codepawlhq/67js-render-native
+
+Optional. Traces a 67js scene on the GPU with hardware ray queries (wgpu, Vulkan) instead of the browser's software BVH walk. It uses the same WGSL path tracer as the browser kernel, so one seed gives the same picture. It is not a root dependency and no render job calls it yet.
+
+Needs Rust (stable) and a Vulkan GPU with ray queries. On Windows build for MSVC; the default GNU toolchain crashes any wgpu 30 program. The DX12 backend does not report ray queries, so the addon uses Vulkan only.
+
+```sh
+npm run build # cargo build --release, copies build/render-native.node
+```
+
+```js
+import { buildNativeInput, traceNative } from '@codepawlhq/67js-render-native';
+import * as pack from '<engine>/src/path-tracer-gpu-pack.js';
+
+const options = { width: 1920, height: 1080, samples: 64, bounces: 8, seed: 0 };
+const input = buildNativeInput(traceScene, camera, options, pack);
+const { rgba, adapter, tracedSeconds } = traceNative(input, options);
+```
+
+`rgba` is linear float RGBA, rows from the top, averaged over the samples. `bench/native-tracer` compares it with the browser kernel.
diff --git a/packages/render-native/build.mjs b/packages/render-native/build.mjs
new file mode 100644
index 00000000..4a5548d8
--- /dev/null
+++ b/packages/render-native/build.mjs
@@ -0,0 +1,17 @@
+// Builds the native addon with cargo and copies it to build/render-native.node.
+// Windows must target MSVC: the default GNU toolchain crashes any wgpu 30 program before main.
+import { spawnSync } from 'node:child_process';
+import { copyFileSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const packageDirectory = dirname(fileURLToPath(import.meta.url));
+const targetArguments = process.platform === 'win32' ? ['--target', 'x86_64-pc-windows-msvc'] : [];
+const build = spawnSync('cargo', ['build', '--release', ...targetArguments], { cwd: packageDirectory, stdio: 'inherit' });
+if (build.status !== 0) process.exit(build.status ?? 1);
+
+const releaseDirectory = join(packageDirectory, 'target', ...(targetArguments.length > 0 ? [targetArguments[1]] : []), 'release');
+const libraryName = { win32: 'render_native.dll', darwin: 'librender_native.dylib', linux: 'librender_native.so' }[process.platform];
+mkdirSync(join(packageDirectory, 'build'), { recursive: true });
+copyFileSync(join(releaseDirectory, libraryName), join(packageDirectory, 'build', 'render-native.node'));
+console.log('Built build/render-native.node');
diff --git a/packages/render-native/build.rs b/packages/render-native/build.rs
new file mode 100644
index 00000000..0f1b0100
--- /dev/null
+++ b/packages/render-native/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ napi_build::setup();
+}
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
new file mode 100644
index 00000000..a1ed6a25
--- /dev/null
+++ b/packages/render-native/index.mjs
@@ -0,0 +1,74 @@
+// Hardware ray traced stills for 67js: loads the native addon built by `npm run build` and traces a packed scene on the
+// GPU with Vulkan ray queries. The addon is not in this package; without it `findNativeAddon()` returns null.
+import { existsSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const PACKAGE_DIRECTORY = dirname(fileURLToPath(import.meta.url));
+const ADDON_PATH = join(PACKAGE_DIRECTORY, 'build', 'render-native.node');
+const PARAMETER_BYTES = 12 * 16;
+const SUN_CONE_COSINE = Math.cos(Math.PI / 360);
+
+/** The path of the built addon, or null when `npm run build` has not run. */
+export function findNativeAddon() {
+ return existsSync(ADDON_PATH) ? ADDON_PATH : null;
+}
+
+function writeParameters(scene, camera, options, lightCount, atlasWidth) {
+ const buffer = new ArrayBuffer(PARAMETER_BYTES);
+ const floats = new Float32Array(buffer);
+ const integers = new Int32Array(buffer);
+ const words = new Uint32Array(buffer);
+ const { sun } = scene.lights;
+ const { environment } = scene;
+ floats.set([...camera.eye, 0], 0);
+ floats.set([...camera.forward, 0], 4);
+ floats.set([...camera.right, 0], 8);
+ floats.set([...camera.above, 0], 12);
+ floats.set([...(sun?.direction ?? [0, 1, 0]), 0], 16);
+ 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);
+ 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);
+ return new Uint8Array(buffer);
+}
+
+/**
+ * Packs a trace scene (from `buildTraceScene`) and its camera into the tables the kernel reads.
+ * `pack` is the module `src/path-tracer-gpu-pack.js`, passed in so this package never imports the engine's source.
+ */
+export function buildNativeInput(scene, camera, options, pack) {
+ const atlas = pack.packAtlas(scene.materials);
+ const lights = pack.packLights(scene.lights);
+ const environment = pack.packEnvironment(scene.environment);
+ const environmentTables = new Float32Array(environment ? environment.height + environment.width * environment.height : 4);
+ if (environment) {
+ environmentTables.set(environment.rows.data.subarray(0, environment.height), 0);
+ environmentTables.set(environment.pixels.data.subarray(0, environment.width * environment.height), environment.height);
+ }
+ return {
+ triangles: pack.packTriangles(scene).data,
+ triangleCount: scene.bvh.triangleOrder.length,
+ materials: pack.packMaterials(scene.materials, atlas).data,
+ 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),
+ };
+}
+
+/**
+ * Traces the input on the GPU and resolves linear RGBA float data (`rgba`, width * height * 4, rows from the top, the
+ * average of `samples` paths) with the adapter name and timings in seconds.
+ */
+export function traceNative(input, { width, height, samples }) {
+ const addonPath = findNativeAddon();
+ if (!addonPath) throw new Error('The native tracer is not built. Run `npm run build` in packages/render-native.');
+ const addon = createRequire(import.meta.url)(addonPath);
+ return addon.traceScene(input, { width, height, samples });
+}
diff --git a/packages/render-native/package.json b/packages/render-native/package.json
new file mode 100644
index 00000000..1e7d3e6d
--- /dev/null
+++ b/packages/render-native/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "@codepawlhq/67js-render-native",
+ "version": "0.1.0",
+ "description": "Optional hardware ray traced stills for 67js: the path tracer on wgpu and Vulkan ray queries. Not part of the core archive.",
+ "type": "module",
+ "main": "./index.mjs",
+ "exports": {
+ ".": "./index.mjs"
+ },
+ "files": [
+ "index.mjs",
+ "build.mjs",
+ "build.rs",
+ "Cargo.toml",
+ "src",
+ "README.md"
+ ],
+ "scripts": {
+ "build": "node build.mjs"
+ },
+ "license": "MIT",
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/packages/render-native/src/kernel.wgsl b/packages/render-native/src/kernel.wgsl
new file mode 100644
index 00000000..20ebadae
--- /dev/null
+++ b/packages/render-native/src/kernel.wgsl
@@ -0,0 +1,873 @@
+enable wgpu_ray_query;
+
+const PI: f32 = 3.14159265358979;
+const TWO_PI: f32 = 6.28318530717959;
+const TRIANGLE_TEXELS: i32 = 9;
+const MATERIAL_TEXELS: i32 = 10;
+const LIGHT_TEXELS: i32 = 6;
+const ALPHA_STEP_LIMIT: i32 = 8;
+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;
+
+struct Params {
+ eye: vec4<f32>,
+ forward: vec4<f32>,
+ right: vec4<f32>,
+ above: vec4<f32>,
+ sunDirection: vec4<f32>,
+ sunColorAndCosine: vec4<f32>,
+ environmentShape: vec4<f32>,
+ environmentRotationAndRays: vec4<f32>,
+ cameraAndClamp: vec4<f32>,
+ sizeBouncesLights: vec4<i32>,
+ emittersFlagsSample: vec4<i32>,
+ seedAndAtlas: vec4<u32>,
+}
+
+@group(0) @binding(0) var<uniform> params: Params;
+@group(0) @binding(1) var sceneStructure: acceleration_structure;
+@group(0) @binding(2) var<storage, read> triangles: array<vec4<f32>>;
+@group(0) @binding(3) var<storage, read> materials: array<vec4<f32>>;
+@group(0) @binding(4) var<storage, read> lights: array<vec4<f32>>;
+@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.
+@group(0) @binding(8) var<storage, read_write> accumulation: array<vec4<f32>>;
+
+var<private> rngState: u32 = 1u;
+
+fn resetRandom(pixel: u32, sampleIndex: u32, seed: u32) {
+ var mixed = ((pixel + 0x9e3779b9u) * 0x85ebca6bu) ^ ((sampleIndex + 0x7f4a7c15u) * 0xc2b2ae35u) ^ ((seed + 0x165667b1u) * 0x27d4eb2fu);
+ mixed = (mixed ^ (mixed >> 15u)) * 0x2c1b3c6du;
+ mixed = (mixed ^ (mixed >> 12u)) * 0x297a2d39u;
+ mixed ^= mixed >> 15u;
+ rngState = select(mixed, 1u, mixed == 0u);
+}
+
+fn nextRandom() -> f32 {
+ rngState = rngState * 747796405u + 2891336453u;
+ var word = ((rngState >> ((rngState >> 28u) + 4u)) ^ rngState) * 277803737u;
+ word = (word >> 22u) ^ word;
+ return f32(word >> 8u) / 16777216.0;
+}
+
+fn hashJitter(pixel: u32, sampleIndex: u32, seed: u32, dimension: u32) -> f32 {
+ var mixed = ((pixel ^ 0x51ed270bu) * 0x9e3779b1u) ^ ((sampleIndex + dimension * 0x632be5abu) * 0x85ebca6bu) ^ ((seed + 0x1b873593u) * 0xc2b2ae35u);
+ mixed = (mixed ^ (mixed >> 16u)) * 0x7feb352du;
+ mixed = (mixed ^ (mixed >> 15u)) * 0x846ca68bu;
+ mixed ^= mixed >> 16u;
+ return f32(mixed >> 8u) / 16777216.0;
+}
+
+fn luminance(color: vec3<f32>) -> f32 {
+ return dot(color, vec3<f32>(0.2126, 0.7152, 0.0722));
+}
+
+// ---- Ray queries ----
+
+var<private> nearestDistance: f32;
+var<private> nearestSlot: i32;
+var<private> nearestU: f32;
+var<private> nearestV: f32;
+
+// The hardware ray query replaces the software BVH walk. The acceleration structure holds the triangles of the packed
+// table in order, so a primitive index is the same slot the browser kernel finds, and the barycentrics are the weights of
+// the second and third corner, as nearestU and nearestV were.
+const RAY_FLAG_TERMINATE_ON_FIRST_HIT: u32 = 4u;
+
+fn traceRay(origin: vec3<f32>, direction: vec3<f32>, limit: f32, anyHit: bool) {
+ nearestDistance = limit;
+ nearestSlot = -1;
+ var query: ray_query;
+ let flags = select(0u, RAY_FLAG_TERMINATE_ON_FIRST_HIT, anyHit);
+ rayQueryInitialize(&query, sceneStructure, RayDesc(flags, 0xFFu, 0.0, limit, origin, direction));
+ while (rayQueryProceed(&query)) {}
+ let hit = rayQueryGetCommittedIntersection(&query);
+ if (hit.kind == RAY_QUERY_INTERSECTION_NONE) { return; }
+ nearestDistance = hit.t;
+ nearestSlot = i32(hit.primitive_index);
+ nearestU = hit.barycentrics.x;
+ nearestV = hit.barycentrics.y;
+}
+
+// ---- Hits ----
+
+var<private> hitDistance: f32;
+var<private> hitPoint: vec3<f32>;
+var<private> hitNormal: vec3<f32>;
+var<private> hitColor: vec3<f32>;
+var<private> hitEmission: vec3<f32>;
+var<private> hitMetallic: f32;
+var<private> hitRoughness: f32;
+var<private> hitClearcoat: f32;
+var<private> hitClearcoatRoughness: f32;
+var<private> hitTransmission: f32;
+var<private> hitIor: f32;
+var<private> hitCutoff: f32;
+var<private> hitMask: u32;
+
+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));
+}
+
+fn atlasTexel(x: i32, y: i32) -> vec4<f32> {
+ return unpack4x8unorm(atlas[u32(y) * params.seedAndAtlas.y + u32(x)]);
+}
+
+fn sampleAtlas(rectangle: vec4<f32>, flags: f32, uv: vec2<f32>) -> vec4<f32> {
+ if (rectangle.z <= 0.0) { return vec4<f32>(1.0); }
+ let width = i32(rectangle.z);
+ let height = i32(rectangle.w);
+ let repeat = (flags % 2.0) >= 1.0;
+ let encoded = flags >= 2.0;
+ let x = uv.x * rectangle.z - 0.5;
+ let y = uv.y * rectangle.w - 0.5;
+ let left = floor(x);
+ let top = floor(y);
+ let shareX = x - left;
+ let shareY = y - top;
+ var total = vec4<f32>(0.0);
+ for (var corner = 0; corner < 4; corner++) {
+ var column = i32(left) + (corner & 1);
+ var row = i32(top) + (corner >> 1u);
+ if (repeat) {
+ column = ((column % width) + width) % width;
+ row = ((row % height) + height) % height;
+ } else {
+ column = clamp(column, 0, width - 1);
+ row = clamp(row, 0, height - 1);
+ }
+ let weight = select(1.0 - shareX, shareX, (corner & 1) == 1) * select(1.0 - shareY, shareY, (corner >> 1u) == 1);
+ let texel = atlasTexel(i32(rectangle.x) + column, i32(rectangle.y) + row);
+ let color = select(texel.rgb, srgbToLinear(texel.rgb), encoded);
+ total += weight * vec4<f32>(color, texel.a);
+ }
+ return total;
+}
+
+fn applyNormalMap(rectangle: vec4<f32>, flags: f32, scale: vec2<f32>, edgeOne: vec3<f32>, edgeTwo: vec3<f32>, uvOne: vec2<f32>, uvTwo: vec2<f32>, uv: vec2<f32>) {
+ let determinant = uvOne.x * uvTwo.y - uvTwo.x * uvOne.y;
+ if (abs(determinant) < 1e-12) { return; }
+ let normal = hitNormal;
+ var tangent = (edgeOne * uvTwo.y - edgeTwo * uvOne.y) / determinant;
+ let bitangent = (edgeTwo * uvOne.x - edgeOne * uvTwo.x) / determinant;
+ tangent -= normal * dot(tangent, normal);
+ let tangentLength = length(tangent);
+ if (tangentLength == 0.0) { return; }
+ tangent /= tangentLength;
+ var across = cross(normal, tangent);
+ var acrossLength = length(across);
+ if (acrossLength == 0.0) { acrossLength = 1.0; }
+ let handedness = select(1.0, -1.0, dot(across, bitangent) < 0.0);
+ across *= handedness / acrossLength;
+ let texel = sampleAtlas(rectangle, flags, uv).rgb;
+ let sideways = (texel.x * 2.0 - 1.0) * scale.x;
+ let forwards = (texel.y * 2.0 - 1.0) * scale.y;
+ let outwards = texel.z * 2.0 - 1.0;
+ let mapped = tangent * sideways + across * forwards + normal * outwards;
+ let mappedLength = length(mapped);
+ if (!(mappedLength > 1e-6)) { return; }
+ hitNormal = mapped / mappedLength;
+}
+
+// Fills the hit globals from the triangle in nearestSlot; returns the alpha of the colour map.
+fn fillHit(origin: vec3<f32>, direction: vec3<f32>, distance: f32) -> f32 {
+ let base = nearestSlot * TRIANGLE_TEXELS;
+ let cornerData = triangles[base];
+ let edgeOne = triangles[base + 1].xyz;
+ let edgeTwo = triangles[base + 2].xyz;
+ let normalOneData = triangles[base + 3];
+ let normalTwoData = triangles[base + 4];
+ let normalThreeData = triangles[base + 5];
+ let colorOneData = triangles[base + 6];
+ let colorTwoData = triangles[base + 7];
+ let colorThreeData = triangles[base + 8];
+ let secondWeight = nearestU;
+ let thirdWeight = nearestV;
+ let firstWeight = 1.0 - secondWeight - thirdWeight;
+ hitDistance = distance;
+ hitPoint = origin + direction * distance;
+ let normal = firstWeight * normalOneData.xyz + secondWeight * normalTwoData.xyz + thirdWeight * normalThreeData.xyz;
+ let normalLength = length(normal);
+ 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;
+ let colorMetallic = materials[material];
+ let emissionRoughness = materials[material + 1];
+ let coating = materials[material + 2];
+ let shape = materials[material + 3];
+ let flagsOne = materials[material + 4];
+ let flagsTwo = materials[material + 5];
+ hitColor = colorMetallic.rgb * vertexColor;
+ hitEmission = emissionRoughness.rgb;
+ hitMetallic = colorMetallic.w;
+ hitRoughness = emissionRoughness.w;
+ hitClearcoat = coating.x;
+ hitClearcoatRoughness = coating.y;
+ hitTransmission = coating.z;
+ hitIor = coating.w;
+ hitCutoff = shape.z;
+ hitMask = u32(shape.w) | (u32(flagsOne.x) << 16u);
+ var alpha = 1.0;
+ let mapRectangle = materials[material + 6];
+ if (mapRectangle.z > 0.0) {
+ let texel = sampleAtlas(mapRectangle, flagsOne.y, uv);
+ hitColor *= texel.rgb;
+ alpha = texel.a;
+ }
+ let emissiveRectangle = materials[material + 9];
+ if (emissiveRectangle.z > 0.0) { hitEmission *= sampleAtlas(emissiveRectangle, flagsTwo.x, uv).rgb; }
+ let surfaceRectangle = materials[material + 8];
+ if (surfaceRectangle.z > 0.0) {
+ let texel = sampleAtlas(surfaceRectangle, flagsOne.w, uv);
+ hitRoughness *= texel.g;
+ hitMetallic *= texel.b;
+ }
+ let normalRectangle = materials[material + 7];
+ if (normalRectangle.z > 0.0) {
+ let uvOne = vec2<f32>(normalTwoData.w - normalOneData.w, colorTwoData.w - colorOneData.w);
+ let uvTwo = vec2<f32>(normalThreeData.w - normalOneData.w, colorThreeData.w - colorOneData.w);
+ applyNormalMap(normalRectangle, flagsOne.z, shape.xy, edgeOne, edgeTwo, uvOne, uvTwo, uv);
+ }
+ return alpha;
+}
+
+// The nearest solid hit, stepping through the transparent texels of cutout materials.
+fn intersectScene(origin: vec3<f32>, direction: vec3<f32>) -> bool {
+ var start = origin;
+ var travelled = 0.0;
+ let farDistance = params.environmentRotationAndRays.w;
+ let surfaceOffset = params.environmentRotationAndRays.z;
+ for (var attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
+ traceRay(start, direction, farDistance, false);
+ if (nearestSlot < 0) { return false; }
+ let foundDistance = nearestDistance;
+ let alpha = fillHit(start, direction, foundDistance);
+ if (hitCutoff == 0.0 || alpha >= hitCutoff) {
+ hitDistance += travelled;
+ return true;
+ }
+ let advance = foundDistance + surfaceOffset;
+ travelled += advance;
+ start += direction * advance;
+ }
+ return false;
+}
+
+// The alpha of the colour map at the nearest hit, without touching the hit globals a shadow ray must not disturb.
+fn alphaAtNearestHit() -> f32 {
+ let base = nearestSlot * TRIANGLE_TEXELS;
+ let secondWeight = nearestU;
+ let thirdWeight = nearestV;
+ let firstWeight = 1.0 - secondWeight - thirdWeight;
+ let first = triangles[base + 3];
+ let second = triangles[base + 4];
+ let third = triangles[base + 5];
+ let uv = firstWeight * vec2<f32>(first.w, triangles[base + 6].w) + secondWeight * vec2<f32>(second.w, triangles[base + 7].w) + thirdWeight * vec2<f32>(third.w, triangles[base + 8].w);
+ let material = i32(triangles[base].w) * MATERIAL_TEXELS;
+ let mapRectangle = materials[material + 6];
+ if (mapRectangle.z <= 0.0) { return 1.0; }
+ return sampleAtlas(mapRectangle, materials[material + 4].y, uv).a;
+}
+
+fn occluded(origin: vec3<f32>, direction: vec3<f32>, limit: f32) -> bool {
+ var start = origin;
+ var remaining = limit;
+ let surfaceOffset = params.environmentRotationAndRays.z;
+ for (var attempt = 0; attempt < ALPHA_STEP_LIMIT; attempt++) {
+ traceRay(start, direction, remaining, true);
+ if (nearestSlot < 0) { return false; }
+ let material = i32(triangles[nearestSlot * TRIANGLE_TEXELS].w) * MATERIAL_TEXELS;
+ let cutoff = materials[material + 3].z;
+ if (cutoff == 0.0) { return true; }
+ if (alphaAtNearestHit() >= cutoff) { return true; }
+ let advance = nearestDistance + surfaceOffset;
+ remaining -= advance;
+ if (remaining <= 0.0) { return false; }
+ start += direction * advance;
+ }
+ return true;
+}
+
+// ---- Frames ----
+
+fn buildFrame(normal: vec3<f32>) -> mat3x3<f32> {
+ let helperIsX = abs(normal.x) < 0.9;
+ let helperX = select(0.0, 1.0, helperIsX);
+ let helperY = select(1.0, 0.0, helperIsX);
+ let tangent = normalize(vec3<f32>(-normal.z * helperY, normal.z * helperX, normal.x * helperY - normal.y * helperX));
+ return mat3x3<f32>(tangent, cross(normal, tangent), normal);
+}
+
+fn localToWorld(frame: mat3x3<f32>, local: vec3<f32>) -> vec3<f32> {
+ return frame * local;
+}
+
+fn worldToLocal(frame: mat3x3<f32>, world: vec3<f32>) -> vec3<f32> {
+ return transpose(frame) * world;
+}
+
+// ---- Environment map ----
+
+fn environmentRadiance(direction: vec3<f32>) -> vec3<f32> {
+ let width = params.environmentShape.x;
+ let height = params.environmentShape.y;
+ let cosine = params.environmentRotationAndRays.x;
+ let sine = params.environmentRotationAndRays.y;
+ let mapX = cosine * direction.x - sine * direction.z;
+ let mapZ = sine * direction.x + cosine * direction.z;
+ let column = (atan2(mapX, -mapZ) / TWO_PI + 0.5) * width - 0.5;
+ let row = acos(clamp(direction.y, -1.0, 1.0)) / PI * height - 0.5;
+ let left = floor(column);
+ let top = floor(row);
+ let shareX = column - left;
+ let shareY = row - top;
+ let columns = i32(width);
+ let rows = i32(height);
+ var total = vec3<f32>(0.0);
+ for (var corner = 0; corner < 4; corner++) {
+ let cornerColumn = ((i32(left) + (corner & 1)) % columns + columns) % columns;
+ let cornerRow = clamp(i32(top) + (corner >> 1u), 0, rows - 1);
+ let weight = select(1.0 - shareX, shareX, (corner & 1) == 1) * select(1.0 - shareY, shareY, (corner >> 1u) == 1);
+ total += weight * environmentColors[cornerRow * columns + cornerColumn].rgb * params.environmentShape.z;
+ }
+ return total;
+}
+
+fn environmentPdf(direction: vec3<f32>) -> f32 {
+ let width = params.environmentShape.x;
+ let height = params.environmentShape.y;
+ let cosine = params.environmentRotationAndRays.x;
+ let sine = params.environmentRotationAndRays.y;
+ let mapX = cosine * direction.x - sine * direction.z;
+ let mapZ = sine * direction.x + cosine * direction.z;
+ let column = min(i32(width) - 1, i32(floor((atan2(mapX, -mapZ) / TWO_PI + 0.5) * width)));
+ let polar = acos(clamp(direction.y, -1.0, 1.0));
+ let row = min(i32(height) - 1, i32(floor(polar / PI * height)));
+ let sinePolar = max(sin(polar), 1e-6);
+ let rowWeight = sin(PI * (f32(row) + 0.5) / height);
+ let texel = environmentColors[row * i32(width) + column].rgb;
+ let weight = (luminance(texel) + 1e-6) * rowWeight;
+ return weight / params.environmentShape.w * width * height / (TWO_PI * PI * sinePolar);
+}
+
+// The cumulative row table sits first in environmentTables, the per-pixel tables follow it.
+fn firstIndexAbove(tableOffset: i32, start: i32, end: i32, threshold: f32) -> i32 {
+ var low = start;
+ var high = end - 1;
+ for (var step = 0; step < 24; step++) {
+ if (low >= high) { break; }
+ let middle = (low + high) >> 1u;
+ if (environmentTables[tableOffset + middle] < threshold) { low = middle + 1; } else { high = middle; }
+ }
+ return low;
+}
+
+var<private> sampledDirection: vec3<f32>;
+
+// Draws a direction in proportion to the map's light into sampledDirection; returns its pdf.
+fn sampleEnvironment(rowUnit: f32, columnUnit: f32, columnJitter: f32, rowJitter: f32) -> f32 {
+ let width = i32(params.environmentShape.x);
+ let height = i32(params.environmentShape.y);
+ let row = firstIndexAbove(0, 0, height, rowUnit);
+ let rowBase = row * width;
+ let column = firstIndexAbove(height, rowBase, rowBase + width, columnUnit) - rowBase;
+ let polar = PI * (f32(row) + rowJitter) / f32(height);
+ let azimuth = ((f32(column) + columnJitter) / f32(width) - 0.5) * TWO_PI;
+ let sinePolar = sin(polar);
+ let mapX = sinePolar * sin(azimuth);
+ let mapZ = -sinePolar * cos(azimuth);
+ let cosine = params.environmentRotationAndRays.x;
+ let sine = params.environmentRotationAndRays.y;
+ sampledDirection = vec3<f32>(cosine * mapX + sine * mapZ, cos(polar), -sine * mapX + cosine * mapZ);
+ return environmentPdf(sampledDirection);
+}
+
+// ---- Microfacet pieces ----
+
+fn ggxDistribution(alpha: f32, cosineHalf: f32) -> f32 {
+ let alphaSquared = alpha * alpha;
+ let denominator = cosineHalf * cosineHalf * (alphaSquared - 1.0) + 1.0;
+ return alphaSquared / (PI * denominator * denominator);
+}
+
+fn smithMasking(alpha: f32, cosine: f32) -> f32 {
+ let alphaSquared = alpha * alpha;
+ return 2.0 * cosine / (cosine + sqrt(alphaSquared + (1.0 - alphaSquared) * cosine * cosine));
+}
+
+fn schlick(reflectanceAtNormal: f32, cosine: f32) -> f32 {
+ let weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);
+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;
+}
+
+fn schlickColor(reflectanceAtNormal: vec3<f32>, cosine: f32) -> vec3<f32> {
+ let weight = pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0);
+ return reflectanceAtNormal + (1.0 - reflectanceAtNormal) * weight;
+}
+
+fn sampleVisibleNormal(view: vec3<f32>, alpha: f32, firstUnit: f32, secondUnit: f32) -> vec3<f32> {
+ var stretched = vec3<f32>(alpha * view.x, alpha * view.y, view.z);
+ let stretchedLength = length(stretched);
+ stretched /= stretchedLength;
+ let heightAxis = stretched.z;
+ let planeLength = length(stretched.xy);
+ let planeDirection = select(vec2<f32>(0.0), stretched.xy / planeLength, planeLength > 0.0);
+ let tangent = select(vec2<f32>(1.0, 0.0), vec2<f32>(-stretched.y, stretched.x) / planeLength, planeLength > 0.0);
+ let bitangentXY = -heightAxis * planeDirection;
+ let bitangentZ = planeLength;
+ let radius = sqrt(firstUnit);
+ let angle = TWO_PI * secondUnit;
+ let diskX = radius * cos(angle);
+ var diskY = radius * sin(angle);
+ let blend = 0.5 * (1.0 + heightAxis);
+ diskY = (1.0 - blend) * sqrt(1.0 - diskX * diskX) + blend * diskY;
+ let lift = sqrt(max(0.0, 1.0 - diskX * diskX - diskY * diskY));
+ let normalXY = diskX * tangent + diskY * bitangentXY + lift * stretched.xy;
+ let normalZ = diskY * bitangentZ + lift * heightAxis;
+ let unstretched = vec3<f32>(alpha * normalXY.x, alpha * normalXY.y, max(0.0, normalZ));
+ return unstretched / length(unstretched);
+}
+
+fn roughnessToAlpha(roughness: f32) -> f32 {
+ return max(roughness * roughness, MINIMUM_ALPHA);
+}
+
+// ---- The layered surface ----
+
+var<private> surfaceFrame: mat3x3<f32>;
+var<private> surfaceView: vec3<f32>;
+var<private> surfaceViewCosine: f32;
+var<private> surfaceDiffuse: vec3<f32>;
+var<private> surfaceSpecularNormal: vec3<f32>;
+var<private> surfaceSpecularWeight: f32;
+var<private> surfaceSpecularAlpha: f32;
+var<private> surfaceCoatWeight: f32;
+var<private> surfaceCoatChance: f32;
+var<private> surfaceSampledCoat: bool;
+var<private> surfaceCoatAlpha: f32;
+var<private> surfaceDiffuseChance: f32;
+var<private> surfaceSpecularChance: f32;
+var<private> surfaceValue: vec3<f32>;
+var<private> surfacePdf: f32;
+
+fn dielectricSpecularAlbedo(normalReflectance: f32, roughness: f32, viewCosine: f32) -> f32 {
+ let smoothness = 1.0 - roughness;
+ let slope = min(smoothness * smoothness, exp2(-9.28 * viewCosine)) * smoothness + (0.0425 - 0.0275 * roughness);
+ let scale = 1.04 - 0.572 * roughness - 1.04 * slope;
+ let offset = 1.04 * slope + 0.022 * roughness - 0.04;
+ return clamp(normalReflectance * scale + offset, 0.0, 1.0);
+}
+
+fn prepareSurface(normal: vec3<f32>, view: vec3<f32>) {
+ surfaceFrame = buildFrame(normal);
+ surfaceView = view;
+ let viewCosine = max(dot(normal, view), 1e-4);
+ surfaceViewCosine = viewCosine;
+ let ratio = (hitIor - 1.0) / (hitIor + 1.0);
+ let dielectricNormalReflectance = ratio * ratio;
+ let dielectricFresnel = dielectricSpecularAlbedo(dielectricNormalReflectance, hitRoughness, viewCosine);
+ surfaceCoatWeight = select(0.0, hitClearcoat * schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), hitClearcoat > 0.0);
+ let underCoat = 1.0 - surfaceCoatWeight;
+ let diffuseShare = (1.0 - hitMetallic) * (1.0 - dielectricFresnel) * underCoat;
+ surfaceDiffuse = hitColor * diffuseShare;
+ surfaceSpecularNormal = vec3<f32>(dielectricNormalReflectance * (1.0 - hitMetallic)) + hitColor * hitMetallic;
+ let specularLuminance = luminance(surfaceSpecularNormal);
+ surfaceSpecularWeight = underCoat;
+ surfaceSpecularAlpha = roughnessToAlpha(hitRoughness);
+ surfaceCoatAlpha = roughnessToAlpha(hitClearcoatRoughness);
+ let diffuseLuminance = luminance(surfaceDiffuse);
+ let specularChance = schlick(specularLuminance, viewCosine) * underCoat;
+ let coatChance = surfaceCoatWeight;
+ let sum = diffuseLuminance + specularChance + coatChance;
+ surfaceDiffuseChance = select(1.0, diffuseLuminance / sum, sum > 0.0);
+ surfaceSpecularChance = select(0.0, specularChance / sum, sum > 0.0);
+ surfaceCoatChance = select(0.0, coatChance / sum, sum > 0.0);
+}
+
+fn microfacetTerm(alpha: f32, viewCosine: f32, lightCosine: f32, halfCosine: f32) -> f32 {
+ return ggxDistribution(alpha, halfCosine) * smithMasking(alpha, viewCosine) * smithMasking(alpha, lightCosine) / (4.0 * viewCosine * lightCosine);
+}
+
+fn evaluateSurface(lightDirection: vec3<f32>) {
+ surfaceValue = vec3<f32>(0.0);
+ surfacePdf = 0.0;
+ let normal = surfaceFrame[2];
+ let lightCosine = dot(normal, lightDirection);
+ if (lightCosine <= 0.0) { return; }
+ var halfVector = surfaceView + lightDirection;
+ let halfLength = length(halfVector);
+ halfVector /= select(halfLength, 1.0, halfLength == 0.0);
+ let halfCosine = dot(normal, halfVector);
+ let viewHalfCosine = max(dot(surfaceView, halfVector), 0.0);
+ let viewCosine = surfaceViewCosine;
+ surfacePdf += surfaceDiffuseChance * lightCosine / PI;
+ surfaceValue += surfaceDiffuse / PI;
+ if (surfaceSpecularChance > 0.0 && surfaceSpecularAlpha > MIRROR_ALPHA) {
+ let alpha = surfaceSpecularAlpha;
+ let term = microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * surfaceSpecularWeight;
+ surfaceValue += schlickColor(surfaceSpecularNormal, viewHalfCosine) * term;
+ surfacePdf += surfaceSpecularChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4.0 * viewCosine);
+ }
+ if (surfaceCoatChance > 0.0 && surfaceCoatAlpha > MIRROR_ALPHA) {
+ let alpha = surfaceCoatAlpha;
+ let reflectance = schlick(DIELECTRIC_COAT_REFLECTANCE, viewHalfCosine) * microfacetTerm(alpha, viewCosine, lightCosine, halfCosine) * (surfaceCoatWeight / max(schlick(DIELECTRIC_COAT_REFLECTANCE, viewCosine), 1e-6));
+ surfaceValue += vec3<f32>(reflectance);
+ surfacePdf += surfaceCoatChance * smithMasking(alpha, viewCosine) * ggxDistribution(alpha, halfCosine) / (4.0 * viewCosine);
+ }
+}
+
+// The next direction of a path goes into sampledDirection; returns true for a mirror lobe, which is followed exactly.
+fn sampleSurface(lobeUnit: f32, firstUnit: f32, secondUnit: f32) -> bool {
+ if (lobeUnit < surfaceDiffuseChance) {
+ let radius = sqrt(firstUnit);
+ let angle = TWO_PI * secondUnit;
+ sampledDirection = localToWorld(surfaceFrame, vec3<f32>(radius * cos(angle), radius * sin(angle), sqrt(max(0.0, 1.0 - firstUnit))));
+ return false;
+ }
+ let isCoat = lobeUnit >= surfaceDiffuseChance + surfaceSpecularChance;
+ surfaceSampledCoat = isCoat;
+ let alpha = select(surfaceSpecularAlpha, surfaceCoatAlpha, isCoat);
+ let localView = worldToLocal(surfaceFrame, surfaceView);
+ if (alpha <= MIRROR_ALPHA) {
+ sampledDirection = 2.0 * surfaceViewCosine * surfaceFrame[2] - surfaceView;
+ return true;
+ }
+ let localHalf = sampleVisibleNormal(localView, alpha, firstUnit, secondUnit);
+ let localLight = 2.0 * dot(localView, localHalf) * localHalf - localView;
+ sampledDirection = localToWorld(surfaceFrame, localLight);
+ return false;
+}
+
+fn mirrorWeight() -> vec3<f32> {
+ if (surfaceSampledCoat) { return vec3<f32>(surfaceCoatWeight / surfaceCoatChance); }
+ return schlickColor(surfaceSpecularNormal, surfaceViewCosine) * surfaceSpecularWeight / surfaceSpecularChance;
+}
+
+fn dielectricFresnelTerm(cosineIncident: f32, relativeIndex: f32) -> f32 {
+ let sineSquared = relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident);
+ if (sineSquared >= 1.0) { return 1.0; }
+ let cosineTransmitted = sqrt(1.0 - sineSquared);
+ let parallel = (relativeIndex * cosineIncident - cosineTransmitted) / (relativeIndex * cosineIncident + cosineTransmitted);
+ let perpendicular = (cosineIncident - relativeIndex * cosineTransmitted) / (cosineIncident + relativeIndex * cosineTransmitted);
+ return 0.5 * (parallel * parallel + perpendicular * perpendicular);
+}
+
+// The glass direction goes into sampledDirection; returns false when the path must end.
+fn sampleGlass(normal: vec3<f32>, view: vec3<f32>, entering: bool, ior: f32, alpha: f32, selectionUnit: f32, firstUnit: f32, secondUnit: f32) -> bool {
+ let frame = buildFrame(normal);
+ var halfVector = normal;
+ if (alpha > MIRROR_ALPHA) {
+ let localView = worldToLocal(frame, view);
+ halfVector = localToWorld(frame, sampleVisibleNormal(localView, alpha, firstUnit, secondUnit));
+ }
+ let relativeIndex = select(ior, 1.0 / ior, entering);
+ let cosineIncident = max(dot(view, halfVector), 1e-6);
+ let reflectChance = dielectricFresnelTerm(cosineIncident, relativeIndex);
+ if (selectionUnit < reflectChance) {
+ sampledDirection = 2.0 * dot(view, halfVector) * halfVector - view;
+ return dot(sampledDirection, normal) > 0.0;
+ }
+ let cosineTransmitted = sqrt(max(0.0, 1.0 - relativeIndex * relativeIndex * (1.0 - cosineIncident * cosineIncident)));
+ let bend = relativeIndex * cosineIncident - cosineTransmitted;
+ sampledDirection = bend * halfVector - relativeIndex * view;
+ return dot(sampledDirection, normal) < 0.0;
+}
+
+// ---- One path ----
+
+var<private> throughput: vec3<f32>;
+var<private> radiance: vec3<f32>;
+var<private> direction: vec3<f32>;
+var<private> lightDirection: vec3<f32>;
+var<private> lightRadiance: vec3<f32>;
+var<private> selectionProbability: f32 = 1.0;
+var<private> environmentSampledPdf: f32 = 0.0;
+var<private> sunFrame: mat3x3<f32>;
+var<private> featureAlbedo: vec3<f32>;
+var<private> featureNormal: vec3<f32>;
+var<private> featureDepth: f32;
+var<private> firstLegEscaped: f32 = 0.0;
+
+fn addRadiance(depth: i32, amountIn: vec3<f32>) {
+ var amount = amountIn;
+ if (depth > 0) {
+ let peak = max(amount.x, max(amount.y, amount.z));
+ if (peak > params.cameraAndClamp.z) { amount *= params.cameraAndClamp.z / peak; }
+ }
+ radiance += amount;
+}
+
+fn environmentWeight(candidatePdf: f32) -> f32 {
+ let lightPdf = environmentSampledPdf * selectionProbability;
+ let total = lightPdf * lightPdf + candidatePdf * candidatePdf;
+ return lightPdf * lightPdf / total / lightPdf;
+}
+
+fn directWeight(mode: i32, candidatePdf: f32) -> f32 {
+ if (mode == 1) { return environmentWeight(candidatePdf); }
+ return 1.0 / selectionProbability;
+}
+
+// Same shape as the GLSL: addDirect records one shadow ray and flushShadowRay traces it, so the shader holds one copy of the
+// shadow-ray traversal.
+var<private> shadowOrigin: vec3<f32>;
+var<private> shadowDirection: vec3<f32>;
+var<private> shadowLimit: f32;
+var<private> shadowAmount: vec3<f32>;
+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;
+ shadowDirection = lightDirection;
+ shadowLimit = distance;
+ shadowPending = true;
+}
+
+fn flushShadowRay() {
+ if (!shadowPending) { return; }
+ shadowPending = false;
+ if (!occluded(shadowOrigin, shadowDirection, shadowLimit)) { addRadiance(shadowDepth, shadowAmount); }
+}
+
+fn reaches(bit: i32) -> bool {
+ return ((hitMask >> u32(bit)) & 1u) == 1u;
+}
+
+// Aims lightDirection at the target and returns the distance; distanceSquared goes into aimedDistanceSquared.
+var<private> aimedDistanceSquared: f32;
+
+fn aimAt(aimPoint: vec3<f32>) -> f32 {
+ let delta = aimPoint - hitPoint;
+ aimedDistanceSquared = dot(delta, delta);
+ let distance = sqrt(aimedDistanceSquared);
+ lightDirection = delta / distance;
+ return distance;
+}
+
+fn randomOnSphere(radius: f32) -> vec3<f32> {
+ let height = 2.0 * nextRandom() - 1.0;
+ let angle = TWO_PI * nextRandom();
+ let ring = sqrt(1.0 - height * height);
+ return vec3<f32>(radius * ring * cos(angle), radius * height, radius * ring * sin(angle));
+}
+
+fn pointLightFalloff(distanceSquared: f32, range: f32, radius: f32) -> f32 {
+ var cutoff = 1.0;
+ if (range > 0.0) {
+ let ratio = distanceSquared / (range * range);
+ let fade = max(1.0 - ratio * ratio, 0.0);
+ cutoff = fade * fade;
+ }
+ return cutoff / max(distanceSquared, radius * radius);
+}
+
+// Draws one emitter's contribution into the pending shadow ray: emitter 0 is the sun when there is one, then the lights, then the sky.
+fn sampleEmitter(depth: i32, normal: vec3<f32>, emitter: i32) {
+ var distance = 0.0;
+ var weightMode = 0;
+ let hasSun = params.emittersFlagsSample.y != 0;
+ let lightCount = params.sizeBouncesLights.w;
+ if (hasSun && emitter == 0) {
+ if (!reaches(0)) { return; }
+ let cosineTheta = 1.0 - nextRandom() * (1.0 - params.sunColorAndCosine.w);
+ let sineTheta = sqrt(max(0.0, 1.0 - cosineTheta * cosineTheta));
+ let phi = TWO_PI * nextRandom();
+ lightDirection = sunFrame[0] * (sineTheta * cos(phi)) + sunFrame[1] * (sineTheta * sin(phi)) + sunFrame[2] * cosineTheta;
+ lightRadiance = params.sunColorAndCosine.rgb;
+ distance = params.environmentRotationAndRays.w;
+ } else {
+ let index = emitter - select(0, 1, hasSun);
+ if (index < lightCount) {
+ let base = index * LIGHT_TEXELS;
+ let positionType = lights[base];
+ let colorBit = lights[base + 1];
+ let directionRadius = lights[base + 2];
+ let acrossCone = lights[base + 3];
+ let alongBlend = lights[base + 4];
+ let intensityRange = lights[base + 5];
+ let lightType = i32(positionType.w);
+ if (!reaches(i32(colorBit.w))) { return; }
+ if (lightType == 2) {
+ let across = (nextRandom() - 0.5) * directionRadius.w;
+ let along = (nextRandom() - 0.5) * acrossCone.w;
+ let point = positionType.xyz + acrossCone.xyz * across + alongBlend.xyz * along;
+ distance = aimAt(point);
+ let emitCosine = -dot(directionRadius.xyz, lightDirection);
+ if (distance < 1e-6 || emitCosine <= 0.0) { return; }
+ lightRadiance = colorBit.rgb * (intensityRange.x * emitCosine / aimedDistanceSquared);
+ } else {
+ let jitter = randomOnSphere(directionRadius.w);
+ distance = aimAt(positionType.xyz + jitter);
+ if (distance < 1e-6) { return; }
+ var mask = 1.0;
+ if (lightType == 1) {
+ let inside = -dot(directionRadius.xyz, lightDirection) - acrossCone.w;
+ if (inside <= 0.0) { return; }
+ if (alongBlend.w > 0.0 && inside < alongBlend.w) {
+ let unit = inside / alongBlend.w;
+ mask = unit * unit * (3.0 - 2.0 * unit);
+ }
+ }
+ lightRadiance = colorBit.rgb * (intensityRange.x * pointLightFalloff(aimedDistanceSquared, intensityRange.y, directionRadius.w) * mask);
+ }
+ distance -= params.environmentRotationAndRays.z;
+ } else {
+ let rowUnit = nextRandom();
+ let columnUnit = nextRandom();
+ let columnJitter = nextRandom();
+ let rowJitter = nextRandom();
+ environmentSampledPdf = sampleEnvironment(rowUnit, columnUnit, columnJitter, rowJitter);
+ lightDirection = sampledDirection;
+ if (!(environmentSampledPdf > 0.0)) { return; }
+ lightRadiance = environmentRadiance(lightDirection);
+ distance = params.environmentRotationAndRays.w;
+ weightMode = 1;
+ }
+ }
+ addDirect(depth, normal, distance, weightMode);
+}
+
+// The first hit lights from every emitter; later hits draw one, and divide by the chance of drawing it.
+fn addLights(depth: i32, normal: vec3<f32>) {
+ let emitterCount = params.emittersFlagsSample.x;
+ if (depth == 0 || emitterCount <= 1) {
+ selectionProbability = 1.0;
+ for (var emitter = 0; emitter < emitterCount; emitter++) {
+ sampleEmitter(depth, normal, emitter);
+ flushShadowRay();
+ }
+ return;
+ }
+ selectionProbability = 1.0 / f32(emitterCount);
+ sampleEmitter(depth, normal, i32(floor(nextRandom() * f32(emitterCount))));
+ flushShadowRay();
+}
+
+fn addEscape(depth: i32, previousPdf: f32, afterMirror: bool) {
+ if (params.emittersFlagsSample.z == 0) { return; }
+ let sky = environmentRadiance(direction);
+ var weight = 1.0;
+ if (!afterMirror) {
+ let environmentSide = environmentPdf(direction) * selectionProbability;
+ weight = previousPdf * previousPdf / (previousPdf * previousPdf + environmentSide * environmentSide);
+ }
+ addRadiance(depth, throughput * sky * weight);
+}
+
+fn survivesRoulette(depth: i32) -> bool {
+ if (depth < RUSSIAN_ROULETTE_START) { return true; }
+ let survival = min(0.95, max(0.05, max(throughput.x, max(throughput.y, throughput.z))));
+ if (nextRandom() >= survival) { return false; }
+ throughput /= survival;
+ 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);
+ throughput = vec3<f32>(1.0);
+ featureAlbedo = vec3<f32>(1.0);
+ featureNormal = vec3<f32>(0.0, 0.0, 1.0);
+ featureDepth = 0.0;
+ var featuresRecorded = false;
+ direction = startDirection;
+ var position = origin;
+ var previousPdf = 0.0;
+ var afterMirror = true;
+ var normal = vec3<f32>(0.0, 1.0, 0.0);
+ let bounces = params.sizeBouncesLights.z;
+ let surfaceOffset = params.environmentRotationAndRays.z;
+ for (var depth = 0; depth <= bounces; depth++) {
+ let found = intersectScene(position, direction);
+ if (!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;
+ }
+ addRadiance(depth, throughput * hitEmission);
+ if (!isGlass) {
+ prepareSurface(normal, -direction);
+ addLights(depth, normal);
+ }
+ if (isGlass) {
+ let alpha = roughnessToAlpha(hitRoughness);
+ let selectionUnit = nextRandom();
+ let firstUnit = nextRandom();
+ let secondUnit = nextRandom();
+ if (!sampleGlass(normal, -direction, entering, hitIor, alpha, selectionUnit, firstUnit, secondUnit)) { break; }
+ direction = sampledDirection;
+ if (dot(direction, normal) < 0.0) { throughput *= hitColor; }
+ afterMirror = true;
+ } else {
+ let lobeUnit = nextRandom();
+ let firstUnit = nextRandom();
+ let secondUnit = nextRandom();
+ let isMirror = sampleSurface(lobeUnit, firstUnit, secondUnit);
+ direction = sampledDirection;
+ let cosine = dot(direction, normal);
+ if (cosine <= 0.0) { break; }
+ if (isMirror) {
+ throughput *= mirrorWeight();
+ afterMirror = true;
+ } else {
+ evaluateSurface(direction);
+ if (!(surfacePdf > 0.0)) { break; }
+ throughput *= surfaceValue * cosine / surfacePdf;
+ previousPdf = surfacePdf;
+ afterMirror = false;
+ }
+ }
+ position = hitPoint + direction * surfaceOffset;
+ if (!survivesRoulette(depth)) { break; }
+ }
+}
+
+@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 sampleIndex = u32(params.emittersFlagsSample.w);
+ let seed = params.seedAndAtlas.x;
+ if (params.emittersFlagsSample.y != 0) { sunFrame = buildFrame(params.sunDirection.xyz); }
+ let jitterX = hashJitter(pixel, sampleIndex, seed, 1u);
+ let jitterY = hashJitter(pixel, sampleIndex, seed, 2u);
+ let screenX = ((f32(id.x) + jitterX) / f32(width) * 2.0 - 1.0) * params.cameraAndClamp.x;
+ let screenY = (1.0 - (f32(id.y) + jitterY) / f32(height) * 2.0) * params.cameraAndClamp.y;
+ let rayDirection = normalize(params.forward.xyz + params.right.xyz * screenX + params.above.xyz * screenY);
+ tracePath(params.eye.xyz, rayDirection, pixel, sampleIndex);
+ if (!(all(radiance >= vec3<f32>(0.0)) && all(radiance < vec3<f32>(1e30)))) { radiance = vec3<f32>(0.0); }
+ if (!(featureDepth >= 0.0 && featureDepth < 1e30)) { featureDepth = 0.0; }
+ 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);
+}
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
new file mode 100644
index 00000000..81efb19b
--- /dev/null
+++ b/packages/render-native/src/lib.rs
@@ -0,0 +1,320 @@
+//! Hardware ray traced stills for 67js (issue #626). The packed scene tables of the browser path tracer go in, the WGSL
+//! kernel of the #625 spike runs on wgpu with ray queries (Vulkan), and the averaged linear colour comes back.
+//! The kernel keeps the random numbers, light sampling and shading of the browser kernel; only the BVH walk is hardware.
+
+use std::time::Instant;
+
+use napi::bindgen_prelude::{Float32Array, Uint32Array, Uint8Array};
+use napi::{Error, Result};
+use napi_derive::napi;
+use wgpu::util::DeviceExt;
+
+const KERNEL_SOURCE: &str = include_str!("kernel.wgsl");
+const WORKGROUP_SIZE: u32 = 8;
+const TRIANGLE_FLOATS: usize = 9 * 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.
+const SAMPLES_PER_WAIT: u32 = 4;
+
+#[napi(object)]
+pub struct NativeTraceInput {
+ /// The 9 texel triangle table of `packTriangles`, in BVH order, as float32 data.
+ pub triangles: Float32Array,
+ /// How many triangles the table holds; the table itself is padded to whole texture rows.
+ pub triangle_count: u32,
+ pub materials: Float32Array,
+ pub lights: Float32Array,
+ /// The texture atlas as 32 bit words.
+ 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.
+ pub parameters: Uint8Array,
+}
+
+#[napi(object)]
+pub struct NativeTraceOptions {
+ pub width: u32,
+ pub height: u32,
+ pub samples: u32,
+}
+
+#[napi(object)]
+pub struct NativeTraceResult {
+ /// Linear RGBA, averaged over the samples, row by row from the top.
+ pub rgba: Float32Array,
+ pub adapter: String,
+ pub backend: String,
+ pub setup_seconds: f64,
+ pub compile_seconds: f64,
+ pub upload_seconds: f64,
+ pub acceleration_build_seconds: f64,
+ pub traced_seconds: f64,
+}
+
+fn failure(message: impl Into<String>) -> Error {
+ Error::from_reason(message.into())
+}
+
+fn storage_buffer(device: &wgpu::Device, label: &str, bytes: &[u8]) -> wgpu::Buffer {
+ let mut padded = bytes.to_vec();
+ padded.resize(padded.len().next_multiple_of(4).max(16), 0);
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some(label),
+ contents: &padded,
+ usage: wgpu::BufferUsages::STORAGE,
+ })
+}
+
+fn layout_entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty,
+ count: None,
+ }
+}
+
+fn storage_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
+ layout_entry(
+ binding,
+ wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Storage { read_only },
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ )
+}
+
+/// Traces the packed scene on the GPU with hardware ray queries.
+#[napi]
+pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Result<NativeTraceResult> {
+ let setup_started = Instant::now();
+ let triangle_count = input.triangle_count as usize;
+ if triangle_count == 0 || input.triangles.len() < triangle_count * TRIANGLE_FLOATS {
+ 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."));
+ }
+ let pixel_count = options.width as u64 * options.height as u64;
+
+ let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
+ backends: wgpu::Backends::VULKAN,
+ ..wgpu::InstanceDescriptor::new_without_display_handle()
+ });
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::HighPerformance,
+ ..Default::default()
+ }))
+ .map_err(|error| failure(format!("No Vulkan adapter: {error}")))?;
+ if !adapter.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) {
+ return Err(failure("The Vulkan adapter does not support ray queries."));
+ }
+ let adapter_info = adapter.get_info();
+ let adapter_limits = adapter.limits();
+ let required_limits = wgpu::Limits {
+ max_storage_buffer_binding_size: adapter_limits.max_storage_buffer_binding_size.min(1 << 30),
+ max_buffer_size: adapter_limits.max_buffer_size.min(1 << 30),
+ ..wgpu::Limits::default()
+ }
+ .using_minimum_supported_acceleration_structure_values();
+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ label: Some("render-native"),
+ required_features: wgpu::Features::EXPERIMENTAL_RAY_QUERY,
+ required_limits,
+ experimental_features: unsafe { wgpu::ExperimentalFeatures::enabled() },
+ ..Default::default()
+ }))
+ .map_err(|error| failure(format!("Could not open the device: {error}")))?;
+ let setup_seconds = setup_started.elapsed().as_secs_f64();
+
+ let compile_started = Instant::now();
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("path tracer"),
+ source: wgpu::ShaderSource::Wgsl(KERNEL_SOURCE.into()),
+ });
+ let mut layout_entries = vec![
+ layout_entry(
+ 0,
+ wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ ),
+ layout_entry(1, wgpu::BindingType::AccelerationStructure { vertex_return: false }),
+ ];
+ layout_entries.extend((2..=7).map(|binding| storage_entry(binding, true)));
+ layout_entries.push(storage_entry(8, false));
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("path tracer"),
+ entries: &layout_entries,
+ });
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("path tracer"),
+ bind_group_layouts: &[Some(&bind_group_layout)],
+ immediate_size: 0,
+ });
+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some("path tracer"),
+ layout: Some(&pipeline_layout),
+ module: &module,
+ entry_point: Some("main"),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ let compile_seconds = compile_started.elapsed().as_secs_f64();
+
+ let upload_started = Instant::now();
+ // The corners of every triangle: the table stores a corner and two edges in its first three texels.
+ let mut vertices: Vec<f32> = Vec::with_capacity(triangle_count * 9);
+ for triangle in triangle_data.chunks_exact(TRIANGLE_FLOATS) {
+ let corner = [triangle[0], triangle[1], triangle[2]];
+ let edge_first = [triangle[4], triangle[5], triangle[6]];
+ let edge_second = [triangle[8], triangle[9], triangle[10]];
+ vertices.extend_from_slice(&corner);
+ vertices.extend((0..3).map(|axis| corner[axis] + edge_first[axis]));
+ vertices.extend((0..3).map(|axis| corner[axis] + edge_second[axis]));
+ }
+ let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("triangle corners"),
+ contents: bytemuck::cast_slice(&vertices),
+ usage: wgpu::BufferUsages::BLAS_INPUT,
+ });
+ let buffers = [
+ storage_buffer(&device, "triangles", bytemuck::cast_slice(triangle_data)),
+ storage_buffer(&device, "materials", bytemuck::cast_slice(&input.materials)),
+ storage_buffer(&device, "lights", bytemuck::cast_slice(&input.lights)),
+ storage_buffer(&device, "atlas", bytemuck::cast_slice(&input.atlas)),
+ storage_buffer(&device, "environment colors", bytemuck::cast_slice(&input.environment_colors)),
+ storage_buffer(&device, "environment tables", bytemuck::cast_slice(&input.environment_tables)),
+ ];
+ let accumulation = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("accumulation"),
+ size: pixel_count * 4 * 16,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
+ mapped_at_creation: false,
+ });
+ let parameters = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("parameters"),
+ contents: &input.parameters[..],
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+ let upload_seconds = upload_started.elapsed().as_secs_f64();
+
+ let build_started = Instant::now();
+ let geometry_size = wgpu::BlasTriangleGeometrySizeDescriptor {
+ vertex_format: wgpu::VertexFormat::Float32x3,
+ vertex_count: (triangle_count * 3) as u32,
+ index_format: None,
+ index_count: None,
+ flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE,
+ };
+ let blas = device.create_blas(
+ &wgpu::CreateBlasDescriptor {
+ label: Some("scene"),
+ flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: wgpu::AccelerationStructureUpdateMode::Build,
+ },
+ wgpu::BlasGeometrySizeDescriptors::Triangles {
+ descriptors: vec![geometry_size.clone()],
+ },
+ );
+ let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor {
+ label: Some("scene"),
+ flags: wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE,
+ update_mode: wgpu::AccelerationStructureUpdateMode::Build,
+ max_instances: 1,
+ });
+ tlas[0] = Some(wgpu::TlasInstance::new(
+ &blas,
+ [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0],
+ 0,
+ 0xFF,
+ ));
+ let mut build_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("build") });
+ build_encoder.build_acceleration_structures(
+ std::iter::once(&wgpu::BlasBuildEntry {
+ blas: &blas,
+ geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry {
+ size: &geometry_size,
+ vertex_buffer: &vertex_buffer,
+ first_vertex: 0,
+ vertex_stride: 12,
+ index_buffer: None,
+ first_index: None,
+ transform_buffer: None,
+ transform_buffer_offset: None,
+ }]),
+ }),
+ std::iter::once(&tlas),
+ );
+ queue.submit(Some(build_encoder.finish()));
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ let acceleration_build_seconds = build_started.elapsed().as_secs_f64();
+
+ let mut entries = vec![
+ wgpu::BindGroupEntry { binding: 0, resource: parameters.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: tlas.as_binding() },
+ ];
+ for (offset, buffer) in buffers.iter().enumerate() {
+ entries.push(wgpu::BindGroupEntry { binding: 2 + offset as u32, resource: buffer.as_entire_binding() });
+ }
+ entries.push(wgpu::BindGroupEntry { binding: 8, resource: accumulation.as_entire_binding() });
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("path tracer"),
+ layout: &bind_group_layout,
+ entries: &entries,
+ });
+
+ let trace_started = Instant::now();
+ for sample_index in 0..options.samples {
+ queue.write_buffer(&parameters, SAMPLE_INDEX_BYTE_OFFSET, &sample_index.to_le_bytes());
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("sample") });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes: None });
+ pass.set_pipeline(&pipeline);
+ pass.set_bind_group(0, &bind_group, &[]);
+ pass.dispatch_workgroups(options.width.div_ceil(WORKGROUP_SIZE), options.height.div_ceil(WORKGROUP_SIZE), 1);
+ }
+ queue.submit(Some(encoder.finish()));
+ if (sample_index + 1) % SAMPLES_PER_WAIT == 0 {
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ }
+ }
+ let readback_size = pixel_count * 16;
+ let readback = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("readback"),
+ size: readback_size,
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ let mut copy_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("readback") });
+ copy_encoder.copy_buffer_to_buffer(&accumulation, 0, &readback, 0, readback_size);
+ queue.submit(Some(copy_encoder.finish()));
+ readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ let mapped = readback.slice(..).get_mapped_range().map_err(|error| failure(format!("Could not read the image back: {error}")))?;
+ let sums: &[f32] = bytemuck::cast_slice(&mapped);
+ let sample_scale = 1.0 / options.samples.max(1) as f32;
+ let mut rgba = Vec::with_capacity(pixel_count as usize * 4);
+ for pixel in sums.chunks_exact(4) {
+ rgba.extend_from_slice(&[pixel[0] * sample_scale, pixel[1] * sample_scale, pixel[2] * sample_scale, 1.0]);
+ }
+ drop(mapped);
+ let traced_seconds = trace_started.elapsed().as_secs_f64();
+
+ Ok(NativeTraceResult {
+ rgba: Float32Array::new(rgba),
+ adapter: adapter_info.name,
+ backend: format!("{:?}", adapter_info.backend),
+ setup_seconds,
+ compile_seconds,
+ upload_seconds,
+ acceleration_build_seconds,
+ traced_seconds,
+ })
+}