3D engine that AI agents drive
Merge origin/main into 895-cook-sampler-light-tree (#895)
Nguyen Xuan An1885acd9df66
diff --cc bench/cycles-parity/make-many-lights-scene.mjsindex 00000000,c0cda724..ca50fe66mode 000000,100644..100644--- a/bench/cycles-parity/make-many-lights-scene.mjs+++ b/bench/cycles-parity/make-many-lights-scene.mjs@@@ -1,0 -1,41 +1,40 @@@+ // Writes a copy of an exported scene with many small point lights spread through the room, for light tree measurements.-// The lights go in `environment.manyPointLights`, which trace-native.mjs adds after the scene is built: a trace scene itself-// takes at most 32 lights because each light owns a light-link bit.++// trace-scene-many-lights.mjs (used by trace-native.mjs) builds a scene with more than 32 lights in chunks, because a trace++// scene itself takes at most 32 lights: each light owns a light-link bit.+ // node bench/cycles-parity/make-many-lights-scene.mjs <sceneJsonPath> <outputJsonPath> [--count 500] [--seed 7]+ import { readFile, writeFile } from 'node:fs/promises';+ import { resolve } from 'node:path';++ function readFlagValue(argumentList, flagName, fallbackValue) {+ const flagIndex = argumentList.indexOf(flagName);+ return flagIndex === -1 ? fallbackValue : argumentList[flagIndex + 1];+ }++ function createRandom(seed) {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;+ };+ }++ const argumentList = process.argv.slice(2);+ if (argumentList.length < 2) {+ throw new RangeError('Usage: node bench/cycles-parity/make-many-lights-scene.mjs <sceneJsonPath> <outputJsonPath> [--count 500] [--seed 7]');+ }+ const lightCount = Number(readFlagValue(argumentList, '--count', 500));+ const nextRandom = createRandom(Number(readFlagValue(argumentList, '--seed', 7)));+ const description = JSON.parse(await readFile(resolve(argumentList[0]), 'utf8'));+ const totalIntensity = 12;+ description.id = `${description.id}-${lightCount}-lights`;-description.environment.pointLights = [];-description.environment.manyPointLights = Array.from({ length: lightCount }, () => ({++description.environment.pointLights = Array.from({ length: lightCount }, () => ({+ position: [(nextRandom() - 0.5) * 7.4, 0.3 + nextRandom() * 2.7, (nextRandom() - 0.5) * 7.4],+ color: [0.6 + 0.4 * nextRandom(), 0.6 + 0.4 * nextRandom(), 0.6 + 0.4 * nextRandom()],+ intensity: (totalIntensity / lightCount) * (0.25 + 1.5 * nextRandom()),+ radius: 0.03,+ castShadow: true,+ }));+ await writeFile(resolve(argumentList[1]), JSON.stringify(description));+ console.log(JSON.stringify({ outputPath: resolve(argumentList[1]), lightCount }));diff --cc bench/cycles-parity/measure-sampler-noise.pyindex 00000000,da4da764..b88d2e96mode 000000,100644..100644--- a/bench/cycles-parity/measure-sampler-noise.py+++ b/bench/cycles-parity/measure-sampler-noise.py@@@ -1,0 -1,112 +1,112 @@@+ """Measure relMSE of Cook's sampler or light selection at equal sample counts against a high-sample reference.++ uv run --no-project --with numpy python bench/cycles-parity/measure-sampler-noise.py <sceneJson> <outputDirectory> \+ [--compare sampler|light-tree] [--samples 16,64,256] [--seeds 1,2] [--reference-samples 2048] [--width 480] [--height 270]++ --compare sampler (default) pits the PCG hash against Sobol-Burley. --compare light-tree pits the cumulative-weight light pick+ against the light tree, both on Sobol-Burley, and also reports sampling seconds and the time each needs to reach the error+ the other reaches (interpolated on a log-log line through the sample ladder).+ Renders go through the script named by GPU_LOCK_COMMAND when it is set. The reference uses the first variant with its own seed, so no candidate shares random+ numbers with it. Prints one JSON object.+ """+ import json+ import math+ import os+ import subprocess+ import sys++ import numpy++ sys.stdout.reconfigure(encoding="utf-8", errors="replace")++ REPOSITORY_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))+ # A shared machine can queue GPU jobs: set GPU_LOCK_COMMAND to a wrapper script and every render runs through it.+ GPU_LOCK_COMMAND = os.environ.get("GPU_LOCK_COMMAND")+ REL_MSE_EPSILON = 1e-2+ REFERENCE_SEED = 9001+ VARIANT_FLAGS = {- "sampler": {"pcg": ["--sampler", "pcg"], "sobol": ["--sampler", "sobol"]},++ "sampler": {"pcg": ["--sampler", "white"], "sobol": ["--sampler", "sobol-burley"]},+ "light-tree": {- "off": ["--sampler", "sobol", "--light-tree", "off"],- "on": ["--sampler", "sobol", "--light-tree", "on"],++ "off": ["--sampler", "sobol-burley", "--light-sampling", "uniform"],++ "on": ["--sampler", "sobol-burley", "--light-sampling", "tree"],+ },+ }+++ def read_flag(argument_list, flag_name, fallback):+ if flag_name not in argument_list:+ return fallback+ return argument_list[argument_list.index(flag_name) + 1]+++ def render(scene_json, output_prefix, variant_flags, samples, seed, width, height, weight):+ environment = dict(os.environ, GPU_LOCK_WEIGHT=weight)+ command = [+ *(["bash", GPU_LOCK_COMMAND] if GPU_LOCK_COMMAND else []), "node", os.path.join(REPOSITORY_ROOT, "bench", "cycles-parity", "trace-native.mjs"),+ scene_json, output_prefix, "--kernel", "cycles", "--samples", str(samples),+ "--seed", str(seed), "--width", str(width), "--height", str(height), *variant_flags,+ ]+ subprocess.run(command, check=True, env=environment, stdout=subprocess.DEVNULL)+ with open(output_prefix + ".json", encoding="utf-8") as handle:+ report = json.load(handle)+ return numpy.load(output_prefix + ".npy"), report+++ def relative_mse(reference_rgb, candidate_rgb):+ denominator = reference_rgb ** 2 + REL_MSE_EPSILON+ return float((((candidate_rgb - reference_rgb) ** 2) / denominator).mean())+++ def seconds_to_reach(error_target, points):+ """points: (samplingSeconds, relMse) per sample count, error falling as time rises. Log-log interpolation or extrapolation."""+ log_seconds = numpy.log([seconds for seconds, _ in points])+ log_errors = numpy.log([error for _, error in points])+ slope, intercept = numpy.polyfit(log_errors, log_seconds, 1)+ return float(math.exp(slope * math.log(error_target) + intercept))+++ def main():+ argument_list = sys.argv[1:]+ scene_json, output_directory = os.path.abspath(argument_list[0]), os.path.abspath(argument_list[1])+ comparison = read_flag(argument_list, "--compare", "sampler")+ sample_counts = [int(value) for value in read_flag(argument_list, "--samples", "16,64,256").split(",")]+ seeds = [int(value) for value in read_flag(argument_list, "--seeds", "1,2").split(",")]+ reference_samples = int(read_flag(argument_list, "--reference-samples", "2048"))+ width = int(read_flag(argument_list, "--width", "480"))+ height = int(read_flag(argument_list, "--height", "270"))+ variants = VARIANT_FLAGS[comparison]+ baseline_name, candidate_name = list(variants)+ os.makedirs(output_directory, exist_ok=True)+ reference_rgb, _ = render(+ scene_json, os.path.join(output_directory, "reference"), variants[baseline_name], reference_samples, REFERENCE_SEED, width, height, "heavy",+ )+ results = {}+ ladders = {baseline_name: [], candidate_name: []}+ for samples in sample_counts:+ for name, flags in variants.items():+ errors, seconds = [], []+ for seed in seeds:+ prefix = os.path.join(output_directory, f"{name}-{samples}-{seed}")+ candidate_rgb, report = render(scene_json, prefix, flags, samples, seed, width, height, "light")+ errors.append(relative_mse(reference_rgb, candidate_rgb))+ seconds.append(report["samplingSeconds"])+ mean_error, mean_seconds = float(numpy.mean(errors)), float(numpy.mean(seconds))+ results[f"{name}@{samples}"] = {"relMse": mean_error, "samplingSeconds": mean_seconds, "perSeed": errors}+ ladders[name].append((mean_seconds, mean_error))+ baseline = results[f"{baseline_name}@{samples}"]["relMse"]+ candidate = results[f"{candidate_name}@{samples}"]["relMse"]+ results[f"{candidate_name}@{samples}"]["dropVersus" + baseline_name.capitalize()] = 1.0 - candidate / baseline+ if comparison == "light-tree":+ mean_ratio = float(numpy.mean([+ numpy.load(os.path.join(output_directory, f"{candidate_name}-{sample_counts[-1]}-{seeds[0]}.npy")).mean()+ / numpy.load(os.path.join(output_directory, f"{baseline_name}-{sample_counts[-1]}-{seeds[0]}.npy")).mean()+ ]))+ target_error = ladders[baseline_name][-1][1]+ results["meanImageRatioTreeOverUniform"] = mean_ratio+ results["targetRelMse"] = target_error+ results["secondsToTargetWithout"] = ladders[baseline_name][-1][0]+ results["secondsToTargetWith"] = seconds_to_reach(target_error, ladders[candidate_name])+ print(json.dumps(results, indent=2))+++ main()diff --cc bench/cycles-parity/trace-native.mjsindex 8d3bda64,f62cdcac..c9963971--- a/bench/cycles-parity/trace-native.mjs+++ b/bench/cycles-parity/trace-native.mjs@@@ -11,8 -11,7 +11,11 @@@ import { writeFloat32Npy } from './npy.import { reconstructTraceSceneSource } from './scene-bridge.mjs';const SUPPORTED_KERNELS = new Set(['legacy', 'cycles']);-const SUPPORTED_FILTERS = new Set(['box', 'blackman-harris']);+const SUPPORTED_FILTERS = new Set(['box', 'gaussian', 'blackman-harris']);+const SUPPORTED_SAMPLERS = new Set(['white', 'sobol-burley']);++// Names of the earlier sampler option (#957), kept as aliases.++const SAMPLER_ALIASES = { pcg: 'white', sobol: 'sobol-burley' };++const LIGHT_TREE_ALIASES = { auto: 'auto', on: 'tree', off: 'uniform' };function readFlagValue(argumentList, flagName, fallbackValue) {const flagIndex = argumentList.indexOf(flagName);@@@ -58,25 -65,9 +69,34 @@@ function parseFilterTypeOption(argumentreturn filterType;}+function parseSamplerOption(argumentList) {- const sampler = String(readFlagValue(argumentList, '--sampler', 'sobol-burley'));++ const requested = String(readFlagValue(argumentList, '--sampler', 'sobol-burley'));++ const sampler = SAMPLER_ALIASES[requested] ?? requested;+ if (!SUPPORTED_SAMPLERS.has(sampler)) {- throw new RangeError(`Option --sampler must be "white" or "sobol-burley", got "${sampler}".`);++ throw new RangeError(`Option --sampler must be "white" (alias "pcg") or "sobol-burley" (alias "sobol"), got "${requested}".`);+ }+ return sampler;+}++function parseLightSamplingOption(argumentList) {+ const lightSampling = String(readFlagValue(argumentList, '--light-sampling', 'auto'));+ if (!['auto', 'tree', 'uniform'].includes(lightSampling)) {+ throw new RangeError(`Option --light-sampling must be "auto", "tree" or "uniform", got "${lightSampling}".`);+ }- return lightSampling;++ const aliasedLightTree = String(readFlagValue(argumentList, '--light-tree', 'auto'));++ if (!Object.hasOwn(LIGHT_TREE_ALIASES, aliasedLightTree)) {++ throw new RangeError(`Option --light-tree (alias of --light-sampling) must be "auto", "on" or "off", got "${aliasedLightTree}".`);++ }++ const aliasedLightSampling = LIGHT_TREE_ALIASES[aliasedLightTree];++ if (aliasedLightSampling !== 'auto' && lightSampling !== 'auto' && aliasedLightSampling !== lightSampling) {++ throw new RangeError(`Options --light-tree ${aliasedLightTree} and --light-sampling ${lightSampling} disagree; pass only one.`);++ }++ return aliasedLightSampling === 'auto' ? lightSampling : aliasedLightSampling;+}+function parseTraceArguments(argumentList) {if (argumentList.length < 2 || argumentList[0].startsWith('--') || argumentList[1].startsWith('--')) {- throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler sobol|pcg] [--light-tree auto|on|off] [--filter-type box|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0]');+ throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler white|sobol-burley] [--light-sampling auto|tree|uniform] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0]');}return {sceneJsonPath: resolve(argumentList[0]),diff --cc changes/895-light-tree.mdindex e5f34b3b,00000000..780f536dmode 100644,000000..100644--- a/changes/895-light-tree.md+++ b/changes/895-light-tree.md@@@ -1,2 -1,0 +1,2 @@@- - The Cook `cycles` kernel picks next event lights through the Cycles light tree (`lightSampling`: `auto`, `tree` or `uniform`; `--light-sampling` in `trace-native.mjs`), built by the host over analytic lights and emissive triangles (#895)++- The Cook `cycles` kernel picks next event lights through the Cycles light tree (`lightSampling`: `auto`, `tree` or `uniform`; `--light-sampling` in `trace-native.mjs`), built by the host over analytic lights, a sun and emissive triangles; `useLightTree: true|false` is another name for `lightSampling: 'tree'|'uniform'` (#895)+- A packed FORMAT-v2 input without light tree emitter tables is rejected when it asks for the tree (`traceNative` throws for `lightSampling: 'tree'` and uses the flat pick for `auto`), `filterType` and `filterWidth` now apply to an already packed input, and `buildLightTree` throws above 32 distant lights (#895)diff --cc changes/895-sampler.mdindex 7ca67048,00000000..1b9c880dmode 100644,000000..100644--- a/changes/895-sampler.md+++ b/changes/895-sampler.md@@@ -1,1 -1,0 +1,1 @@@- - The Cook `cycles` kernel samples with Cycles' Sobol-Burley blue-noise pattern by default; `sampler: "white"` (`--sampler white` in `trace-native.mjs`) keeps the old hash sampler (#895)++- The Cook `cycles` kernel samples with Cycles' Sobol-Burley blue-noise pattern by default; `sampler: "white"` (`--sampler white` in `trace-native.mjs`) keeps the old hash sampler, and `sampler: 'pcg'` is another name for it (#895)diff --cc docs/cycles-parity.mdindex afa7f0b7,9b1029b4..b4763d6d--- a/docs/cycles-parity.md+++ b/docs/cycles-parity.md@@@ -342,137 -342,6 +342,137 @@@ These are per-sample times on one scene---+### Pixel filter: box versus Blackman-Harris++The six-scene references use the box filter of width 1, so the box filter stays the default of the `cycles` kernel. Cycles' own default is Blackman-Harris with width 1.5. To show which choice matches Cycles, `render-cycles.py --filter-type blackman-harris --filter-width 1.5` rendered a second Cycles 5.3 reference (4096 spp, seed 1, OptiX) and the `cycles` kernel ran at 1024 spp, seed 1, 8 bounces, 960 x 540 with each filter `[measured]`:++| Scene | Native filter | vs Cycles box 1 (relMSE / FLIP LDR) | vs Cycles Blackman-Harris 1.5 (relMSE / FLIP LDR) |+| :--- | :--- | :--- | :--- |+| `lit-interior` | box 1 | 0.00105 / 0.0272 | 0.00106 / 0.0273 |+| `lit-interior` | Blackman-Harris 1.5 | 0.00106 / 0.0273 | 0.00105 / 0.0272 |+| `glass` | box 1 | 0.00009 / 0.0073 | 0.00016 / 0.0084 |+| `glass` | Blackman-Harris 1.5 | 0.00061 / 0.0082 | 0.00010 / 0.0073 |++`lit-interior` is smooth, so the filter hides under its noise. `glass` has hard caustic edges: each native filter scores best against the Cycles reference rendered with the same filter, and the mismatched pair is 4 to 7 times worse in relMSE.++### Light tree for next event estimation+- The `cycles` kernel picks one emitter per surface bounce by walking the Cycles light tree (`light_tree.wgsl`, a translation of `kernel/light/tree.h`: one random number reused down the tree, importance from distance, cone angles, energy and the surface normal, two reservoirs per leaf) and finds the probability of a given emitter from the previous shading point for the MIS weight of a BSDF-sampled hit. `lightSampling` is `auto` (default: tree when the scene has more than one emitter, as Cycles with `use_light_tree` on), `tree` or `uniform` (the flat pick of earlier versions); `trace-native.mjs --light-sampling` sets it. The environment map keeps its own importance sample and is not in the tree. `[measured]`, 960 x 540, 8 bounces, seed 1, against the Cycles 4096-spp seed-1 reference:++The `cycles` kernel picks one emitter per surface bounce by walking the Cycles light tree (`light_tree.wgsl`, a translation of `kernel/light/tree.h`: one random number reused down the tree, importance from distance, cone angles, energy and the surface normal, two reservoirs per leaf) and finds the probability of a given emitter from the previous shading point for the MIS weight of a BSDF-sampled hit. `lightSampling` is `auto` (default: tree when the scene has more than one emitter, as Cycles with `use_light_tree` on), `tree` or `uniform` (the flat pick of earlier versions); `trace-native.mjs --light-sampling` sets it. `useLightTree: true|false` (`--light-tree on|off`) are other names for `tree` and `uniform`; passing both options with different values is an error. A sun is a distant leaf of the same tree, and light-link masks stay as an OR per node: every emitter is in the tree, and a picked emitter whose mask does not match the receiver contributes nothing (`lgt_links_match`), so linked scenes use the tree too. The environment map keeps its own importance sample and is not in the tree. `[measured]`, 960 x 540, 8 bounces, seed 1, against the Cycles 4096-spp seed-1 reference:++| Check | Result |+| :--- | :--- |+| Six scenes, 1024 spp, tree on: largest per-channel mean-ratio gap | glass 0.28 %, light-linking 0.09 %, lit-interior 0.34 % (0.34 % with the flat pick too), metal 0.05 %, outdoor-hdri 0.06 %, spot-area 0.00 % |+| `lit-interior` relMSE at 1024 spp, tree against flat | 0.00065 against 0.00105 |+| Pick probabilities, 1600 random shading points per scene (`--light-tree-probe`, the kernel's own `ltr_pdf` and `ltr_sample`) | sum never above 1.0000002; all 800 points that see through the surface sum to 1; of the opaque ones, 664 of 800 (`lit-interior`) and 649 of 800 (12 emissive triangles) sum to 1, the rest are 0 (no emitter above the surface) or lose a share to a node whose emitters are all invisible, as in Cycles; fraction of 64 stratified picks that found an emitter equals the sum to 0.8 %; returned pick probability equals `ltr_pdf` of the picked emitter to 1.3e-6 |+| One large emissive slab over a floor and a glossy ball, 512 spp | mean against both: NEE only 1.0014 / 1.0017 / 1.0018, BSDF only 1.0000 / 0.9999 / 0.9999 |+| 256 spp sampling time, median of 3 interleaved runs (the GPU was shared with another job, so all times are 1.6 times the idle figure) | `lit-interior`: tree 5.94 s [5.91 to 8.52], flat 4.58 s [4.58 to 4.60]; `metal` (one emitter, `auto` picks flat): tree 2.53 s [2.51 to 2.53], flat 2.32 s [2.27 to 2.33] |+| 256 spp relMSE | `lit-interior`: tree 0.00274, flat 0.00433 (Cycles 0.0031); `metal`: 0.00506 both |++On `lit-interior` the tree costs 30 % more per sample and removes 37 % of the noise, so it wins by about 17 % at equal time (inferred from relMSE falling as 1/samples). The probe is a GPU test entry, not a Rust port; `tests/native-light-tree-kernel.test.js` repeats the three checks on a small scene.++### Seventh scene: `many-lights-500` (light tree gate, #895)++A 60 m hall cut into ten cells by partition walls with one doorway each, lit by 500 small lights placed from a fixed seed: 200 point lights, 150 spot lights, 100 emissive quads on the side walls and 50 emissive triangles on the ceiling (350 analytic lights and 200 emissive triangles). A surface sees the lights of its own cell and, through the doorways, a few of the next ones, so most of the 500 are far or hidden from any shading point and a flat pick wastes almost every sample. It is defined in [`bench/reference/scenes.js`](../bench/reference/scenes.js) as `many-lights-500` (the id `many-lights` is the 24-lamp corridor of issue #623), exported by the same `export-scene.mjs` path as the other six, and built by `render-cycles.py` from the same JSON, so both renderers read one scene. Export, a Cycles reference and a Cook run are the same commands as for the six, with `--scene many-lights-500`; `run-m1-parity.py` lists it as the seventh scene.++`buildTraceScene` takes at most 32 analytic lights (`MAX_TRACE_LIGHTS`, one light-link mask bit each). The parity harness has no light links, so [`trace-scene-many-lights.mjs`](../bench/cycles-parity/trace-scene-many-lights.mjs) builds the lights in chunks of 32 and joins the lists, giving every light the "all groups" bit; the core limit and the legacy kernel are unchanged. `tests/cycles-parity-many-lights.test.js` checks the counts, the fixed seed and the join.++Cycles 5.3 reference: Blender 5.3.0 OptiX, 960x540, 4096 spp, seeds 1 and 2, 8 bounces, light tree on (the Cycles default, `use_light_tree = true` in the render report), box filter 1, no denoiser, no clamps. The seed 1 versus seed 2 noise floor is relMSE 0.000791, per-channel mean ratio 1.0000 / 1.0000 / 1.0000, tiles 0.9995 to 1.0009, FLIP LDR 0.0173 `[measured]`. Sampling took 732 s (seed 1) and 1391 s (seed 2) with other jobs on the card, so they are not a speed figure.++**Gate 1, the tree against the flat pick** (Cook `cycles` kernel, seed 1, 8 bounces, sampling seconds from the report, three interleaved rounds, relMSE against the seed 1 reference; the three runs of a rung give the same image, so relMSE has no range) `[measured]`:++| spp | uniform relMSE | tree relMSE | uniform / tree error | uniform sampling s | tree sampling s | tree / uniform time |+| ---: | ---: | ---: | ---: | --- | --- | ---: |+| 16 | 0.37364 | 0.12644 | 2.95 | 1.344 [1.331-1.348] | 1.558 [1.555-1.559] | 1.16 |+| 64 | 0.08809 | 0.03041 | 2.90 | 5.114 [5.095-5.160] | 5.991 [5.968-6.074] | 1.17 |+| 256 | 0.02032 | 0.00766 | 2.65 | 20.474 [20.447-21.442] | 24.159 [24.015-24.450] | 1.18 |+| 1024 | 0.00442 | 0.00218 | 2.03 | 81.958 [81.881-82.966] | 96.484 [95.916-96.609] | 1.18 |++Time to equal error, from the two ladders on a log-log interpolation of time against relMSE (both curves cover 0.00442 to 0.126, so no extrapolation): at relMSE 0.0237 (geometric middle of that range) the flat pick needs 17.7 s and the tree 7.7 s, 2.30 times faster; at 0.00664 (1.5 times the lowest error both reach) 56.7 s and 28.3 s, 2.00 times faster; at 0.0304 (the tree at 64 spp) 14.0 s and 6.0 s, 2.33 times faster `[measured and interpolated]`. **The gate is met**: the tree reaches equal error in less than half the time. The tree costs 16 to 18 % more per sample here and removes 51 to 66 % of the noise per sample. At 1024 spp both curves approach the floor set by the 4096 spp reference's own noise (about half of the 0.000791 seed-to-seed figure), which is why the ratio falls toward 2.++**Gate 2, parity with Cycles** (Cook `cycles` kernel, tree, 4096 spp, seed 1, against the Cycles seed 1 reference, `run-m1-parity.py`) `[measured]`: per-channel mean ratio 1.0009 / 1.0010 / 1.0009 (limit 2 %); 64 of 64 tiles within 5 %, tile ratios 0.9999 to 1.0034; FLIP LDR 0.0178 against a ceiling of 0.0373; relMSE 0.000832 against the 0.000791 noise floor. All gates pass, and nothing in the kernel or the scene export was changed to get there: light types, spot cone and units already matched (spot `angle`, `penumbra` and the 4 pi and pi watt factors are the ones the other scenes use; emissive quads and triangles go through Principled emission strength on both sides, as the kernel emits). Cook took 386.6 s of sampling for 4096 spp with other jobs on the card. These RTX 3060 figures come from before the light tree importance fix described under "Repeat on Modal" below; the Modal run reproduces the same gate values.++### Equal-error time against Cycles++The question is how long each renderer needs for the same error, not how long it takes for the same sample count. Cycles 5.3.0 (OptiX, RTX 3060) and the Cook `cycles` kernel (defaults: Sobol-Burley blue-noise sampler, light tree `auto`, box filter 1) render `lit-interior`, `metal` and `many-lights-500` at 16, 64, 256 and 1024 spp, 960x540, 8 bounces, seed 3 for both, so neither shares a random stream with the seed 1 reference. One rung is a Cook run followed by a Cycles run, one job at a time, three rounds, each through the GPU lock. Time is the sampling time each tool reports (`samplingSeconds`: Cook's sampling loop; for Cycles the span from its first sample statistics event to the end of the render call), without scene setup and without a denoiser. Error is relMSE against the Cycles 4096 spp seed 1 reference. The images do not change between rounds, so relMSE has no range; times are medians with the range of three runs `[measured]`.++| scene | spp | Cook relMSE | Cycles relMSE | Cook s | Cycles s |+| --- | ---: | ---: | ---: | --- | --- |+| `lit-interior` | 16 | 0.06530 | 0.07024 | 0.415 [0.405-0.446] | 1.454 [0.467-5.732] |+| `lit-interior` | 64 | 0.01283 | 0.01483 | 1.547 [1.452-4.544] | 1.794 [1.670-5.488] |+| `lit-interior` | 256 | 0.00274 | 0.00310 | 5.922 [5.774-6.144] | 6.375 [5.669-8.254] |+| `lit-interior` | 1024 | 0.000656 | 0.000771 | 24.75 [24.00-24.78] | 26.11 [25.93-28.35] |+| `many-lights-500` | 16 | 0.1277 | 0.1172 | 1.516 [1.511-1.550] | 1.493 [1.482-1.861] |+| `many-lights-500` | 64 | 0.03061 | 0.02793 | 5.913 [5.837-7.692] | 5.974 [5.854-7.034] |+| `many-lights-500` | 256 | 0.00764 | 0.00699 | 23.57 [23.50-23.71] | 25.59 [24.83-25.76] |+| `many-lights-500` | 1024 | 0.00218 | 0.00200 | 94.84 [93.79-96.43] | 97.73 [93.23-144.8] |+| `metal` | 16 | 0.00450 | 0.6283 | 0.177 [0.153-0.215] | 0.171 [0.163-0.175] |+| `metal` | 64 | 0.2806 | 0.00422 | 0.628 [0.622-0.629] | 0.619 [0.601-0.718] |+| `metal` | 256 | 0.01812 | 0.07499 | 2.279 [2.264-2.914] | 2.752 [2.302-4.047] |+| `metal` | 1024 | 0.00831 | 0.00590 | 9.517 [8.986-13.27] | 9.298 [9.091-11.07] |++Time to equal error, log-log interpolation of time against relMSE on each renderer's ladder, only inside the errors both ladders cover. "Floor corrected" subtracts half of the reference's seed 1 versus seed 2 relMSE (the reference's own noise, which both renderers carry) from every error before interpolating `[measured and interpolated]`:++| scene | relMSE target | Cook s | Cycles s | Cook speed relative to Cycles | floor corrected |+| --- | ---: | ---: | ---: | ---: | ---: |+| `lit-interior` | 0.005 | 3.51 | 4.33 | 1.23x faster | 1.24x |+| `lit-interior` | 0.001 | 16.2 | 20.1 | 1.24x faster | 1.25x |+| `many-lights-500` | 0.005 | 37.7 | 36.6 | 0.97x (Cook slower) | 0.98x |+| `many-lights-500` | 0.00218 (lowest both reach) | 94.8 | 89.4 | 0.94x (Cook slower) | 0.93x (at 0.00178) |+| `metal` | none | | | not defined | |++What the table says:++- `lit-interior`: at equal samples Cook has 7 to 15 % lower error (0.00274 against 0.00310 at 256 spp, 0.000656 against 0.000771 at 1024) and takes 5 to 14 % less time on the medians from 64 spp up, so it reaches equal error about 1.2 times faster. The 16 and 64 spp Cycles times carry up to 5 s of noise in their ranges, probably start-up and load from other sessions on the shared card `[inferred]`; the cost per sample of both is close to 24 to 25 ms at 1024 spp. The earlier figure of 11.4 s for Cycles at 256 spp differs from the 5.7 to 8.3 s measured here; the card was shared in both cases.+- `many-lights-500`: Cook is slightly worse. The error is 9 to 10 % higher at equal samples at every rung, while the time per sample is between 1.5 % higher and 8 % lower than Cycles (16 spp +1.5 %, 64 spp -1 %, 256 spp -8 %, 1024 spp -3 %), so Cook needs about 3 to 6 % more time for the same error. This is the one scene where Cook is slower. The gap is small next to the run-to-run range of the Cycles 1024 spp time (93 to 145 s), so read it as a tie to slightly behind, not a clear loss. Where the 9 % comes from (differences between this tree and the Cycles tree, such as the double-sided emissive-triangle cone, or the sampler dimensions) was not isolated.+- `metal`: no equal-error time can be given. The error looks dominated by a few very bright paths rather than by smooth noise `[inferred]`. The reference's own seed-to-seed relMSE is 0.0034, higher than both targets, and neither ladder falls monotonically (Cook 0.0045, 0.281, 0.0181, 0.0083; Cycles 0.628, 0.0042, 0.0750, 0.0059): a single firefly decides a rung. Per sample the two run at the same speed (9.5 s against 9.3 s at 1024 spp). Parity of the converged image is separate and passes (4096 spp relMSE 0.00271 against the 0.0034 noise floor).+- The error gap on `many-lights-500` survived the review fix to `ltr_importance` (maximum importance now divided by the squared nearest distance and minimum by the squared farthest, as in Cycles): see "Repeat on Modal".+- Nothing here changes a gate or retunes a kernel default. The comparison is one seed per renderer and one Cycles reference; the error of a single rung moves with the seed, and the interpolation uses four points per curve, so ratios under about 10 % are not resolved.++### Repeat on Modal after the review fixes (NVIDIA A10G, 2026-11-12)++The review of #895 found that `ltr_importance` had the distances swapped against `kernel/light/tree.h` (the maximum importance is divided by the squared minimum distance, the minimum importance by the squared maximum distance). That is fixed, and the ladders were measured again on a Modal container instead of the RTX 3060: one NVIDIA A10G (driver 610.57, Vulkan 1.4 with ray queries; Cook picked the `NVIDIA A10G` adapter, not llvmpipe), Blender 5.3.0 Cycles on OptiX on the same card, one container for the whole run so the timings are comparable, seed 3 for both, three rounds in which each rung runs Cook then Cycles. Error is relMSE against the same 4096 spp seed 1 Cycles reference `[measured]`; seconds are `samplingSeconds` with the range of three runs. The harness is `modal/app.py` outside the repository (Modal functions `build_and_test`, `measure`, `parity`).++| scene | spp | Cook relMSE | Cycles relMSE | Cook s | Cycles s |+| --- | ---: | ---: | ---: | --- | --- |+| `lit-interior` | 16 | 0.06529 | 0.07024 | 0.196 [0.177-0.345] | 0.229 [0.227-0.230] |+| `lit-interior` | 64 | 0.01283 | 0.01483 | 0.651 [0.629-0.884] | 0.828 [0.826-0.830] |+| `lit-interior` | 256 | 0.002741 | 0.003103 | 2.500 [2.498-2.518] | 3.250 [3.249-3.257] |+| `lit-interior` | 1024 | 0.000656 | 0.000771 | 10.04 [10.04-10.05] | 13.07 [13.03-13.07] |+| `many-lights-500` | 16 | 0.1276 | 0.1173 | 0.663 [0.662-0.919] | 0.734 [0.734-0.737] |+| `many-lights-500` | 64 | 0.03059 | 0.02793 | 2.487 [2.483-2.499] | 2.795 [2.795-2.804] |+| `many-lights-500` | 256 | 0.007630 | 0.006984 | 9.843 [9.839-9.856] | 11.07 [11.04-11.12] |+| `many-lights-500` | 1024 | 0.002174 | 0.002001 | 39.32 [39.32-39.36] | 44.20 [44.06-44.21] |++Time to equal error, same interpolation as above `[measured and interpolated]`:++| scene | relMSE target | Cook s | Cycles s | Cook relative to Cycles |+| --- | ---: | ---: | ---: | ---: |+| `lit-interior` | 0.005 | 1.48 | 2.14 | 1.45x faster |+| `lit-interior` | 0.001 | 6.66 | 10.08 | 1.51x faster |+| `lit-interior` | 0.000771 (lowest both reach) | 8.58 | 13.07 | 1.52x faster |+| `many-lights-500` | 0.005 | 15.69 | 16.02 | 1.02x faster |+| `many-lights-500` | 0.002174 (lowest both reach) | 39.32 | 40.32 | 1.03x faster |++- Against the RTX 3060 figures, the Cook relMSE moved by at most 0.1 percent on `lit-interior` and 0.1 percent on `many-lights-500` (for example 0.127595 against 0.127697 at 16 spp and 0.002174 against 0.002175 at 1024 spp): the importance fix changes which emitter is picked, but not by much on these two scenes, and it does not close the 9 percent error gap to Cycles on `many-lights-500` (0.002174 against 0.002001 at 1024 spp). That gap is still not isolated.+- Both renderers are 2.0 to 2.5 times faster on the A10G than on the 3060 in these runs (Cook 2.4 to 2.5 times, Cycles 2.0 to 2.2 times), and the job ran alone in its container, so the Cycles ranges are tight (no 5 s outliers). On this card Cook is 1.45 to 1.52 times faster at equal error on `lit-interior` (1.2 times on the 3060) and level with Cycles on `many-lights-500` (3 to 6 percent slower on the 3060). The ratios depend on the GPU and on load `[inferred]`; no claim is made about other cards.+- The tree against the flat pick on `many-lights-500` (Cook, seed 3, A10G): error ratio uniform / tree 2.98, 2.86, 2.67 and 2.03 at 16, 64, 256 and 1024 spp, tree time 1.30 to 1.32 times the flat pick per sample (1.16 to 1.18 on the 3060). Time to equal error, tree against flat: 2.03 times faster at relMSE 0.0237, 2.05 at 0.0304, 1.80 at 0.00664 and 1.70 at 0.005 (the flat pick's 1024 spp run reaches only 0.00442, so it was run once there). The "less than half the time" reading of the gate holds at the larger errors and is 1.7 to 1.8 times near 0.005 on this card; the RTX 3060 figures above (2.0 to 2.3 times) were measured before the fix and on a different card.+- 4096 spp parity of the `cycles` kernel at its defaults, seven scenes, seed 1, on a Modal NVIDIA A10: 7 of 7 pass, with the same mean ratios, tile counts, FLIP LDR and relMSE as the table below to the digits shown (worst per-channel mean ratio 1.0035 on `lit-interior`, against the 2 percent limit). Cook sampling seconds at 4096 spp: `spot-area` 24.3, `light-linking` 27.2, `metal` 17.8, `glass` 30.1, `outdoor-hdri` 9.4, `lit-interior` 49.4, `many-lights-500` 205.7.+- Checks on the same Modal container: `cargo test` 25 passed, 0 failed (no GPU needed; the napi symbols are left unresolved at link time on Linux, and the one new test covers a tree flag without emitter tables); `node --test tests/native-*.test.js tests/cook-kernel-parity.test.js tests/cycles-parity-many-lights.test.js` 76 tests, 75 passed, 1 skipped, 0 failed; lobe probes 22 of 22 and sphere furnace scenes 6 of 6 at 512 spp.++### Final gates for #895++Release addon built; on the RTX 3060 `cargo test --target x86_64-pc-windows-msvc`: 24 pass; `node --test tests/native-*.test.js`: 53 pass; lobe probes 22 of 22 and sphere furnace scenes 6 of 6 pass (512 spp); 4096 spp parity of the `cycles` kernel at its defaults on all seven scenes, 7 of 7 pass `[measured]`. The Modal run after the review fixes gives the same table (see above) with 25 cargo tests and 75 node tests passing:++| scene | mean ratio (R / G / B) | tiles within 5 % | FLIP LDR (ceiling) | relMSE (noise floor) |+| --- | --- | ---: | --- | --- |+| `spot-area` | 1.0000 / 1.0000 / 1.0000 | 47 of 47 | 0.0039 (0.0239) | 0.000008 (0.000009) |+| `light-linking` | 1.0009 / 1.0007 / 1.0008 | 64 of 64 | 0.0051 (0.0228) | 0.000015 (0.000004) |+| `metal` | 0.9991 / 0.9992 / 0.9995 | 64 of 64 | 0.0042 (0.0237) | 0.00271 (0.003399) |+| `glass` | 0.9976 / 0.9978 / 0.9982 | 64 of 64 | 0.0070 (0.0234) | 0.000058 (0.000044) |+| `outdoor-hdri` | 0.9995 / 0.9996 / 0.9998 | 64 of 64 | 0.0023 (0.0215) | 0.000005 (0.000007) |+| `lit-interior` | 1.0032 / 1.0035 / 1.0034 | 64 of 64 | 0.0168 (0.0365) | 0.00026 (0.000285) |+| `many-lights-500` | 1.0009 / 1.0010 / 1.0009 | 64 of 64 | 0.0178 (0.0373) | 0.000832 (0.000791) |+## Reproducible CommandsRun from the repository root in PowerShell. Set `$env:BLENDER_BIN` if Blender 5.3 is installed outside `C:\Program Files\Blender Foundation\Blender 5.3\blender.exe`, and pass an untracked `<out-dir>` (such as `artifacts/cycles-parity`) so binary `.exr` and `.npy` files stay out of Git:@@@ -522,3 -391,22 +522,5 @@@ uv run --no-project --with numpy pytho# Set GIT_BASH_BIN="C:\Program Files\Git\bin\bash.exe" and GPU_LOCK_SCRIPT="<path-to-gpu-lock.sh>" to wrap every GPU step automatically.uv run --no-project --with numpy --with psutil python bench/cycles-parity/run-m0-suite.py $OutDir --scene lit-interior --repeats 3 --bounces 8 --mode all```+-## Sampling and light selection (#895)--Cook's `cycles` kernel draws its random numbers from an Owen-scrambled Sobol sequence (Burley 2020, hash-based scrambling, one scramble per pixel and per group of four dimensions) and picks lights through a light tree (Conty and Kulla 2018) once the analytic lights or the emissive triangles number more than 8. `sampler: 'pcg'` and `useLightTree: false` restore the earlier behaviour. The pixel filter is unchanged: `box` unless `filterType: 'blackman-harris'` is passed, which is what a Cycles reference at its default filter needs.--Measured on the RTX 3060 at `480 × 270`, 8 bounces, `box` filter, two seeds per point, against a high-sample reference of the other variant with its own seed (`bench/cycles-parity/measure-sampler-noise.py`):--| Scene | Comparison | Samples | `relMSE` before | `relMSE` after | Drop |-| :--- | :--- | ---: | ---: | ---: | ---: |-| `lit-interior` | PCG hash, then Sobol-Burley | 16 | 0.1024 | 0.0886 | 13.5% |-| `lit-interior` | PCG hash, then Sobol-Burley | 64 | 0.02629 | 0.02022 | 23.1% |-| `lit-interior` | PCG hash, then Sobol-Burley | 256 | 0.007130 | 0.004966 | 30.4% |-| `lit-interior` with 500 point lights | uniform pick, then light tree | 16 | 0.09166 | 0.02193 | 76.1% |-| `lit-interior` with 500 point lights | uniform pick, then light tree | 256 | 0.004423 | 0.001235 | 72.1% |-| `lit-interior` with 500 point lights | uniform pick, then light tree | 1024 | 0.000993 | 0.000431 | 56.6% |--On the 500-light scene (`make-many-lights-scene.mjs`) the tree costs about 4% more time per sample and reaches the 1024-sample error of the uniform pick in `9.6 s` of sampling instead of `25.3 s` (log-log interpolation over the 16 to 1024 ladder). The mean image of the tree over the uniform pick is `0.99996`, and the per-channel mean of Sobol-Burley at 256 samples is within `0.04%` of the reference, so neither change moves the image mean.--Not done: the blue-noise arrangement of the per-pixel scrambles across the image (each pixel hashes its own scramble, so the error is white across pixels, not blue), and a light tree that stays on in scenes with a sun or with instances that restrict their light group. The image-match runs against Blender Cycles (`run-m1-parity.py`) need Blender, which this machine did not have on the path.++`bench/cycles-parity/make-many-lights-scene.mjs <scene.json> <out.json> --count 500` writes a copy of an exported scene with that many small point lights, and `bench/cycles-parity/measure-sampler-noise.py <scene.json> <outDir> --compare sampler|light-tree` measures relMSE per sample count for `white` against `sobol-burley`, or for `uniform` against `tree`, against a high-sample reference with its own seed.diff --cc packages/render-native/README.mdindex 62f8ce89,750cc742..c4f684f6--- a/packages/render-native/README.md+++ b/packages/render-native/README.md@@@ -31,3 -31,5 +31,5 @@@ const { radiance, escaped } = traceNati````radiance` is the mean light that reaches each texel (three floats per texel) and `escaped` the share of first rays that left the scene. The agent runtime uses it for recipe bakes (`bake.backend: "native"`).+-Cook's sampler is an Owen-scrambled Sobol sequence (Burley 2020); `sampler: 'pcg'` selects the earlier white-noise hash. Lights are picked through a light tree (Conty and Kulla 2018) when a kind, analytic lights or emissive triangles, holds more than 8 emitters, no sun is among the lights and no instance restricts its light group; `useLightTree: true` forces it and `false` turns it off. Both change only the noise pattern of the image, not its mean. The pixel filter stays `box` unless `filterType: 'blackman-harris'` is passed ([FORMAT-v2.md](./FORMAT-v2.md)).++Cook's `cycles` kernel samples with Cycles' Sobol-Burley blue-noise pattern (`sampler: 'sobol-burley'`, default; `'white'` keeps the earlier hash sampler, and `'pcg'` and `'sobol'` are other names for `'white'` and `'sobol-burley'`). It picks lights through the Cycles light tree over the analytic lights, a sun and the emissive triangles (`lightSampling: 'auto'`, default: tree from more than one emitter; `'tree'`; `'uniform'` for the flat pick, and `useLightTree: true|false` is another name for `'tree'|'uniform'`). Naming an option twice with different values is an error. The pixel filter is `box` unless `filterType` says otherwise. Details and measurements: [docs/cycles-parity.md](../../docs/cycles-parity.md), layout: [FORMAT-v2.md](./FORMAT-v2.md).diff --cc packages/render-native/index.mjsindex 98a0673b,8c02fefc..0c013d34--- a/packages/render-native/index.mjs+++ b/packages/render-native/index.mjs@@@ -9,15 -9,7 +9,16 @@@ importFORMAT_V2_MAGIC,FORMAT_V2_VERSION,STRUCT_STRIDES_V2,+ KERNEL_FLAG_USE_LIGHT_TREE,+ KERNEL_FLAG_WHITE_NOISE_SAMPLER,++ resolveSamplingOptions,+ resolveUseLightTree,KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,+ KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET,+ KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET,+ KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET,+ filterTypeCode,+ resolveFilterParameters,buildNativeInputV2,packMaterialRecordV2,upgradeNativeInputV1ToV2,@@@ -69,6 -61,6 +70,7 @@@ export function resolveNativeKernel(ker*/export function traceNative(input, options = {}) {validatePackOptions(options, 'traceNative', true);++ const { sampler, lightSampling } = resolveSamplingOptions(options, 'traceNative');const { width, height, samples, maxSeconds, kernel, samplesPerDispatch, bootstrapKernel } = options;const selectedKernel = resolveNativeKernel(kernel);const addon = loadAddon();@@@ -91,15 -83,6 +93,15 @@@new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength).setFloat32(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, resolvedFilterGlossy, true);v2Input = { ...v2Input, kernelParams: patchedParams };}+ if (input?.schemaVersion === FORMAT_V2_VERSION && hasFilterOptions(options)) {+ v2Input = { ...v2Input, kernelParams: withFilterOptions(v2Input.kernelParams, options) };+ }- if (input?.schemaVersion === FORMAT_V2_VERSION && options.sampler !== undefined) {- v2Input = { ...v2Input, kernelParams: withSamplerFlag(v2Input.kernelParams, options.sampler) };++ if (input?.schemaVersion === FORMAT_V2_VERSION && sampler !== undefined) {++ v2Input = { ...v2Input, kernelParams: withSamplerFlag(v2Input.kernelParams, sampler) };+ }- if (input?.schemaVersion === FORMAT_V2_VERSION && options.lightSampling !== undefined) {- v2Input = { ...v2Input, kernelParams: withLightSamplingFlag(v2Input, options.lightSampling) };++ if (input?.schemaVersion === FORMAT_V2_VERSION && lightSampling !== undefined) {++ v2Input = { ...v2Input, kernelParams: withLightSamplingFlag(v2Input, lightSampling) };+ }return addon.traceSceneCycles(v2Input, {width,height,diff --cc packages/render-native/pack-input-v2.mjsindex 78177de5,fc49e3d3..978efc9b--- a/packages/render-native/pack-input-v2.mjs+++ b/packages/render-native/pack-input-v2.mjs@@@ -1498,35 -1461,6 +1498,68 @@@ function requireFiniteIntegerInRangeIfP* Validates public boundary options for `buildNativeInputV2`, `upgradeNativeInputV1ToV2`, and* `traceNative`. Throws `RangeError` or `TypeError` with a descriptive message on failure.*/+/** Throws unless `sampler` is undefined, "sobol-burley" (the Cycles default pattern) or "white" (the PCG hash). */+export function validateSamplerOption(sampler, callerName) {+ if (sampler !== undefined && !VALID_SAMPLERS.includes(sampler)) {+ throw new RangeError(+ `${callerName}: \`sampler\` must be "sobol-burley" (default) or "white", got ${JSON.stringify(sampler)}.`+ );+ }+}++/** Throws unless `lightSampling` is undefined, "auto", "tree" or "uniform". */+export function validateLightSamplingOption(lightSampling, callerName) {+ if (lightSampling !== undefined && !VALID_LIGHT_SAMPLING.includes(lightSampling)) {+ throw new RangeError(+ `${callerName}: \`lightSampling\` must be "auto" (default), "tree" or "uniform", got ${JSON.stringify(lightSampling)}.`+ );+ }+}+++/**++ * Reads the sampler and light-selection options, including the earlier names `sampler: 'pcg'` (same as `'white'`),++ * `sampler: 'sobol'` (same as `'sobol-burley'`) and `useLightTree: true|false` (same as `lightSampling: 'tree'|'uniform'`).++ * Returns `{ sampler, lightSampling }` with the canonical names, or `undefined` for an option that was left out.++ * Throws when a name is unknown or when an alias and its canonical option disagree.++ */++export function resolveSamplingOptions(options, callerName) {++ const samplerAliases = { pcg: 'white', sobol: 'sobol-burley' };++ let sampler = options.sampler;++ if (typeof sampler === 'string' && Object.hasOwn(samplerAliases, sampler)) {++ sampler = samplerAliases[sampler];++ }++ validateSamplerOption(sampler, callerName);++++ let lightSampling = options.lightSampling;++ validateLightSamplingOption(lightSampling, callerName);++ if (options.useLightTree !== undefined) {++ if (typeof options.useLightTree !== 'boolean') {++ throw new TypeError(++ `${callerName}: \`useLightTree\` must be true, false or left out for automatic, got ${JSON.stringify(options.useLightTree)}.`++ );++ }++ const aliasedLightSampling = options.useLightTree ? 'tree' : 'uniform';++ if (lightSampling !== undefined && lightSampling !== aliasedLightSampling) {++ throw new RangeError(++ `${callerName}: \`useLightTree: ${options.useLightTree}\` means \`lightSampling: "${aliasedLightSampling}"\`, which disagrees with \`lightSampling: "${lightSampling}"\`. Pass only one of them.`++ );++ }++ lightSampling = aliasedLightSampling;++ }++ return { sampler, lightSampling };++}+++/** True when the kernel should pick lights through the light tree for this scene and mode. */+export function resolveUseLightTree(lightSampling, emitterCount, lightTreeNodeCount) {+ if (lightTreeNodeCount <= 0 || lightSampling === 'uniform') {+ return false;+ }+ if (lightSampling === 'tree') {+ return emitterCount > 0;+ }+ return emitterCount > LIGHT_TREE_AUTO_MIN_EMITTERS;+}+export function validatePackOptions(options, callerName, requireDimensionsAndSamples = false) {if (!options || typeof options !== 'object') {throw new TypeError(`${callerName}: \`options\` must be an object.`);@@@ -1544,9 -1478,12 +1577,8 @@@// samplesPerDispatch is optional (undefined means "let the addon choose"); only validate when provided.requireFiniteIntegerInRangeIfPresent(samplesPerDispatch, 'samplesPerDispatch', 1, 65536, callerName);validateMaxSeconds(options.maxSeconds, callerName);- validateSamplerOption(options.sampler, callerName);- validateLightSamplingOption(options.lightSampling, callerName);- if (options.sampler !== undefined && options.sampler !== 'sobol' && options.sampler !== 'pcg') {- throw new RangeError(`${callerName}: \`sampler\` must be "sobol" or "pcg", got ${JSON.stringify(options.sampler)}.`);- }- if (options.useLightTree !== undefined && typeof options.useLightTree !== 'boolean') {- throw new TypeError(`${callerName}: \`useLightTree\` must be true, false or left out for automatic, got ${JSON.stringify(options.useLightTree)}.`);- }++ resolveSamplingOptions(options, callerName);+ validateFilterOptions(options, callerName);if (width !== undefined && height !== undefined) {validateImagePixelCount(width, height, callerName);if (samplesPerDispatch !== undefined) {@@@ -1644,21 -1557,11 +1676,21 @@@ function packKernelParamsV2(const volumeDensity = Math.max(0, Number(volume?.density ?? 0));let kernelFlags = 0;- validateLightSamplingOption(options.lightSampling, 'packKernelParamsV2');- if (counts.analyticLightTree === true) {- kernelFlags |= KERNEL_FLAG_USE_LIGHT_TREE;++ const { sampler, lightSampling } = resolveSamplingOptions(options, 'packKernelParamsV2');+ if (options.directLighting !== undefined && !VALID_DIRECT_LIGHTING.includes(options.directLighting)) {+ throw new RangeError(`packKernelParamsV2: \`directLighting\` must be "both", "nee-only" or "bsdf-only", got ${JSON.stringify(options.directLighting)}.`);+ }+ if (options.directLighting === 'nee-only') {+ kernelFlags |= KERNEL_FLAG_TEST_NEE_ONLY;+ } else if (options.directLighting === 'bsdf-only') {+ kernelFlags |= KERNEL_FLAG_TEST_BSDF_ONLY;}- if (counts.emissiveLightTree === true) {- kernelFlags |= KERNEL_FLAG_USE_EMISSIVE_LIGHT_TREE;+ if (options.lightTreeProbe === true) {+ kernelFlags |= KERNEL_FLAG_LIGHT_TREE_PROBE;+ }+ const emitterCount = counts.lightCount + counts.emissiveTriangleCount;- if (resolveUseLightTree(options.lightSampling, emitterCount, counts.lightTreeNodeCount)) {++ if (resolveUseLightTree(lightSampling, emitterCount, counts.lightTreeNodeCount)) {+ kernelFlags |= KERNEL_FLAG_USE_LIGHT_TREE;}if (volumeDensity > 0) {kernelFlags |= KERNEL_FLAG_HAS_VOLUME;@@@ -1675,9 -1578,8 +1707,8 @@@if (options.transparentBackground === true) {kernelFlags |= KERNEL_FLAG_TRANSPARENT_BACKGROUND;}- validateSamplerOption(options.sampler, 'packKernelParamsV2');- if (options.sampler === 'white') {- if (options.sampler === 'pcg') {- kernelFlags |= KERNEL_FLAG_PCG_SAMPLER;++ if (sampler === 'white') {+ kernelFlags |= KERNEL_FLAG_WHITE_NOISE_SAMPLER;}const maxBounces = Math.max(0, Math.round(Number(options.bounces ?? options.maxBounces ?? 8)));diff --cc tests/native-light-tree.test.jsindex 219e55bb,a53987f8..0251a3eb--- a/tests/native-light-tree.test.js+++ b/tests/native-light-tree.test.js@@@ -1,549 -1,136 +1,660 @@@import assert from 'node:assert/strict';import test from 'node:test';- import { buildNativeInputV2, withLightSamplingFlag } from '../packages/render-native/index.mjs';-import { STRUCT_STRIDES_V2, buildNativeInputV2 } from '../packages/render-native/index.mjs';-import { NO_TREE_ROOT } from '../packages/render-native/light-tree-v2.mjs';++import { STRUCT_STRIDES_V2, buildNativeInputV2, withLightSamplingFlag } from '../packages/render-native/index.mjs';+import { readFileSync } from 'node:fs';+import {+ LIGHT_TREE_EMITTER_BYTES,+ LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS,+ LIGHT_TREE_MAX_EMITTERS,+ LIGHT_TREE_NODE_BYTES,+ buildLightTree,+ coneMeasure,+ mergeCones,+} from '../packages/render-native/light-tree-v2.mjs';import { createCamera } from '../src/path-tracer.js';+ import { buildTraceScene } from '../src/path-tracer-scene.js';+const LIGHT_BYTES = 128;+const TRIANGLE_BYTES = 96;+const TYPE_POINT = 0;+const TYPE_SPOT = 1;+const TYPE_AREA_RECT = 2;+const TYPE_SUN = 4;+const LEAF_LIMIT = 8;++function createRandom(seed) {+ let state = seed >>> 0;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++function randomDirection(random) {+ const z = random() * 2 - 1;+ const angle = random() * Math.PI * 2;+ const ring = Math.sqrt(1 - z * z);+ return [ring * Math.cos(angle), ring * Math.sin(angle), z];+}++function writeLight(bytes, index, light) {+ const floats = new Float32Array(bytes.buffer, index * LIGHT_BYTES, LIGHT_BYTES / 4);+ const words = new Uint32Array(bytes.buffer, index * LIGHT_BYTES, LIGHT_BYTES / 4);+ floats.set(light.position, 0);+ words[3] = light.type;+ floats.set(light.radiance, 4);+ floats.set(light.direction, 8);+ floats[11] = light.radius ?? 0;+ floats.set(light.axisU ?? [1, 0, 0], 12);+ floats[15] = light.sizeU ?? 0;+ floats.set(light.axisV ?? [0, 1, 0], 16);+ floats[19] = light.sizeV ?? 0;+ floats[20] = light.cosHalfAngle ?? 0;+ floats[22] = light.tanHalfSpread ?? 0;+ floats[24] = light.areaOrSolidAngle ?? 0;+ words[30] = light.maskLow ?? 1;+}++function makeLights(count, seed, { includeSun = false } = {}) {+ const random = createRandom(seed);+ const bytes = new Uint8Array(Math.max(1, count) * LIGHT_BYTES);+ for (let index = 0; index < count; index++) {+ const position = [random() * 40 - 20, random() * 10, random() * 40 - 20];+ const radiance = [0.2 + random() * 5, 0.2 + random() * 5, 0.2 + random() * 5];+ const direction = randomDirection(random);+ const choice = includeSun && index === count - 1 ? 3 : Math.floor(random() * 3);+ if (choice === 0) {+ writeLight(bytes, index, { position, type: TYPE_POINT, radiance, direction, radius: random() * 0.3 });+ } else if (choice === 1) {+ writeLight(bytes, index, {+ position, type: TYPE_SPOT, radiance, direction, radius: 0.05, cosHalfAngle: Math.cos(0.2 + random()),+ });+ } else if (choice === 2) {+ const width = 0.5 + random();+ const height = 0.5 + random();+ writeLight(bytes, index, {+ position, type: TYPE_AREA_RECT, radiance, direction, sizeU: width, sizeV: height, areaOrSolidAngle: width * height,+ });+ } else {+ writeLight(bytes, index, {+ position, type: TYPE_SUN, radiance, direction, cosHalfAngle: Math.cos(0.005), areaOrSolidAngle: 6.8e-5,+ });+ }+ }+ return bytes;+}++function makeTriangles(count, seed) {+ const random = createRandom(seed);+ const bytes = new Uint8Array(Math.max(1, count) * TRIANGLE_BYTES);+ for (let index = 0; index < count; index++) {+ const floats = new Float32Array(bytes.buffer, index * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);+ const words = new Uint32Array(bytes.buffer, index * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);+ const origin = [random() * 40 - 20, random() * 10, random() * 40 - 20];+ const edgeOne = [random() - 0.5, random() - 0.5, random() - 0.5];+ const edgeTwo = [random() - 0.5, random() - 0.5, random() - 0.5];+ const cross = [+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],+ ];+ const crossLength = Math.hypot(...cross);+ floats.set(origin, 0);+ floats[3] = 0.5 * crossLength;+ floats.set(edgeOne, 4);+ floats.set(edgeTwo, 8);+ floats.set(cross.map((value) => value / crossLength), 12);+ floats.set([1 + random() * 4, 1 + random() * 4, 1 + random() * 4], 16);+ words[22] = 1;+ }+ return bytes;+}++function readNode(tree, index) {+ const offset = index * LIGHT_TREE_NODE_BYTES;+ const floats = new Float32Array(tree.nodes.buffer, offset, 16);+ const words = new Uint32Array(tree.nodes.buffer, offset, 16);+ const ints = new Int32Array(tree.nodes.buffer, offset, 16);+ return {+ boxMin: [floats[0], floats[1], floats[2]],+ energy: floats[3],+ boxMax: [floats[4], floats[5], floats[6]],+ thetaO: floats[7],+ axis: [floats[8], floats[9], floats[10]],+ thetaE: floats[11],+ leftChild: ints[12],+ rightOrFirst: words[13],+ count: words[14] & 0xffff,+ isDistant: (words[14] & (1 << 17)) !== 0,+ maskOr: words[15],+ isLeaf: ints[12] < 0,+ };+}++function readEmitter(tree, slot) {+ const offset = slot * LIGHT_TREE_EMITTER_BYTES;+ const floats = new Float32Array(tree.emitters.buffer, offset, 8);+ const words = new Uint32Array(tree.emitters.buffer, offset, 8);+ return {+ energy: floats[0],+ thetaO: floats[1],+ thetaE: floats[2],+ isTriangle: (words[3] & 1) !== 0,+ isDistant: (words[3] & 2) !== 0,+ depth: words[3] >>> 8,+ recordIndex: words[4],+ leafIndex: words[5],+ trailLow: words[6],+ trailHigh: words[7],+ };+}++function normalize(vector) {+ const length = Math.hypot(...vector);+ return vector.map((value) => value / length);+}++function angleBetween(a, b) {+ const dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+ return Math.acos(Math.min(1, Math.max(-1, dot)));+}++// The geometry of one emitter as the test reads it back from the packed records.+function describeEmitter(lights, triangles, lightCount, unifiedIndex) {+ if (unifiedIndex < lightCount) {+ const floats = new Float32Array(lights.buffer, unifiedIndex * LIGHT_BYTES, LIGHT_BYTES / 4);+ const position = [floats[0], floats[1], floats[2]];+ const type = new Uint32Array(lights.buffer, unifiedIndex * LIGHT_BYTES, 4)[3];+ const direction = normalize([floats[8], floats[9], floats[10]]);+ if (type === TYPE_SUN) {+ return { axis: direction, normal: null, boxMin: null, boxMax: null };+ }+ let extent = [floats[11], floats[11], floats[11]];+ if (type === TYPE_AREA_RECT) {+ extent = [0, 1, 2].map(+ (axis) => 0.5 * floats[15] * Math.abs(floats[12 + axis]) + 0.5 * floats[19] * Math.abs(floats[16 + axis])+ );+ }+ return {+ axis: direction,+ normal: type === TYPE_AREA_RECT || type === TYPE_SPOT ? direction : null,+ normalSlack: 2e-3,+ boxMin: position.map((value, axis) => value - extent[axis]),+ boxMax: position.map((value, axis) => value + extent[axis]),+ };+ }+ const triangleIndex = unifiedIndex - lightCount;+ const floats = new Float32Array(triangles.buffer, triangleIndex * TRIANGLE_BYTES, TRIANGLE_BYTES / 4);+ const origin = [floats[0], floats[1], floats[2]];+ const vertices = [+ origin,+ origin.map((value, axis) => value + floats[4 + axis]),+ origin.map((value, axis) => value + floats[8 + axis]),+ ];+ return {+ axis: normalize([-floats[4], -floats[5], -floats[6]]),+ normal: [floats[12], floats[13], floats[14]],+ // A double-sided triangle cone is centred on an in-plane axis, so its normal is a quarter turn from it.+ normalSlack: Math.PI / 2 + 2e-3,+ boxMin: [0, 1, 2].map((axis) => Math.min(...vertices.map((vertex) => vertex[axis]))),+ boxMax: [0, 1, 2].map((axis) => Math.max(...vertices.map((vertex) => vertex[axis]))),+ };+}++function boxInside(innerMin, innerMax, outerMin, outerMax, slack = 1e-4) {+ return [0, 1, 2].every(+ (axis) => innerMin[axis] >= outerMin[axis] - slack && innerMax[axis] <= outerMax[axis] + slack+ );+}++// Walks the whole tree and returns every leaf with the chain of ancestors above it.+function collectLeaves(tree) {+ const leaves = [];+ const visit = (nodeIndex, ancestors, depth, trailLow) => {+ const node = readNode(tree, nodeIndex);+ if (node.isLeaf) {+ leaves.push({ nodeIndex, node, ancestors, depth, trailLow });+ return;+ }+ visit(node.leftChild, [...ancestors, nodeIndex], depth + 1, trailLow);+ visit(node.rightOrFirst, [...ancestors, nodeIndex], depth + 1, (trailLow | (1 << depth)) >>> 0);+ };+ visit(0, [], 0, 0);+ return leaves;+}++function checkTreeInvariants(tree, lights, triangles, lightCount, triangleCount) {+ const totalEmitters = lightCount + triangleCount;+ const leaves = collectLeaves(tree);+ const seenUnified = new Set();+ const seenSlots = new Set();++ for (const leaf of leaves) {+ assert.ok(leaf.node.count >= 1, 'a leaf holds at least one emitter');+ if (!leaf.node.isDistant) {+ assert.ok(leaf.node.count <= LEAF_LIMIT || leaf.depth >= 24, `leaf ${leaf.nodeIndex} holds ${leaf.node.count} emitters`);+ }+ let energySum = 0;+ for (let offset = 0; offset < leaf.node.count; offset++) {+ const slot = leaf.node.rightOrFirst + offset;+ assert.ok(!seenSlots.has(slot), `slot ${slot} appears in two leaves`);+ seenSlots.add(slot);+ const emitter = readEmitter(tree, slot);+ assert.equal(emitter.leafIndex, leaf.nodeIndex, 'emitter points at its leaf');+ assert.equal(emitter.depth, leaf.depth, 'emitter depth is its leaf depth');+ assert.equal(emitter.trailLow, leaf.trailLow, 'trail bits describe the path from the root');+ assert.equal(emitter.trailHigh, 0);+ const unifiedIndex = emitter.isTriangle ? lightCount + emitter.recordIndex : emitter.recordIndex;+ assert.ok(!seenUnified.has(unifiedIndex), `emitter ${unifiedIndex} appears in two leaves`);+ seenUnified.add(unifiedIndex);+ assert.equal(tree.lightToTree[unifiedIndex], slot, 'light_to_tree inverts the emitter order');+ energySum += emitter.energy;++ const geometry = describeEmitter(lights, triangles, lightCount, unifiedIndex);+ for (const ancestorIndex of [leaf.nodeIndex, ...leaf.ancestors.slice().reverse()]) {+ const ancestor = readNode(tree, ancestorIndex);+ if (geometry.boxMin && !ancestor.isDistant) {+ assert.ok(+ boxInside(geometry.boxMin, geometry.boxMax, ancestor.boxMin, ancestor.boxMax),+ `emitter ${unifiedIndex} lies inside the box of node ${ancestorIndex}`+ );+ }+ assert.ok(+ Math.min(Math.PI, angleBetween(ancestor.axis, geometry.axis) + emitter.thetaO) <= ancestor.thetaO + 2e-3,+ `node ${ancestorIndex} cone contains the cone of emitter ${unifiedIndex}`+ );+ assert.ok(ancestor.thetaE >= emitter.thetaE - 1e-6, `node ${ancestorIndex} keeps the widest theta_e`);+ if (geometry.normal) {+ assert.ok(+ angleBetween(ancestor.axis, geometry.normal) <= ancestor.thetaO + geometry.normalSlack,+ `node ${ancestorIndex} cone reaches the normal of emitter ${unifiedIndex}`+ );+ }+ }+ }+ assert.ok(+ Math.abs(leaf.node.energy - energySum) <= 1e-5 * Math.max(1, energySum),+ `leaf ${leaf.nodeIndex} energy is the sum of its emitters`+ );+ }+ assert.equal(seenUnified.size, totalEmitters, 'every emitter is in exactly one leaf');+ assert.equal(seenSlots.size, totalEmitters);++ for (let nodeIndex = 0; nodeIndex < tree.nodeCount; nodeIndex++) {+ const node = readNode(tree, nodeIndex);+ if (node.isLeaf) {+ continue;+ }+ const left = readNode(tree, node.leftChild);+ const right = readNode(tree, node.rightOrFirst);+ assert.ok(+ Math.abs(node.energy - (left.energy + right.energy)) <= 1e-5 * Math.max(1, node.energy),+ `node ${nodeIndex} energy equals the sum of its children`+ );+ assert.equal(node.maskOr, (left.maskOr | right.maskOr) >>> 0);+ for (const child of [left, right]) {+ if (!child.isDistant && child.energy > 0) {+ assert.ok(boxInside(child.boxMin, child.boxMax, node.boxMin, node.boxMax), `child box inside the box of node ${nodeIndex}`);+ }+ }+ }+}+++test('every emitter is in exactly one leaf and the node invariants hold for lights and triangles', () => {+ const lights = makeLights(60, 11);+ const triangles = makeTriangles(140, 12);+ const tree = buildLightTree(lights, 60, triangles, 140);+ assert.equal(tree.emitterCount, 200);+ assert.ok(tree.nodeCount > 1);+ assert.equal(tree.nodes.byteLength, tree.nodeCount * LIGHT_TREE_NODE_BYTES);+ assert.equal(tree.emitters.byteLength, 200 * LIGHT_TREE_EMITTER_BYTES);+ checkTreeInvariants(tree, lights, triangles, 60, 140);+});++test('sun lights form one distant leaf on the right of the root, outside the local tree', () => {+ const lights = makeLights(40, 21, { includeSun: true });+ const tree = buildLightTree(lights, 40, makeTriangles(30, 22), 30);+ checkTreeInvariants(tree, lights, makeTriangles(30, 22), 40, 30);+ const root = readNode(tree, 0);+ assert.ok(!root.isLeaf);+ const distant = readNode(tree, root.rightOrFirst);+ assert.ok(distant.isLeaf && distant.isDistant);+ assert.equal(distant.count, 1);+ const sun = readEmitter(tree, distant.rightOrFirst);+ assert.ok(sun.isDistant);+ assert.equal(sun.recordIndex, 39);+ assert.equal(sun.depth, 1);+ assert.equal(sun.trailLow, 1);+ const lightLeaf = new Uint32Array(lights.buffer, 39 * LIGHT_BYTES, 32)[27];+ assert.equal(lightLeaf, 0, 'the packed record is untouched by the builder');+ assert.equal(tree.lightLeafIndices[39], root.rightOrFirst);+});++test('a scene with only a sun is one distant leaf and an empty scene has no nodes', () => {+ const sunOnly = makeLights(1, 3, { includeSun: true });+ const tree = buildLightTree(sunOnly, 1, new Uint8Array(TRIANGLE_BYTES), 0);+ assert.equal(tree.nodeCount, 1);+ assert.ok(readNode(tree, 0).isDistant);++ const empty = buildLightTree(new Uint8Array(LIGHT_BYTES), 0, new Uint8Array(TRIANGLE_BYTES), 0);+ assert.equal(empty.nodeCount, 0);+ assert.equal(empty.emitterCount, 0);+ assert.equal(empty.nodes.byteLength, LIGHT_TREE_NODE_BYTES);+});++test('the same input gives byte-identical output, also from copied buffers', () => {+ const lights = makeLights(120, 31, { includeSun: true });+ const triangles = makeTriangles(300, 32);+ const first = buildLightTree(lights, 120, triangles, 300);+ const second = buildLightTree(lights.slice(), 120, triangles.slice(), 300);+ assert.deepEqual(first.nodes, second.nodes);+ assert.deepEqual(first.emitters, second.emitters);+ assert.deepEqual(first.lightToTree, second.lightToTree);+});++test('co-located emitters and emitters on one plane still build balanced trees within the leaf limit', () => {+ const lights = new Uint8Array(100 * LIGHT_BYTES);+ for (let index = 0; index < 100; index++) {+ writeLight(lights, index, {+ position: [1, 2, 3], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1], radius: 0.1,+ });+ }+ const colocated = buildLightTree(lights, 100, new Uint8Array(TRIANGLE_BYTES), 0);+ checkTreeInvariants(colocated, lights, new Uint8Array(TRIANGLE_BYTES), 100, 0);++ const planar = new Uint8Array(100 * LIGHT_BYTES);+ for (let index = 0; index < 100; index++) {+ writeLight(planar, index, {+ position: [5, index % 10, Math.floor(index / 10)], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1],+ });+ }+ const planarTree = buildLightTree(planar, 100, new Uint8Array(TRIANGLE_BYTES), 0);+ checkTreeInvariants(planarTree, planar, new Uint8Array(TRIANGLE_BYTES), 100, 0);+});++test('a tight spatial cluster of lights splits from a far one so the tree separates them', () => {+ const lights = new Uint8Array(20 * LIGHT_BYTES);+ for (let index = 0; index < 20; index++) {+ const cluster = index < 10 ? 0 : 1000;+ writeLight(lights, index, {+ position: [cluster + (index % 10) * 0.01, 0, 0], type: TYPE_POINT, radiance: [1, 1, 1], direction: [0, 0, -1], radius: 0.01,+ });+ }+ const tree = buildLightTree(lights, 20, new Uint8Array(TRIANGLE_BYTES), 0);+ const root = readNode(tree, 0);+ const left = readNode(tree, root.leftChild);+ const right = readNode(tree, root.rightOrFirst);+ assert.ok(left.boxMax[0] < 1 || right.boxMax[0] < 1, 'one child holds only the near cluster');+ assert.ok(left.boxMin[0] > 100 || right.boxMin[0] > 100, 'the other holds only the far cluster');+});++test('cone merge contains both inputs and the measure grows with the cone', () => {+ const coneA = { axis: [1, 0, 0], thetaO: 0.2, thetaE: 0.3 };+ const coneB = { axis: [0, 1, 0], thetaO: 0.1, thetaE: 0.5 };+ const merged = mergeCones(coneA, coneB);+ for (const cone of [coneA, coneB]) {+ assert.ok(Math.min(Math.PI, angleBetween(merged.axis, cone.axis) + cone.thetaO) <= merged.thetaO + 1e-9);+ }+ assert.equal(merged.thetaE, 0.5);+ assert.ok(coneMeasure(merged) > coneMeasure(coneA));+ assert.equal(coneMeasure({ axis: [0, 0, 0], thetaO: 0, thetaE: 0 }), 0);+ const opposite = mergeCones({ axis: [1, 0, 0], thetaO: 0, thetaE: 0 }, { axis: [-1, 0, 0], thetaO: 0, thetaE: 0 });+ assert.ok(Math.abs(Math.hypot(...opposite.axis) - 1) < 1e-9);+ assert.ok(opposite.thetaO >= Math.PI / 2 - 1e-9);++ const nearlyOpposite = [+ { axis: [1, 0, 0], thetaO: 0.3, thetaE: 0 },+ { axis: normalize([-1, 0.02, 0]), thetaO: 0.1, thetaE: 0 },+ ];+ const nearlyOppositeMerge = mergeCones(nearlyOpposite[0], nearlyOpposite[1]);+ for (const cone of nearlyOpposite) {+ const reach = Math.min(Math.PI, angleBetween(nearlyOppositeMerge.axis, cone.axis) + cone.thetaO);+ assert.ok(reach <= nearlyOppositeMerge.thetaO + 1e-9, 'a near-opposite merge still contains both cones');+ }+});++test('500 lights build in bounded time and 5000 emitters stay within the invariants', () => {+ const lights = makeLights(500, 41);+ const started = performance.now();+ const tree = buildLightTree(lights, 500, new Uint8Array(TRIANGLE_BYTES), 0);+ const elapsedMilliseconds = performance.now() - started;+ assert.ok(elapsedMilliseconds < 5000, `500 lights took ${elapsedMilliseconds.toFixed(0)} ms`);+ checkTreeInvariants(tree, lights, new Uint8Array(TRIANGLE_BYTES), 500, 0);++ const bigLights = makeLights(1000, 42);+ const bigTriangles = makeTriangles(4000, 43);+ const bigTree = buildLightTree(bigLights, 1000, bigTriangles, 4000);+ checkTreeInvariants(bigTree, bigLights, bigTriangles, 1000, 4000);+});++test('the boundary rejects bad counts, short buffers, non-finite values and unknown light types', () => {+ const lights = makeLights(2, 51);+ const triangles = makeTriangles(1, 52);+ assert.throws(() => buildLightTree(lights, -1, triangles, 1), /non-negative integer/);+ assert.throws(() => buildLightTree(lights, 2.5, triangles, 1), /non-negative integer/);+ assert.throws(() => buildLightTree(lights, 3, triangles, 1), /fewer than 3 records of 128 bytes/);+ assert.throws(() => buildLightTree(lights, 2, triangles, 2), /fewer than 2 records of 96 bytes/);+ assert.throws(() => buildLightTree([], 0, triangles, 1), /Uint8Array/);+ assert.throws(+ () => buildLightTree(lights, 2, triangles, LIGHT_TREE_MAX_EMITTERS),+ new RegExp(`exceed the limit of ${LIGHT_TREE_MAX_EMITTERS}`)+ );+ const broken = lights.slice();+ new Float32Array(broken.buffer, 0, 1)[0] = Number.NaN;+ assert.throws(() => buildLightTree(broken, 2, triangles, 1), /analytic light 0 has a non-finite value/);+ const unknownType = lights.slice();+ new Uint32Array(unknownType.buffer, 0, 4)[3] = 9;+ assert.throws(() => buildLightTree(unknownType, 2, triangles, 1), /unknown light_type 9/);+});++test('buildNativeInputV2 packs the tree, fills tree_leaf_index and keeps counts consistent', () => {+ const camera = createCamera({ eye: [0, 0, 6], target: [0, 0, 0], fov: 50 }, 16, 16);+ const quad = {+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),+ colors: new Float32Array(12).fill(1),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+ const v2 = buildNativeInputV2(+ {+ materials: [{ color: [0.8, 0.8, 0.8] }, { color: [1, 1, 1], emission: 5 }],+ instances: [+ { geometry: quad, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], materialIndex: 0 },+ { geometry: quad, matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 3, 0, 1], materialOverride: 1 },+ ],+ lights: {+ points: [+ { position: [2, 2, 2], intensity: 10, radius: 0.1 },+ { position: [-3, 1, 0], intensity: 4 },+ ],+ sun: { color: [1, 1, 1], direction: [0, 1, 0.2] },+ },+ },+ camera,+ { width: 16, height: 16, samples: 1 }+ );+ assert.equal(v2.lightCount, 3);+ assert.equal(v2.emissiveTriangleCount, 2);+ assert.equal(v2.lightTreeEmitterCount, 5);+ assert.ok(v2.lightTreeNodeCount >= 3);+ assert.equal(v2.lightTreeNodes.byteLength, v2.lightTreeNodeCount * LIGHT_TREE_NODE_BYTES);+ assert.equal(v2.lightTreeEmitters.byteLength, 5 * LIGHT_TREE_EMITTER_BYTES);+ assert.equal(v2.lightToTree.length, 5);+ const tree = {+ nodes: v2.lightTreeNodes,+ nodeCount: v2.lightTreeNodeCount,+ emitters: v2.lightTreeEmitters,+ lightToTree: v2.lightToTree,+ };+ checkTreeInvariants(tree, v2.lights, v2.emissiveTriangles, 3, 2);+ for (let index = 0; index < 3; index++) {+ const leafIndex = new Uint32Array(v2.lights.buffer, v2.lights.byteOffset + index * LIGHT_BYTES, 32)[27];+ const slot = v2.lightToTree[index];+ assert.equal(leafIndex, readEmitter(tree, slot).leafIndex, `light ${index} tree_leaf_index names its leaf`);+ }+ const kp = new Uint32Array(v2.kernelParams.buffer, v2.kernelParams.byteOffset, 80);+ assert.equal(kp[26], v2.lightTreeNodeCount, 'kernel params carry the node count');+});++test('the distant leaf limit matches the per-leaf clamp of the kernel', () => {+ const kernelSource = readFileSync(new URL('../packages/render-native/src/cycles/light_tree.wgsl', import.meta.url), 'utf8');+ const match = /const LTR_MAX_LEAF_EMITTERS: u32 = (\d+)u;/.exec(kernelSource);+ assert.ok(match, 'light_tree.wgsl declares LTR_MAX_LEAF_EMITTERS');+ assert.equal(Number(match[1]), LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS);+});++test('more distant lights than the kernel reads from one leaf are rejected with the allowed count', () => {+ const allowed = LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS;+ const suns = (count) => {+ const bytes = new Uint8Array(count * LIGHT_BYTES);+ for (let index = 0; index < count; index++) {+ writeLight(bytes, index, { position: [0, 0, 0], type: TYPE_SUN, radiance: [1, 1, 1], direction: [0, 1, 0] });+ }+ return bytes;+ };+ assert.doesNotThrow(() => buildLightTree(suns(allowed), allowed, new Uint8Array(TRIANGLE_BYTES), 0));+ assert.throws(+ () => buildLightTree(suns(allowed + 1), allowed + 1, new Uint8Array(TRIANGLE_BYTES), 0),+ new RegExp(`${allowed + 1} distant lights exceed the ${allowed} the kernel reads from one leaf. Pass at most ${allowed}`)+ );+});++test('index words of an emissive triangle are not checked as floats', () => {+ const triangles = makeTriangles(2, 61);+ const words = new Uint32Array(triangles.buffer);+ words[7] = 0xffffffff;+ words[11] = 0x7fc00000;+ words[15] = 0xffffffff;+ assert.doesNotThrow(() => buildLightTree(makeLights(1, 62), 1, triangles, 2));+});++test('lightSampling on a packed v2 input without emitter tables is rejected for "tree" and ignored for "auto"', () => {+ const kernelParams = new Uint8Array(320);+ const staleInput = { kernelParams, lightCount: 40, emissiveTriangleCount: 0, lightTreeNodeCount: 1 };+ const flagsOf = (params) => new DataView(params.buffer, params.byteOffset).getUint32(32, true);+ assert.throws(+ () => withLightSamplingFlag(staleInput, 'tree'),+ /lightSampling "tree" needs the emitter tables .* Repack the scene with buildNativeInputV2/+ );+ assert.equal(flagsOf(withLightSamplingFlag(staleInput, 'auto')) & 1, 0);+ const completeInput = {+ ...staleInput,+ lightTreeEmitters: new Uint8Array(32),+ lightToTree: new Uint32Array(1),+ lightTreeEmitterCount: 40,+ };+ assert.equal(flagsOf(withLightSamplingFlag(completeInput, 'tree')) & 1, 1);+ assert.equal(flagsOf(withLightSamplingFlag(completeInput, 'uniform')) & 1, 0);+});++++// Options and packing of a scene built from the trace scene (the tests adapted from the earlier sampler change, #957).+ const KERNEL_FLAGS_WORD = 8;+ const FLAG_USE_LIGHT_TREE = 1;-const FLAG_PCG_SAMPLER = 64;-const FLAG_USE_EMISSIVE_LIGHT_TREE = 128;++const FLAG_WHITE_NOISE_SAMPLER = 64;++ function floorGeometry() {+ return {+ positions: new Float32Array([-4, 0, -4, 4, 0, -4, 4, 0, 4, -4, 0, 4]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]),+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),+ colors: new Float32Array(12).fill(1),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+ }+-function pointLights(count) {++function pointLightList(count) {+ return Array.from({ length: count }, (_, index) => ({+ position: [(index % 5) - 2, 1 + (index % 3) * 0.5, Math.floor(index / 5) - 2],+ color: [1, 0.9, 0.8],+ intensity: 1 + index,+ radius: 0.05,+ }));+ }+-function pack(environment, options = {}, parts = [{ name: 'floor', geometry: floorGeometry(), material: { color: [0.5, 0.5, 0.5] } }]) {++function packTraceScene(environment, options = {}, parts = [{ name: 'floor', geometry: floorGeometry(), material: { color: [0.5, 0.5, 0.5] } }]) {+ const scene = buildTraceScene(parts, environment);+ const camera = createCamera({ eye: [0, 2, 6], target: [0, 0, 0], fov: 45 }, 32, 16);+ return buildNativeInputV2(scene, camera, { width: 32, height: 16, samples: 4, ...options });+ }+-function kernelFlags(input) {++function packedKernelFlags(input) {+ return new Uint32Array(input.kernelParams.buffer, input.kernelParams.byteOffset, STRUCT_STRIDES_V2.kernelParams / 4)[KERNEL_FLAGS_WORD];+ }+-function nodeViews(input) {- const stride = STRUCT_STRIDES_V2.lightTreeNode;- return Array.from({ length: input.lightTreeNodeCount }, (_, index) => {- const offset = input.lightTreeNodes.byteOffset + index * stride;- return {- f32: new Float32Array(input.lightTreeNodes.buffer, offset, stride / 4),- i32: new Int32Array(input.lightTreeNodes.buffer, offset, stride / 4),- u32: new Uint32Array(input.lightTreeNodes.buffer, offset, stride / 4),- };- });++function treeOf(input) {++ return { nodes: input.lightTreeNodes, nodeCount: input.lightTreeNodeCount, emitters: input.lightTreeEmitters, lightToTree: input.lightToTree };+ }+-function parentOf(node) {- return node.i32[12] < 0 ? -1 - node.i32[12] : node.u32[14] & 0xffff;-}--test('the Sobol-Burley sampler is the default and sampler "pcg" sets the opt-out flag', () => {- assert.equal(kernelFlags(pack({})) & FLAG_PCG_SAMPLER, 0);- assert.equal(kernelFlags(pack({}, { sampler: 'sobol' })) & FLAG_PCG_SAMPLER, 0);- assert.equal(kernelFlags(pack({}, { sampler: 'pcg' })) & FLAG_PCG_SAMPLER, FLAG_PCG_SAMPLER);- assert.throws(() => pack({}, { sampler: 'halton' }), /sampler.*sobol.*pcg/);++test('the Sobol-Burley sampler is the default, "white" sets the opt-out flag and "pcg" and "sobol" are its earlier names', () => {++ assert.equal(packedKernelFlags(packTraceScene({})) & FLAG_WHITE_NOISE_SAMPLER, 0);++ assert.equal(packedKernelFlags(packTraceScene({}, { sampler: 'sobol-burley' })) & FLAG_WHITE_NOISE_SAMPLER, 0);++ assert.equal(packedKernelFlags(packTraceScene({}, { sampler: 'sobol' })) & FLAG_WHITE_NOISE_SAMPLER, 0);++ assert.equal(packedKernelFlags(packTraceScene({}, { sampler: 'white' })) & FLAG_WHITE_NOISE_SAMPLER, FLAG_WHITE_NOISE_SAMPLER);++ assert.equal(packedKernelFlags(packTraceScene({}, { sampler: 'pcg' })) & FLAG_WHITE_NOISE_SAMPLER, FLAG_WHITE_NOISE_SAMPLER);++ assert.throws(() => packTraceScene({}, { sampler: 'halton' }), /sampler.*sobol-burley.*white/);+ });+-test('a scene with few lights keeps the cumulative pick, and useLightTree forces or forbids the tree', () => {- const environment = { pointLights: pointLights(3) };- assert.equal(pack(environment).lightTreeNodeCount, 0);- assert.equal(kernelFlags(pack(environment)) & FLAG_USE_LIGHT_TREE, 0);- assert.equal(pack(environment, { useLightTree: true }).lightTreeNodeCount, 1 + 5);- assert.equal(pack({ pointLights: pointLights(20) }, { useLightTree: false }).lightTreeNodeCount, 0);- assert.throws(() => pack(environment, { useLightTree: 'yes' }), /useLightTree/);++test('light selection: the tree is the default from two emitters, and lightSampling or its alias useLightTree forces or forbids it', () => {++ const few = { pointLights: pointLightList(3) };++ const many = { pointLights: pointLightList(20) };++ assert.equal(packedKernelFlags(packTraceScene({ pointLights: pointLightList(1) })) & FLAG_USE_LIGHT_TREE, 0, 'one emitter needs no pick');++ assert.equal(packedKernelFlags(packTraceScene(few)) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ assert.equal(packedKernelFlags(packTraceScene(many, { lightSampling: 'uniform' })) & FLAG_USE_LIGHT_TREE, 0);++ assert.equal(packedKernelFlags(packTraceScene(many, { useLightTree: false })) & FLAG_USE_LIGHT_TREE, 0);++ assert.equal(packedKernelFlags(packTraceScene({ pointLights: pointLightList(1) }, { useLightTree: true })) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ assert.deepEqual(++ packTraceScene(many, { useLightTree: false }).kernelParams,++ packTraceScene(many, { lightSampling: 'uniform' }).kernelParams,++ 'the alias packs the same bytes'++ );++ assert.doesNotThrow(() => packTraceScene(many, { useLightTree: true, lightSampling: 'tree' }));++ assert.throws(() => packTraceScene(many, { useLightTree: true, lightSampling: 'uniform' }), /disagrees/);++ assert.throws(() => packTraceScene(many, { useLightTree: 'yes' }), /useLightTree/);++ assert.throws(() => packTraceScene(many, { lightSampling: 'sometimes' }), /lightSampling/);+ });+-test('the analytic light tree links every light to the root through its parents and sums their energy', () => {++test('the light tree built from a trace scene links every light to the root and sums their energy', () => {+ const lightCount = 20;- const input = pack({ pointLights: pointLights(lightCount) });- assert.equal(kernelFlags(input) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);- assert.equal(kernelFlags(input) & FLAG_USE_EMISSIVE_LIGHT_TREE, 0);- assert.equal(input.lightTreeNodeCount, 1 + (2 * lightCount - 1));-- const nodes = nodeViews(input);- const analyticRoot = nodes[0].i32[12];- assert.equal(nodes[0].u32[13], NO_TREE_ROOT, 'no emissive tree');- assert.equal(parentOf(nodes[analyticRoot]), 0, 'the root hangs off the directory node');-- let leafEnergy = 0;- for (let lightIndex = 0; lightIndex < lightCount; lightIndex++) {- const leaf = nodes[1 + lightIndex];- assert.ok(leaf.i32[12] < 0, 'leaf marker');- assert.equal(leaf.u32[13], lightIndex, 'leaf stores its light index');- leafEnergy += leaf.f32[3];- let current = 1 + lightIndex;- for (let depth = 0; current !== analyticRoot; depth++) {- assert.ok(depth < 32, 'chain reaches the root');- const parent = parentOf(nodes[current]);- assert.ok(parent > 0, 'parent is a real node');- const children = [nodes[parent].i32[12], nodes[parent].u32[13]];- assert.ok(children.includes(current), 'the parent lists the child');- current = parent;- }- }++ const input = packTraceScene({ pointLights: pointLightList(lightCount) });++ assert.equal(packedKernelFlags(input) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ assert.equal(input.lightCount, lightCount);++ const tree = treeOf(input);++ checkTreeInvariants(tree, input.lights, input.emissiveTriangles, lightCount, 0);++ const root = readNode(tree, 0);++ const leafEnergy = collectLeaves(tree).reduce((sum, leaf) => sum + leaf.node.energy, 0);+ assert.ok(leafEnergy > 0);- assert.ok(Math.abs(nodes[analyticRoot].f32[3] - leafEnergy) <= leafEnergy * 1e-5, 'root energy is the sum of the leaves');++ assert.ok(Math.abs(root.energy - leafEnergy) <= leafEnergy * 1e-5, 'root energy is the sum of the leaves');+ });+-test('a sun, or light-linking masks, keep the analytic lights on the cumulative pick', () => {- const withSun = pack({ pointLights: pointLights(20), keyColor: [3, 3, 3], lightDirection: [0, 1, 0] });- assert.equal(kernelFlags(withSun) & FLAG_USE_LIGHT_TREE, 0);- assert.equal(withSun.lightTreeNodeCount, 0);++test('a sun stays in the tree as a distant leaf, so the other lights keep the tree pick', () => {++ const input = packTraceScene({ pointLights: pointLightList(20), keyColor: [3, 3, 3], lightDirection: [0, 1, 0] });++ assert.equal(packedKernelFlags(input) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ const tree = treeOf(input);++ checkTreeInvariants(tree, input.lights, input.emissiveTriangles, input.lightCount, 0);++ assert.ok(collectLeaves(tree).some((leaf) => leaf.node.isDistant), 'the sun is a distant leaf');+ });+-test('emissive triangles get their own tree, found through the directory node', () => {++test('emissive triangles are leaves of the same tree', () => {+ const emissivePanels = Array.from({ length: 12 }, (_, index) => {+ const geometry = floorGeometry();+ geometry.positions = geometry.positions.map((value, position) => (position % 3 === 1 ? 3 : value * 0.1 + (index - 6) * 0.6));+ return { name: `panel-${index}`, geometry, material: { color: [0.5, 0.5, 0.5], emission: 5 } };+ });- const input = pack({}, {}, emissivePanels);- assert.equal(kernelFlags(input) & FLAG_USE_EMISSIVE_LIGHT_TREE, FLAG_USE_EMISSIVE_LIGHT_TREE);- assert.equal(kernelFlags(input) & FLAG_USE_LIGHT_TREE, 0);++ const input = packTraceScene({}, {}, emissivePanels);+ assert.equal(input.emissiveTriangleCount, 24);++ assert.equal(packedKernelFlags(input) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ checkTreeInvariants(treeOf(input), input.lights, input.emissiveTriangles, input.lightCount, 24);++});+- const nodes = nodeViews(input);- const emissiveRoot = nodes[0].u32[13];- const leafBase = nodes[0].u32[15];- assert.notEqual(emissiveRoot, NO_TREE_ROOT);- assert.equal(leafBase, 1);- for (let triangle = 0; triangle < input.emissiveTriangleCount; triangle++) {- let current = leafBase + triangle;- assert.equal(nodes[current].u32[13], triangle);- for (let depth = 0; current !== emissiveRoot; depth++) {- assert.ok(depth < 32);- current = parentOf(nodes[current]);- }++test('light-link masks do not switch the tree off: every node keeps the OR of the masks below it', () => {++ const input = packTraceScene({ pointLights: pointLightList(20) });++ const lightWords = new Uint32Array(input.lights.buffer, input.lights.byteOffset, input.lights.byteLength / 4);++ let maskOr = 0;++ for (let index = 0; index < input.lightCount; index++) {++ maskOr = (maskOr | lightWords[index * (LIGHT_BYTES / 4) + 30]) >>> 0;+ }++ assert.equal(packedKernelFlags(input) & FLAG_USE_LIGHT_TREE, FLAG_USE_LIGHT_TREE);++ assert.equal(readNode(treeOf(input), 0).maskOr, maskOr);+ });