Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Pick next event lights through the Cycles light tree in the cycles kernel, with a light-sampling option and probes for pick probabilities and MIS (#895)

Nguyen Xuan Anbe112f646375
diff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjs
index 2538f938..615be561 100644
--- a/bench/cycles-parity/trace-native.mjs
+++ b/bench/cycles-parity/trace-native.mjs
@@ -66,9 +66,17 @@ function parseSamplerOption(argumentList) {
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;
+}
+
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 white|sobol-burley] [--filter-type box|gaussian|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]),
@@ -81,6 +89,9 @@ function parseTraceArguments(argumentList) {
seed: parseIntegerOption(argumentList, '--seed', 1, 0),
filterType: parseFilterTypeOption(argumentList),
sampler: parseSamplerOption(argumentList),
+ lightSampling: parseLightSamplingOption(argumentList),
+ directLighting: String(readFlagValue(argumentList, '--direct-lighting', 'both')),
+ lightTreeProbe: argumentList.includes('--light-tree-probe'),
filterWidth: parseNumberOption(argumentList, '--filter-width', 1.0, 0.01),
clampDirect: parseNumberOption(argumentList, '--clamp-direct', 0, 0),
clampIndirect: parseNumberOption(argumentList, '--clamp-indirect', 0, 0),
@@ -142,6 +153,7 @@ async function runCli() {
kernel: options.kernel,
filterType: options.filterType,
sampler: options.sampler,
+ lightSampling: options.lightSampling,
filterWidth: options.filterWidth,
clampDirect: options.clampDirect,
clampIndirect: options.clampIndirect,
@@ -169,6 +181,7 @@ async function runCli() {
seed: options.seed,
filterType: options.filterType,
sampler: options.sampler,
+ lightSampling: options.lightSampling,
filterWidth: options.filterWidth,
clampDirect: options.clampDirect,
clampIndirect: options.clampIndirect,
diff --git a/packages/render-native/FORMAT-v2.md b/packages/render-native/FORMAT-v2.md
index 75eacdb8..e77cd2a5 100644
--- a/packages/render-native/FORMAT-v2.md
+++ b/packages/render-native/FORMAT-v2.md
@@ -40,7 +40,7 @@ Total size: **320 bytes** (`20 × 16 B`), alignment: **16 bytes**.
| `20` | `4` | `4` | `u32` | `samples_per_dispatch` | Samples traced per pixel in one dispatch (`>= 1`) |
| `24` | `4` | `4` | `u32` | `total_samples` | Target total samples per pixel |
| `28` | `4` | `4` | `u32` | `seed` | Deterministic scramble seed |
-| `32` | `4` | `4` | `u32` | `kernel_flags` | Bitmask: `1=USE_LIGHT_TREE`, `2=HAS_VOLUME`, `4=HAS_SUBSURFACE`, `8=ORTHOGRAPHIC_CAMERA`, `16=ADAPTIVE_SAMPLING`, `32=TRANSPARENT_BACKGROUND`, `64=WHITE_NOISE_SAMPLER` (bit clear: Cycles' Sobol-Burley blue-noise pattern, the default; bit set: the PCG hash sampler) |
+| `32` | `4` | `4` | `u32` | `kernel_flags` | Bitmask: `1=USE_LIGHT_TREE`, `2=HAS_VOLUME`, `4=HAS_SUBSURFACE`, `8=ORTHOGRAPHIC_CAMERA`, `16=ADAPTIVE_SAMPLING`, `32=TRANSPARENT_BACKGROUND`, `64=WHITE_NOISE_SAMPLER` (bit clear: Cycles' Sobol-Burley blue-noise pattern, the default; bit set: the PCG hash sampler), `128=LIGHT_TREE_PROBE`, `256=TEST_NEE_ONLY`, `512=TEST_BSDF_ONLY` (the last three are for tests). Bit `1` is set by the packer from `lightSampling` (`auto` default: tree from more than one emitter; `tree`; `uniform`) and compiles the traversal in or out (`SCENE_HAS_LIGHT_TREE`) |
| `36` | `4` | `4` | `f32` | `adaptive_threshold` | Adaptive stop threshold (`0.0` = disabled) |
| `40` | `4` | `4` | `f32` | `clamp_direct` | Effective direct radiance ceiling at bounce `0` (`0.0` or `>= 1e30` = unclamped; Cycles `sample_clamp_direct * 3.0`) |
| `44` | `4` | `4` | `f32` | `clamp_indirect` | Effective indirect radiance ceiling at bounce `> 0` (`0.0` or `>= 1e30` = unclamped; Cycles `sample_clamp_indirect * 3.0`) |
@@ -319,7 +319,7 @@ Light tree revision 1 (`LIGHT_TREE_REVISION` in `light-tree-v2.mjs`; `schemaVers
## 7b. Light Tree Emitters — `LightTreeEmitter` (`@binding(13)`) and `light_to_tree` (`@binding(14)`)
-`LightTreeEmitter` stride: **32 bytes**, alignment 16 bytes. Slots are in tree order, so the emitters of a leaf are contiguous. Unified emitter index `i` is an analytic light for `i < light_count` and emissive triangle `i - light_count` otherwise; `light_to_tree[i]` is its slot. Both tables are optional in the napi input (`lightTreeEmitters`, `lightTreeEmitterCount`, `lightToTree` come together or not at all); without them the host binds a zeroed record. The kernel does not read them yet.
+`LightTreeEmitter` stride: **32 bytes**, alignment 16 bytes. Slots are in tree order, so the emitters of a leaf are contiguous. Unified emitter index `i` is an analytic light for `i < light_count` and emissive triangle `i - light_count` otherwise; `light_to_tree[i]` is its slot. Both tables are optional in the napi input (`lightTreeEmitters`, `lightTreeEmitterCount`, `lightToTree` come together or not at all); without them the host binds a zeroed record. With `USE_LIGHT_TREE` set the kernel (`light_tree.wgsl`, a translation of Cycles `kernel/light/tree.h`) picks one emitter per surface bounce by walking the nodes from the root with one random number, and finds the probability of a given emitter with `bit_trail_low/high` and `kind_and_depth` for the MIS weight of a BSDF-sampled hit. The environment map keeps its own importance sample and is not part of the tree.
| Byte Offset | Size (B) | WGSL Type | Field | Description |
| ---: | ---: | :--- | :--- | :--- |
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index f05ac64f..b2c45c36 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -9,7 +9,9 @@ import {
FORMAT_V2_MAGIC,
FORMAT_V2_VERSION,
STRUCT_STRIDES_V2,
+ KERNEL_FLAG_USE_LIGHT_TREE,
KERNEL_FLAG_WHITE_NOISE_SAMPLER,
+ resolveUseLightTree,
KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,
KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET,
buildNativeInputV2,
@@ -88,6 +90,9 @@ export function traceNative(input, options = {}) {
if (input?.schemaVersion === FORMAT_V2_VERSION && options.sampler !== undefined) {
v2Input = { ...v2Input, kernelParams: withSamplerFlag(v2Input.kernelParams, options.sampler) };
}
+ if (input?.schemaVersion === FORMAT_V2_VERSION && options.lightSampling !== undefined) {
+ v2Input = { ...v2Input, kernelParams: withLightSamplingFlag(v2Input, options.lightSampling) };
+ }
return addon.traceSceneCycles(v2Input, {
width,
height,
@@ -98,6 +103,19 @@ export function traceNative(input, options = {}) {
});
}
+function withLightSamplingFlag(v2Input, lightSampling) {
+ const patchedParams = new Uint8Array(v2Input.kernelParams);
+ const view = new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength);
+ const flags = view.getUint32(KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET, true);
+ const emitterCount = (v2Input.lightCount ?? 0) + (v2Input.emissiveTriangleCount ?? 0);
+ const useTree = resolveUseLightTree(lightSampling, emitterCount, v2Input.lightTreeNodeCount ?? 0);
+ const patchedFlags = useTree
+ ? (flags | KERNEL_FLAG_USE_LIGHT_TREE) >>> 0
+ : (flags & ~KERNEL_FLAG_USE_LIGHT_TREE) >>> 0;
+ view.setUint32(KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET, patchedFlags, true);
+ return patchedParams;
+}
+
function withSamplerFlag(kernelParams, sampler) {
const patchedParams = new Uint8Array(kernelParams);
const view = new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength);
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index a12abc4d..6b28bf0b 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -13,6 +13,10 @@ export const KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET = 300;
export const KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET = 32;
export const VALID_SAMPLERS = Object.freeze(['sobol-burley', 'white']);
+/** `auto` picks the light tree when the scene has more than `LIGHT_TREE_AUTO_MIN_EMITTERS` emitters. */
+export const VALID_LIGHT_SAMPLING = Object.freeze(['auto', 'tree', 'uniform']);
+/** A single emitter is picked with probability 1 either way, so the tree only pays off from two emitters on. */
+export const LIGHT_TREE_AUTO_MIN_EMITTERS = 1;
export const STRUCT_STRIDES_V2 = Object.freeze({
kernelParams: 320,
@@ -25,7 +29,12 @@ export const STRUCT_STRIDES_V2 = Object.freeze({
textureDescriptor: 32,
});
-const KERNEL_FLAG_USE_LIGHT_TREE = 1;
+export const KERNEL_FLAG_USE_LIGHT_TREE = 1;
+/** Tests only: see `KERNEL_FLAG_TEST_NEE_ONLY` and `KERNEL_FLAG_TEST_BSDF_ONLY` in abi.wgsl. */
+export const KERNEL_FLAG_LIGHT_TREE_PROBE = 128;
+const KERNEL_FLAG_TEST_NEE_ONLY = 256;
+const KERNEL_FLAG_TEST_BSDF_ONLY = 512;
+export const VALID_DIRECT_LIGHTING = Object.freeze(['both', 'nee-only', 'bsdf-only']);
const KERNEL_FLAG_HAS_VOLUME = 2;
const KERNEL_FLAG_HAS_SUBSURFACE = 4;
const KERNEL_FLAG_ORTHOGRAPHIC_CAMERA = 8;
@@ -1495,6 +1504,26 @@ export function validateSamplerOption(sampler, callerName) {
}
}
+/** 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)}.`
+ );
+ }
+}
+
+/** 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.`);
@@ -1513,6 +1542,7 @@ export function validatePackOptions(options, callerName, requireDimensionsAndSam
requireFiniteIntegerInRangeIfPresent(samplesPerDispatch, 'samplesPerDispatch', 1, 65536, callerName);
validateMaxSeconds(options.maxSeconds, callerName);
validateSamplerOption(options.sampler, callerName);
+ validateLightSamplingOption(options.lightSampling, callerName);
validateFilterOptions(options, callerName);
if (width !== undefined && height !== undefined) {
validateImagePixelCount(width, height, callerName);
@@ -1611,7 +1641,20 @@ function packKernelParamsV2({
const volumeDensity = Math.max(0, Number(volume?.density ?? 0));
let kernelFlags = 0;
- if (options.useLightTree === true && counts.lightTreeNodeCount > 0) {
+ validateLightSamplingOption(options.lightSampling, '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 (options.lightTreeProbe === true) {
+ kernelFlags |= KERNEL_FLAG_LIGHT_TREE_PROBE;
+ }
+ const emitterCount = counts.lightCount + counts.emissiveTriangleCount;
+ if (resolveUseLightTree(options.lightSampling, emitterCount, counts.lightTreeNodeCount)) {
kernelFlags |= KERNEL_FLAG_USE_LIGHT_TREE;
}
if (volumeDensity > 0) {
diff --git a/packages/render-native/src/cycles/abi.wgsl b/packages/render-native/src/cycles/abi.wgsl
index 792c7633..00358229 100644
--- a/packages/render-native/src/cycles/abi.wgsl
+++ b/packages/render-native/src/cycles/abi.wgsl
@@ -40,6 +40,12 @@ const KERNEL_FLAG_ADAPTIVE_SAMPLING: u32 = 16u;
const KERNEL_FLAG_TRANSPARENT_BACKGROUND: u32 = 32u;
// Set: unstratified PCG hash sampler. Clear (default): Cycles' Sobol-Burley blue-noise pattern.
const KERNEL_FLAG_WHITE_NOISE_SAMPLER: u32 = 64u;
+// Tests only: every pixel writes the light tree pick probabilities of one random shading point instead of tracing paths.
+const KERNEL_FLAG_LIGHT_TREE_PROBE: u32 = 128u;
+// Tests only: direct light samples carry no MIS weight and emissive hits found by the BSDF count nothing (NEE only), or the
+// reverse: no direct light samples and emissive hits count fully (BSDF only). Both clear is the normal MIS combination.
+const KERNEL_FLAG_TEST_NEE_ONLY: u32 = 256u;
+const KERNEL_FLAG_TEST_BSDF_ONLY: u32 = 512u;
// `KernelParamsV2.filter_type` values.
const FILTER_BOX: u32 = 0u;
@@ -113,6 +119,7 @@ const SCENE_HAS_ANALYTIC_LIGHTS: bool = true;
const SCENE_HAS_FINITE_LIGHTS: bool = true;
const SCENE_HAS_ENV_IMPORTANCE: bool = true;
const SCENE_HAS_LIGHT_LINKING: bool = true;
+const SCENE_HAS_LIGHT_TREE: bool = true;
const LOBE_NONE: u32 = 0u;
const LOBE_DIFFUSE: u32 = 1u;
const LOBE_GLOSSY_GGX: u32 = 2u;
diff --git a/packages/render-native/src/cycles/integrator.wgsl b/packages/render-native/src/cycles/integrator.wgsl
index f23e07a1..4ec6fe39 100644
--- a/packages/render-native/src/cycles/integrator.wgsl
+++ b/packages/render-native/src/cycles/integrator.wgsl
@@ -564,6 +564,15 @@ fn int_is_singular_bsdf_sample(closure: ptr<function, Closure>, point: ptr<funct
return false;
}
+fn int_closure_has_transmission(closure: ptr<function, Closure>) -> bool {
+ for (var lobe_index = 0u; lobe_index < (*closure).lobe_count; lobe_index += 1u) {
+ if ((*closure).lobes[lobe_index].lobe_type == LOBE_GLASS_GGX) {
+ return true;
+ }
+ }
+ return false;
+}
+
fn int_accumulate_direct_sample(
sample: LgtDirectSample,
closure: ptr<function, Closure>,
@@ -582,7 +591,8 @@ fn int_accumulate_direct_sample(
if (bsdf.value.x <= 0.0 && bsdf.value.y <= 0.0 && bsdf.value.z <= 0.0) {
return;
}
- let mis_weight = select(lgt_power_heuristic(sample.pdf, bsdf.pdf), 1.0, sample.is_delta != 0u);
+ let nee_only = (kernel_params.kernel_flags & KERNEL_FLAG_TEST_NEE_ONLY) != 0u;
+ let mis_weight = select(lgt_power_heuristic(sample.pdf, bsdf.pdf), 1.0, sample.is_delta != 0u || nee_only);
if (mis_weight <= 0.0) {
return;
}
@@ -854,6 +864,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
min_ray_pdf = min(phase_pdf, min_ray_pdf);
prev_recv_lo = 0xFFFFFFFFu;
prev_recv_hi = 0xFFFFFFFFu;
+ lgt_remember_mis_origin(scatter_pos, ray_dir, false, false);
continue;
}
@@ -943,11 +954,23 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
break;
}
+ let picks_through_tree = lgt_use_light_tree() && (kernel_params.light_count + kernel_params.emissive_triangle_count) > 0u;
+ let closure_has_transmission = SCENE_HAS_GLASS && int_closure_has_transmission(&closure);
for (var direct_source = 0u; direct_source < 3u; direct_source += 1u) {
+ if ((kernel_params.kernel_flags & KERNEL_FLAG_TEST_BSDF_ONLY) != 0u) {
+ break;
+ }
var direct_sample: LgtDirectSample;
direct_sample.valid = 0u;
direct_sample.pdf = 0.0;
- if (direct_source == 0u) {
+ if (direct_source == 0u && picks_through_tree) {
+ smp_seek(&rng, step, SMP_SLOT_ANALYTIC_PICK);
+ let tree_pick_u = smp_next_1d(&rng);
+ let tree_sample_uv = smp_next_2d(&rng);
+ direct_sample = lgt_sample_tree_emitter(&point, point.shading_normal, closure_has_transmission, tree_pick_u, tree_sample_uv);
+ } else if (direct_source == 1u && picks_through_tree) {
+ continue;
+ } else if (direct_source == 0u) {
if (SCENE_HAS_ANALYTIC_LIGHTS && kernel_params.light_count > 0u) {
smp_seek(&rng, step, SMP_SLOT_ANALYTIC_PICK);
direct_sample = lgt_sample_analytic_light(
@@ -1058,6 +1081,7 @@ fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
min_ray_pdf = min(bsdf_sample.pdf, min_ray_pdf);
prev_recv_lo = point.light_group_mask_lo;
prev_recv_hi = point.light_group_mask_hi;
+ lgt_remember_mis_origin(point.position, point.shading_normal, closure_has_transmission, picks_through_tree);
}
let exposed = int_sanitize_radiance(sample_radiance * exposure);
diff --git a/packages/render-native/src/cycles/kernel-manifest.txt b/packages/render-native/src/cycles/kernel-manifest.txt
index 05f88baf..3f59a4d7 100644
--- a/packages/render-native/src/cycles/kernel-manifest.txt
+++ b/packages/render-native/src/cycles/kernel-manifest.txt
@@ -11,4 +11,5 @@ bsdf_glass.wgsl
bsdf_coat.wgsl
closure.wgsl
lights.wgsl
+light_tree.wgsl
integrator.wgsl
diff --git a/packages/render-native/src/cycles/light_tree.wgsl b/packages/render-native/src/cycles/light_tree.wgsl
new file mode 100644
index 00000000..2c8c8841
--- /dev/null
+++ b/packages/render-native/src/cycles/light_tree.wgsl
@@ -0,0 +1,623 @@
+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Stochastic light tree traversal for next event estimation (`ltr_*`), ported from Cycles `kernel/light/tree.h` and the
+// `*_light_tree_parameters` helpers of `point.h`, `spot.h`, `area.h`, `distant.cpp` and `triangle.h`. Surface shading points
+// only: no volume segments, no instanced mesh subtrees and no light-link roots (FORMAT-v2.md sections 7 and 7b).
+//
+// `ltr_sample` walks from the root to a leaf with one random number that is rescaled at every choice, then picks an emitter
+// inside the leaf with two reservoirs (one driven by the maximum importance, one by the minimum). `ltr_pdf` walks the same
+// path for a known emitter, following the bit trail stored with it, and returns the probability that `ltr_sample` picks it.
+// Emitters are addressed by their unified index: analytic lights first, then emissive triangles after `light_count`.
+
+const LTR_EMITTER_KIND_TRIANGLE: u32 = 1u;
+const LTR_NODE_KIND_DISTANT: u32 = 131072u;
+const LTR_NODE_EMITTER_COUNT_MASK: u32 = 65535u;
+const LTR_MAX_TREE_DEPTH: u32 = 64u;
+const LTR_MAX_LEAF_EMITTERS: u32 = 32u;
+const LTR_LARGE_COSINE: f32 = 1.0e30;
+
+fn ltr_sin_from_cos(cosine: f32) -> f32 {
+ return sqrt(max(0.0, 1.0 - cosine * cosine));
+}
+
+fn ltr_cos_from_sin(sine: f32) -> f32 {
+ return sqrt(max(0.0, 1.0 - sine * sine));
+}
+
+fn ltr_normalize_with_length(vector: vec3<f32>, length_out: ptr<function, f32>) -> vec3<f32> {
+ let vector_length = length(vector);
+ *length_out = vector_length;
+ if (vector_length == 0.0) {
+ return vector;
+ }
+ return vector / vector_length;
+}
+
+fn ltr_safe_normalize(vector: vec3<f32>) -> vec3<f32> {
+ var unused_length = 0.0;
+ return ltr_normalize_with_length(vector, &unused_length);
+}
+
+// Cosine of the angle subtended by the sphere around the node box; -1 when the point is inside that sphere.
+fn ltr_cos_bound_subtended_angle(bounds_max: vec3<f32>, centroid: vec3<f32>, point: vec3<f32>) -> f32 {
+ let distance_to_center_sq = dot(point - centroid, point - centroid);
+ let radius_sq = dot(bounds_max - centroid, bounds_max - centroid);
+ if (distance_to_center_sq <= radius_sq) {
+ return -1.0;
+ }
+ return sqrt(max(0.0, 1.0 - radius_sq / distance_to_center_sq));
+}
+
+// Cycles `light_tree_importance` for a surface point. Returns (maximum importance, minimum importance).
+fn ltr_importance(
+ normal: vec3<f32>,
+ has_transmission: bool,
+ point_to_centroid: vec3<f32>,
+ cos_theta_u: f32,
+ cone_axis: vec3<f32>,
+ cone_theta_o: f32,
+ cone_theta_e: f32,
+ max_distance: f32,
+ min_distance: f32,
+ energy: f32,
+) -> vec2<f32> {
+ let sin_theta_u = ltr_sin_from_cos(cos_theta_u);
+
+ let raw_cos_theta_i = dot(point_to_centroid, normal);
+ let cos_theta_i = select(raw_cos_theta_i, abs(raw_cos_theta_i), has_transmission);
+ let sin_theta_i = ltr_sin_from_cos(cos_theta_i);
+
+ var cos_min_incidence_angle = 1.0;
+ if (cos_theta_i < cos_theta_u) {
+ cos_min_incidence_angle = cos_theta_i * cos_theta_u + sin_theta_i * sin_theta_u;
+ }
+ if (!has_transmission && cos_min_incidence_angle < 0.0) {
+ return vec2<f32>(0.0);
+ }
+ let cos_max_incidence_angle = max(cos_theta_i * cos_theta_u - sin_theta_i * sin_theta_u, 0.0);
+
+ var cos_theta = 1.0;
+ var sin_theta = 0.0;
+ if (!all(cone_axis == -point_to_centroid)) {
+ cos_theta = dot(cone_axis, -point_to_centroid);
+ sin_theta = ltr_sin_from_cos(cos_theta);
+ }
+
+ let cos_theta_minus_theta_u = cos_theta * cos_theta_u + sin_theta * sin_theta_u;
+ let sin_theta_o = sin(cone_theta_o);
+ let cos_theta_o = cos(cone_theta_o);
+
+ var cos_min_outgoing_angle = 1.0;
+ if (cos_theta >= cos_theta_u || cos_theta_minus_theta_u >= cos_theta_o) {
+ cos_min_outgoing_angle = 1.0;
+ } else if (cone_theta_o + cone_theta_e > PI || cos_theta_minus_theta_u > cos(cone_theta_o + cone_theta_e)) {
+ let sin_theta_minus_theta_u = ltr_sin_from_cos(cos_theta_minus_theta_u);
+ cos_min_outgoing_angle = cos_theta_minus_theta_u * cos_theta_o + sin_theta_minus_theta_u * sin_theta_o;
+ } else {
+ return vec2<f32>(0.0);
+ }
+
+ let safe_max_distance = max(max_distance, 1.0e-6);
+ let maximum_importance = abs(cos_min_incidence_angle * energy * cos_min_outgoing_angle / (safe_max_distance * safe_max_distance));
+
+ let cos_theta_plus_theta_u = cos_theta * cos_theta_u - sin_theta * sin_theta_u;
+ if (cone_theta_e - cone_theta_o < 0.0 || cos_theta < 0.0 || cos_theta_u < 0.0 || cos_theta_plus_theta_u < cos(cone_theta_e - cone_theta_o)) {
+ return vec2<f32>(maximum_importance, 0.0);
+ }
+ let sin_theta_plus_theta_u = ltr_sin_from_cos(cos_theta_plus_theta_u);
+ let cos_max_outgoing_angle = cos_theta_plus_theta_u * cos_theta_o - sin_theta_plus_theta_u * sin_theta_o;
+ let safe_min_distance = max(min_distance, 1.0e-6);
+ let minimum_importance = abs(cos_max_incidence_angle * energy * cos_max_outgoing_angle / (safe_min_distance * safe_min_distance));
+ return vec2<f32>(maximum_importance, minimum_importance);
+}
+
+// What `ltr_importance` needs about a node or an emitter. The builders below only gather these numbers; every importance
+// goes through one `ltr_importance` call so the compiled kernel keeps a single copy of the cone arithmetic per call site.
+struct LtrProfile {
+ point_to_centroid: vec3<f32>,
+ cos_theta_u: f32,
+ cone_axis: vec3<f32>,
+ theta_o: f32,
+ theta_e: f32,
+ max_distance: f32,
+ min_distance: f32,
+ energy: f32,
+ visible: bool,
+}
+
+fn ltr_invisible_profile() -> LtrProfile {
+ var profile: LtrProfile;
+ profile.point_to_centroid = vec3<f32>(0.0, 0.0, 1.0);
+ profile.cos_theta_u = 1.0;
+ profile.cone_axis = vec3<f32>(0.0, 0.0, 1.0);
+ profile.theta_o = 0.0;
+ profile.theta_e = 0.0;
+ profile.max_distance = 1.0;
+ profile.min_distance = 1.0;
+ profile.energy = 0.0;
+ profile.visible = false;
+ return profile;
+}
+
+fn ltr_profile_importance(profile: LtrProfile, normal: vec3<f32>, has_transmission: bool) -> vec2<f32> {
+ if (!profile.visible) {
+ return vec2<f32>(0.0);
+ }
+ return ltr_importance(
+ normal,
+ has_transmission,
+ profile.point_to_centroid,
+ profile.cos_theta_u,
+ profile.cone_axis,
+ profile.theta_o,
+ profile.theta_e,
+ profile.max_distance,
+ profile.min_distance,
+ profile.energy,
+ );
+}
+
+// A node is described by its box, cone and energy. The distant leaf covers a cone of directions instead.
+fn ltr_node_profile(node_index: u32, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> LtrProfile {
+ let node = light_tree_nodes[node_index];
+ var profile = ltr_invisible_profile();
+ if (node.energy <= 0.0) {
+ return profile;
+ }
+ profile.cone_axis = node.cone_axis;
+ profile.theta_o = node.theta_o;
+ profile.theta_e = node.theta_e;
+ profile.energy = node.energy;
+ profile.visible = true;
+
+ if ((node.emitter_count_and_kind & LTR_NODE_KIND_DISTANT) != 0u) {
+ profile.point_to_centroid = -node.cone_axis;
+ profile.cos_theta_u = cos(node.theta_o + node.theta_e);
+ return profile;
+ }
+
+ let centroid = 0.5 * (node.bounds_min + node.bounds_max);
+ let box_extent = node.bounds_max - centroid;
+ let box_is_visible = has_transmission || (dot(normal, centroid - position) + dot(abs(normal), abs(box_extent)) > 0.0);
+ if (!box_is_visible) {
+ profile.visible = false;
+ return profile;
+ }
+ var distance = 0.0;
+ profile.point_to_centroid = ltr_normalize_with_length(centroid - position, &distance);
+ profile.cos_theta_u = ltr_cos_bound_subtended_angle(node.bounds_max, centroid, position);
+ distance = max(0.5 * length(centroid - node.bounds_max), distance);
+ profile.max_distance = distance;
+ profile.min_distance = distance;
+ return profile;
+}
+
+fn ltr_triangle_profile(emitter: LightTreeEmitter, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> LtrProfile {
+ let triangle = emissive_triangles[emitter.record_index];
+ let vertex_zero = triangle.p0;
+ let vertex_one = triangle.p0 + triangle.edge1;
+ let vertex_two = triangle.p0 + triangle.edge2;
+ let centroid = (vertex_zero + vertex_one + vertex_two) / 3.0;
+
+ var profile = ltr_invisible_profile();
+ profile.cone_axis = ltr_safe_normalize(vertex_zero - vertex_one);
+ profile.theta_o = emitter.theta_o;
+ profile.theta_e = emitter.theta_e;
+ profile.energy = emitter.energy;
+
+ var min_distance = 0.0;
+ profile.point_to_centroid = ltr_normalize_with_length(centroid - position, &min_distance);
+ profile.min_distance = min_distance;
+ profile.max_distance = min_distance;
+ profile.cos_theta_u = LTR_LARGE_COSINE;
+ var shape_above_surface = false;
+ for (var corner_index = 0u; corner_index < 3u; corner_index += 1u) {
+ var corner = vertex_zero;
+ if (corner_index == 1u) {
+ corner = vertex_one;
+ } else if (corner_index == 2u) {
+ corner = vertex_two;
+ }
+ var corner_distance = 0.0;
+ let point_to_corner = ltr_normalize_with_length(corner - position, &corner_distance);
+ profile.cos_theta_u = min(profile.cos_theta_u, dot(profile.point_to_centroid, point_to_corner));
+ shape_above_surface = shape_above_surface || dot(point_to_corner, normal) > 0.0;
+ profile.max_distance = max(profile.max_distance, corner_distance);
+ }
+
+ let front_facing = emitter.theta_o != 0.0 || dot(profile.cone_axis, profile.point_to_centroid) < 0.0;
+ profile.visible = (front_facing && shape_above_surface) || has_transmission;
+ return profile;
+}
+
+fn ltr_sphere_light_profile(light: LightRecord, emitter: LightTreeEmitter, position: vec3<f32>) -> LtrProfile {
+ var profile = ltr_invisible_profile();
+ var min_distance = 0.0;
+ profile.point_to_centroid = ltr_normalize_with_length(light.position - position, &min_distance);
+ profile.theta_e = emitter.theta_e;
+ profile.energy = emitter.energy;
+ profile.visible = true;
+ profile.cone_axis = ltr_safe_normalize(position - light.position);
+ if (min_distance > light.radius) {
+ profile.cos_theta_u = ltr_cos_from_sin(light.radius / min_distance);
+ profile.max_distance = min_distance / profile.cos_theta_u;
+ profile.min_distance = min_distance;
+ } else {
+ profile.cos_theta_u = -1.0;
+ profile.max_distance = light.radius / sqrt(2.0);
+ profile.min_distance = profile.max_distance;
+ }
+
+ if (light.light_type == LIGHT_TYPE_SPOT) {
+ profile.cone_axis = light.direction;
+ profile.theta_o = emitter.theta_o;
+ let cos_min_outgoing_angle = cos(max(0.0, acos(clamp(dot(profile.cone_axis, -profile.point_to_centroid), -1.0, 1.0)) - acos(clamp(profile.cos_theta_u, -1.0, 1.0))));
+ let blend_offset = cos_min_outgoing_angle - cos(emitter.theta_e);
+ var blend_weight = select(0.0, 1.0, blend_offset > 0.0);
+ if (light.spot_blend > 0.0) {
+ let blend_span = max((1.0 - light.cos_half_angle) * light.spot_blend, 1.0e-8);
+ let blend_t = clamp(blend_offset / blend_span, 0.0, 1.0);
+ blend_weight = blend_t * blend_t * (3.0 - 2.0 * blend_t);
+ }
+ profile.energy = profile.energy * blend_weight;
+ }
+ return profile;
+}
+
+fn ltr_area_light_profile(light: LightRecord, emitter: LightTreeEmitter, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> LtrProfile {
+ let centroid = light.position;
+ var profile = ltr_invisible_profile();
+ var min_distance = 0.0;
+ profile.point_to_centroid = ltr_normalize_with_length(centroid - position, &min_distance);
+ profile.min_distance = min_distance;
+ profile.max_distance = min_distance;
+ profile.cos_theta_u = LTR_LARGE_COSINE;
+ profile.cone_axis = light.direction;
+ profile.theta_o = emitter.theta_o;
+ profile.theta_e = emitter.theta_e;
+ profile.energy = emitter.energy;
+ let extent_u = light.axis_u * light.size_u;
+ let extent_v = light.axis_v * light.size_v;
+ for (var corner_index = 0u; corner_index < 4u; corner_index += 1u) {
+ let sign_u = select(-0.5, 0.5, (corner_index & 1u) != 0u);
+ let sign_v = select(-0.5, 0.5, (corner_index & 2u) != 0u);
+ let corner = centroid + extent_u * sign_u + extent_v * sign_v;
+ var corner_distance = 0.0;
+ let point_to_corner = ltr_normalize_with_length(corner - position, &corner_distance);
+ profile.cos_theta_u = min(profile.cos_theta_u, dot(profile.point_to_centroid, point_to_corner));
+ profile.max_distance = max(profile.max_distance, corner_distance);
+ }
+ let front_facing = dot(light.direction, profile.point_to_centroid) < 0.0;
+ let shape_above_surface = dot(normal, centroid - position) + abs(dot(normal, extent_u)) + abs(dot(normal, extent_v)) > 0.0;
+ profile.visible = (front_facing && shape_above_surface) || has_transmission;
+ return profile;
+}
+
+fn ltr_sun_light_profile(light: LightRecord, emitter: LightTreeEmitter) -> LtrProfile {
+ var profile = ltr_invisible_profile();
+ profile.point_to_centroid = -light.direction;
+ profile.cos_theta_u = cos(emitter.theta_e);
+ profile.cone_axis = light.direction;
+ profile.theta_o = emitter.theta_o;
+ profile.theta_e = emitter.theta_e;
+ profile.energy = emitter.energy;
+ profile.visible = true;
+ return profile;
+}
+
+fn ltr_emitter_profile(emitter_slot: u32, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> LtrProfile {
+ let emitter = light_tree_emitters[emitter_slot];
+ if ((emitter.kind_and_depth & LTR_EMITTER_KIND_TRIANGLE) != 0u) {
+ return ltr_triangle_profile(emitter, position, normal, has_transmission);
+ }
+ let light = lights[emitter.record_index];
+ if (light.light_type == LIGHT_TYPE_POINT || light.light_type == LIGHT_TYPE_SPOT) {
+ return ltr_sphere_light_profile(light, emitter, position);
+ }
+ if (light.light_type == LIGHT_TYPE_AREA_RECT || light.light_type == LIGHT_TYPE_AREA_DISK) {
+ return ltr_area_light_profile(light, emitter, position, normal, has_transmission);
+ }
+ if (light.light_type == LIGHT_TYPE_SUN) {
+ return ltr_sun_light_profile(light, emitter);
+ }
+ return ltr_invisible_profile();
+}
+
+fn ltr_emitter_importance(emitter_slot: u32, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> vec2<f32> {
+ return ltr_profile_importance(ltr_emitter_profile(emitter_slot, position, normal, has_transmission), normal, has_transmission);
+}
+
+// A leaf with one emitter is scored by that emitter, any other node by its box, cone and energy.
+fn ltr_child_importance(child_index: u32, position: vec3<f32>, normal: vec3<f32>, has_transmission: bool) -> vec2<f32> {
+ let child = light_tree_nodes[child_index];
+ let emitter_count = child.emitter_count_and_kind & LTR_NODE_EMITTER_COUNT_MASK;
+ let is_leaf = child.left_child < 0;
+ if (is_leaf && emitter_count == 0u) {
+ return vec2<f32>(0.0);
+ }
+ var profile: LtrProfile;
+ if (is_leaf && emitter_count == 1u) {
+ profile = ltr_emitter_profile(child.right_or_first_emitter, position, normal, has_transmission);
+ } else {
+ profile = ltr_node_profile(child_index, position, normal, has_transmission);
+ }
+ return ltr_profile_importance(profile, normal, has_transmission);
+}
+
+// False when neither child can contribute. Otherwise the probability of going left, averaged over both bounds.
+fn ltr_left_probability(
+ left_index: u32,
+ right_index: u32,
+ position: vec3<f32>,
+ normal: vec3<f32>,
+ has_transmission: bool,
+ left_probability_out: ptr<function, f32>,
+) -> bool {
+ let left = ltr_child_importance(left_index, position, normal, has_transmission);
+ let right = ltr_child_importance(right_index, position, normal, has_transmission);
+ let total_maximum = left.x + right.x;
+ if (!(total_maximum > 0.0)) {
+ return false;
+ }
+ let total_minimum = left.y + right.y;
+ let probability_maximum = left.x / total_maximum;
+ var probability_minimum = 0.5 * (select(0.0, 1.0, left.x > 0.0) + select(0.0, 1.0, right.x == 0.0));
+ if (total_minimum > 0.0) {
+ probability_minimum = left.y / total_minimum;
+ }
+ *left_probability_out = 0.5 * (probability_maximum + probability_minimum);
+ return true;
+}
+
+// Cycles `sample_reservoir`: keeps the candidate with probability proportional to its weight and rescales the random number.
+fn ltr_sample_reservoir(
+ current_slot: i32,
+ current_weight: f32,
+ selected_slot: ptr<function, i32>,
+ selected_weight: ptr<function, f32>,
+ total_weight: ptr<function, f32>,
+ random_number: ptr<function, f32>,
+) {
+ if (!(current_weight > 0.0)) {
+ return;
+ }
+ *total_weight += current_weight;
+ if (*selected_slot == -1) {
+ *selected_slot = current_slot;
+ *selected_weight = current_weight;
+ return;
+ }
+ let threshold = current_weight / *total_weight;
+ if (*random_number <= threshold) {
+ *selected_slot = current_slot;
+ *selected_weight = current_weight;
+ *random_number = *random_number / threshold;
+ } else {
+ *random_number = (*random_number - threshold) / (1.0 - threshold);
+ }
+ *random_number = clamp(*random_number, 0.0, 1.0);
+}
+
+// Picks one emitter of a leaf. Half of the random numbers sample by maximum importance, half by minimum importance.
+fn ltr_select_in_leaf(
+ leaf_index: u32,
+ position: vec3<f32>,
+ normal: vec3<f32>,
+ has_transmission: bool,
+ random_number: ptr<function, f32>,
+ pdf_factor: ptr<function, f32>,
+) -> i32 {
+ let leaf = light_tree_nodes[leaf_index];
+ let emitter_count = min(leaf.emitter_count_and_kind & LTR_NODE_EMITTER_COUNT_MASK, LTR_MAX_LEAF_EMITTERS);
+ let first_slot = leaf.right_or_first_emitter;
+
+ let sample_maximum = *random_number > 0.5;
+ if (emitter_count > 1u) {
+ *random_number = *random_number * 2.0 - select(0.0, 1.0, sample_maximum);
+ }
+
+ var selected_slot = -1;
+ var reservoir_selected = 0.0;
+ var reservoir_total = 0.0;
+ var other_selected = 0.0;
+ var other_total = 0.0;
+ var has_importance = 0u;
+ for (var emitter_index = 0u; emitter_index < emitter_count; emitter_index += 1u) {
+ let slot = first_slot + emitter_index;
+ let importance = ltr_emitter_importance(slot, position, normal, has_transmission);
+ let reservoir_weight = select(importance.y, importance.x, sample_maximum);
+ let other_weight = select(importance.x, importance.y, sample_maximum);
+ ltr_sample_reservoir(i32(slot), reservoir_weight, &selected_slot, &reservoir_selected, &reservoir_total, random_number);
+ if (selected_slot == i32(slot)) {
+ other_selected = other_weight;
+ }
+ other_total += other_weight;
+ if (importance.x > 0.0) {
+ has_importance = has_importance | (1u << emitter_index);
+ }
+ }
+ if (has_importance == 0u) {
+ return -1;
+ }
+
+ if (sample_maximum && other_total == 0.0) {
+ other_selected = 1.0;
+ other_total = f32(countOneBits(has_importance));
+ } else if (!sample_maximum && reservoir_total == 0.0) {
+ selected_slot = -1;
+ for (var emitter_index = 0u; emitter_index < emitter_count; emitter_index += 1u) {
+ let uniform_weight = select(0.0, 1.0, ((has_importance >> emitter_index) & 1u) != 0u);
+ ltr_sample_reservoir(i32(first_slot + emitter_index), uniform_weight, &selected_slot, &reservoir_selected, &reservoir_total, random_number);
+ }
+ other_selected = ltr_emitter_importance(u32(selected_slot), position, normal, has_transmission).x;
+ }
+
+ *pdf_factor *= 0.5 * (reservoir_selected / reservoir_total + other_selected / other_total);
+ return selected_slot;
+}
+
+// Picks an emitter for the shading point and writes the probability of that pick. Returns the emitter slot, or -1 when no
+// emitter can contribute. `random_number` is in [0, 1).
+fn ltr_sample(position: vec3<f32>, normal: vec3<f32>, has_transmission: bool, random_number: f32, pick_probability_out: ptr<function, f32>) -> i32 {
+ // A path from the root cannot be longer than the node count; a runtime bound keeps the driver from unrolling the walk.
+ let max_level = min(kernel_params.light_tree_node_count, LTR_MAX_TREE_DEPTH + 2u);
+ var remaining_random = random_number;
+ var pick_probability = 1.0;
+ var node_index = 0u;
+ for (var level = 0u; level < max_level; level += 1u) {
+ let node = light_tree_nodes[node_index];
+ if (node.left_child < 0) {
+ let slot = ltr_select_in_leaf(node_index, position, normal, has_transmission, &remaining_random, &pick_probability);
+ *pick_probability_out = pick_probability;
+ return slot;
+ }
+
+ let left_index = u32(node.left_child);
+ let right_index = node.right_or_first_emitter;
+ var left_probability = 0.0;
+ if (!ltr_left_probability(left_index, right_index, position, normal, has_transmission, &left_probability)) {
+ return -1;
+ }
+ let right_probability = 1.0 - left_probability;
+ var goes_right = false;
+ if (right_probability > 0.0) {
+ let threshold = right_probability / (left_probability + right_probability);
+ if (remaining_random <= threshold) {
+ goes_right = true;
+ remaining_random = remaining_random / threshold;
+ } else {
+ remaining_random = (remaining_random - threshold) / (1.0 - threshold);
+ }
+ remaining_random = clamp(remaining_random, 0.0, 1.0);
+ }
+ pick_probability *= select(left_probability, right_probability, goes_right);
+ node_index = select(left_index, right_index, goes_right);
+ }
+ return -1;
+}
+
+// Probability that `ltr_sample` picks the emitter with this unified index from this shading point.
+fn ltr_pdf(position: vec3<f32>, normal: vec3<f32>, has_transmission: bool, unified_index: u32) -> f32 {
+ if (kernel_params.light_tree_node_count == 0u) {
+ return 0.0;
+ }
+ let max_level = min(kernel_params.light_tree_node_count, LTR_MAX_TREE_DEPTH + 2u);
+ let target_slot = light_to_tree[unified_index];
+ let target_emitter = light_tree_emitters[target_slot];
+ var pdf = 1.0;
+ var node_index = 0u;
+ for (var level = 0u; level < max_level; level += 1u) {
+ let node = light_tree_nodes[node_index];
+ if (node.left_child < 0) {
+ let emitter_count = min(node.emitter_count_and_kind & LTR_NODE_EMITTER_COUNT_MASK, LTR_MAX_LEAF_EMITTERS);
+ var target_importance = vec2<f32>(0.0);
+ var total_importance = vec2<f32>(0.0);
+ var emitters_with_importance = 0u;
+ for (var emitter_index = 0u; emitter_index < emitter_count; emitter_index += 1u) {
+ let slot = node.right_or_first_emitter + emitter_index;
+ let importance = ltr_emitter_importance(slot, position, normal, has_transmission);
+ if (importance.x > 0.0) {
+ emitters_with_importance += 1u;
+ }
+ if (slot == target_slot) {
+ target_importance = importance;
+ }
+ total_importance += importance;
+ }
+ if (!(target_importance.x > 0.0)) {
+ return 0.0;
+ }
+ var minimum_term = 1.0 / f32(emitters_with_importance);
+ if (total_importance.y > 0.0) {
+ minimum_term = target_importance.y / total_importance.y;
+ }
+ return pdf * 0.5 * (target_importance.x / total_importance.x + minimum_term);
+ }
+
+ let left_index = u32(node.left_child);
+ let right_index = node.right_or_first_emitter;
+ var left_probability = 0.0;
+ if (!ltr_left_probability(left_index, right_index, position, normal, has_transmission, &left_probability)) {
+ return 0.0;
+ }
+ let trail_word = select(target_emitter.bit_trail_low, target_emitter.bit_trail_high, level >= 32u);
+ let goes_right = ((trail_word >> (level & 31u)) & 1u) != 0u;
+ pdf *= select(left_probability, 1.0 - left_probability, goes_right);
+ if (pdf == 0.0) {
+ return 0.0;
+ }
+ node_index = select(left_index, right_index, goes_right);
+ }
+ return 0.0;
+}
+
+// ---- Test probe (`KERNEL_FLAG_LIGHT_TREE_PROBE`) ------------------------------------------------------------------------------
+// One pseudo random shading point per pixel, inside the root box grown by a quarter on every side, with a random normal and a
+// transmission flag that alternates with the pixel index. Writes (sum of `ltr_pdf` over every emitter, fraction of
+// `samples_per_dispatch` stratified `ltr_sample` picks that found an emitter, largest gap between the probability `ltr_sample`
+// returned and `ltr_pdf` of the emitter it picked, number of emitters with a positive pick probability). The host divides the
+// film by the sample count, so a test passes `samples == samples_per_dispatch` and multiplies the result back.
+
+@compute @workgroup_size(8, 8, 1)
+fn light_tree_probe(@builtin(global_invocation_id) global_id: vec3<u32>) {
+ if (global_id.x >= kernel_params.image_width || global_id.y >= kernel_params.image_height) {
+ return;
+ }
+ let pixel_index = global_id.y * kernel_params.image_width + global_id.x;
+ film_accumulation[pixel_index] = ltr_probe_pick_probabilities(pixel_index);
+}
+
+fn ltr_probe_random(pixel_index: u32, stream: u32) -> f32 {
+ return f32(smp_hash_uint(pixel_index * 8u + stream) >> 8u) / 16777216.0;
+}
+
+fn ltr_probe_pick_probabilities(pixel_index: u32) -> vec4<f32> {
+ let root = light_tree_nodes[0];
+ var box_min = root.bounds_min;
+ var box_max = root.bounds_max;
+ if (all(box_max <= box_min)) {
+ box_min = vec3<f32>(-1.0);
+ box_max = vec3<f32>(1.0);
+ }
+ let margin = 0.25 * (box_max - box_min);
+ let corner_min = box_min - margin;
+ let corner_max = box_max + margin;
+ let position = corner_min + (corner_max - corner_min) * vec3<f32>(
+ ltr_probe_random(pixel_index, 0u),
+ ltr_probe_random(pixel_index, 1u),
+ ltr_probe_random(pixel_index, 2u),
+ );
+ let normal = lgt_sample_uniform_sphere(vec2<f32>(ltr_probe_random(pixel_index, 3u), ltr_probe_random(pixel_index, 4u)));
+ let has_transmission = (pixel_index & 1u) != 0u;
+
+ let emitter_total = kernel_params.light_count + kernel_params.emissive_triangle_count;
+ var probability_sum = 0.0;
+ var reachable_emitters = 0.0;
+ for (var unified_index = 0u; unified_index < emitter_total; unified_index += 1u) {
+ let probability = ltr_pdf(position, normal, has_transmission, unified_index);
+ probability_sum += probability;
+ if (probability > 0.0) {
+ reachable_emitters += 1.0;
+ }
+ }
+
+ var found_picks = 0.0;
+ var largest_gap = 0.0;
+ let pick_count = max(kernel_params.samples_per_dispatch, 1u);
+ for (var pick_index = 0u; pick_index < pick_count; pick_index += 1u) {
+ let random_number = (f32(pick_index) + 0.5) / f32(pick_count);
+ var pick_probability = 0.0;
+ let slot = ltr_sample(position, normal, has_transmission, random_number, &pick_probability);
+ if (slot >= 0) {
+ found_picks += 1.0;
+ let emitter = light_tree_emitters[u32(slot)];
+ var unified_index = emitter.record_index;
+ if ((emitter.kind_and_depth & LTR_EMITTER_KIND_TRIANGLE) != 0u) {
+ unified_index += kernel_params.light_count;
+ }
+ largest_gap = max(largest_gap, abs(pick_probability - ltr_pdf(position, normal, has_transmission, unified_index)));
+ }
+ }
+ return vec4<f32>(probability_sum, found_picks / f32(pick_count), largest_gap, reachable_emitters);
+}
diff --git a/packages/render-native/src/cycles/lights.wgsl b/packages/render-native/src/cycles/lights.wgsl
index f47d1708..79d6e785 100644
--- a/packages/render-native/src/cycles/lights.wgsl
+++ b/packages/render-native/src/cycles/lights.wgsl
@@ -30,6 +30,33 @@ fn lgt_empty_sample() -> LgtDirectSample {
return sample;
}
+// Shading point of the last surface bounce, kept for the MIS weight of the next hit. `lgt_mis_picked_by_tree` is false after a
+// volume scatter, whose direct light is picked from the flat analytic table.
+var<private> lgt_mis_picked_by_tree: bool = false;
+var<private> lgt_mis_position: vec3<f32> = vec3<f32>(0.0);
+var<private> lgt_mis_normal: vec3<f32> = vec3<f32>(0.0, 0.0, 1.0);
+var<private> lgt_mis_has_transmission: bool = false;
+
+fn lgt_use_light_tree() -> bool {
+ return SCENE_HAS_LIGHT_TREE && (kernel_params.kernel_flags & KERNEL_FLAG_USE_LIGHT_TREE) != 0u;
+}
+
+fn lgt_remember_mis_origin(position: vec3<f32>, normal: vec3<f32>, has_transmission: bool, picked_by_tree: bool) {
+ lgt_mis_position = position;
+ lgt_mis_normal = normal;
+ lgt_mis_has_transmission = has_transmission;
+ lgt_mis_picked_by_tree = picked_by_tree;
+}
+
+// Probability that the direct light pick chose this emitter from the last shading point. `flat_probability` is the
+// per-table probability used when the pick did not go through the tree.
+fn lgt_selection_probability(unified_index: u32, flat_probability: f32) -> f32 {
+ if (lgt_use_light_tree() && lgt_mis_picked_by_tree) {
+ return ltr_pdf(lgt_mis_position, lgt_mis_normal, lgt_mis_has_transmission, unified_index);
+ }
+ return flat_probability;
+}
+
fn lgt_power_heuristic(pdf_a: f32, pdf_b: f32) -> f32 {
if (pdf_a <= 0.0) {
return 0.0;
@@ -525,7 +552,19 @@ fn lgt_sample_analytic_light(
return lgt_empty_sample();
}
let light_index = lgt_binary_search_light_cdf(pick_u, count);
- let light = lights[light_index];
+ return lgt_sample_analytic_light_at(light_index, lights[light_index].selection_pdf, shading_pos, receiver_lo, receiver_hi, sample_uv);
+}
+
+fn lgt_sample_analytic_light_at(
+ light_index: u32,
+ selection_pdf: f32,
+ shading_pos: vec3<f32>,
+ receiver_lo: u32,
+ receiver_hi: u32,
+ sample_uv: vec2<f32>,
+) -> LgtDirectSample {
+ var light = lights[light_index];
+ light.selection_pdf = selection_pdf;
if (light.selection_pdf <= 0.0) {
return lgt_empty_sample();
}
@@ -551,8 +590,13 @@ fn lgt_sample_emissive_triangle(point: ptr<function, ShadingPoint>, pick_u: f32,
return out;
}
let index = lgt_binary_search_emissive_cdf(pick_u, count);
+ return lgt_sample_emissive_triangle_at(point, index, emissive_triangles[index].selection_pdf, sample_uv);
+}
+
+fn lgt_sample_emissive_triangle_at(point: ptr<function, ShadingPoint>, index: u32, selection_pdf: f32, sample_uv: vec2<f32>) -> LgtDirectSample {
+ var out = lgt_empty_sample();
let emitter = emissive_triangles[index];
- if (emitter.selection_pdf <= 0.0 || emitter.area <= 0.0) {
+ if (selection_pdf <= 0.0 || emitter.area <= 0.0) {
return out;
}
if (!lgt_links_match((*point).light_group_mask_lo, (*point).light_group_mask_hi, emitter.light_group_mask_lo, emitter.light_group_mask_hi)) {
@@ -587,13 +631,40 @@ fn lgt_sample_emissive_triangle(point: ptr<function, ShadingPoint>, pick_u: f32,
out.wi = wi;
out.distance = dist;
out.radiance = emitter.radiance;
- out.pdf = emitter.selection_pdf * pdf_solid_angle;
+ out.pdf = selection_pdf * pdf_solid_angle;
out.target_instance = emitter.instance_index;
out.target_triangle = emitter.triangle_index;
out.cast_shadow = 1u;
return out;
}
+// Picks one emitter (analytic light or emissive triangle) through the light tree and samples a point on it.
+fn lgt_sample_tree_emitter(
+ point: ptr<function, ShadingPoint>,
+ normal: vec3<f32>,
+ has_transmission: bool,
+ pick_u: f32,
+ sample_uv: vec2<f32>,
+) -> LgtDirectSample {
+ var pick_probability = 0.0;
+ let slot = ltr_sample((*point).position, normal, has_transmission, pick_u, &pick_probability);
+ if (slot < 0 || pick_probability <= 0.0) {
+ return lgt_empty_sample();
+ }
+ let emitter = light_tree_emitters[u32(slot)];
+ if ((emitter.kind_and_depth & LTR_EMITTER_KIND_TRIANGLE) != 0u) {
+ return lgt_sample_emissive_triangle_at(point, emitter.record_index, pick_probability, sample_uv);
+ }
+ return lgt_sample_analytic_light_at(
+ emitter.record_index,
+ pick_probability,
+ (*point).position,
+ (*point).light_group_mask_lo,
+ (*point).light_group_mask_hi,
+ sample_uv,
+ );
+}
+
fn lgt_direction_to_env_uv(direction: vec3<f32>, polar_out: ptr<function, f32>) -> vec2<f32> {
let cosine = cos(kernel_params.env_rotation);
let sine = sin(kernel_params.env_rotation);
@@ -789,8 +860,11 @@ fn lgt_eval_analytic_lights_along_segment(
let one_minus_cos = min(one_minus_cos_sphere, one_minus_cos_spot);
pdf_solid_angle = 1.0 / max(TWO_PI * one_minus_cos, 1.0e-30);
}
- let pdf_nee = light.selection_pdf * pdf_solid_angle;
- let mis_weight = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);
+ var mis_weight = 1.0;
+ if (!(is_camera_ray || mis_skip)) {
+ let pdf_nee = lgt_selection_probability(index, light.selection_pdf) * pdf_solid_angle;
+ mis_weight = lgt_power_heuristic(prev_bsdf_pdf, pdf_nee);
+ }
let medium_atten = select(vec3<f32>(1.0), exp(-medium_sigma * max(hit_t - t_min, 0.0)), in_medium);
total += light.radiance * medium_atten * (spot_weight * falloff * mis_weight);
continue;
@@ -850,8 +924,11 @@ fn lgt_eval_analytic_lights_along_segment(
continue;
}
}
- let pdf_nee = light.selection_pdf * pdf_solid_angle;
- let mis_weight = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);
+ var mis_weight = 1.0;
+ if (!(is_camera_ray || mis_skip)) {
+ let pdf_nee = lgt_selection_probability(index, light.selection_pdf) * pdf_solid_angle;
+ mis_weight = lgt_power_heuristic(prev_bsdf_pdf, pdf_nee);
+ }
let medium_atten = select(vec3<f32>(1.0), exp(-medium_sigma * max(hit_t - t_min, 0.0)), in_medium);
total += light.radiance * medium_atten * (spread_weight * falloff * mis_weight);
}
@@ -907,8 +984,11 @@ fn lgt_eval_escaped_ray(
if (dot(ray_dir, to_sun) < 1.0 - one_minus_cos) {
continue;
}
- let pdf_nee = light.selection_pdf / max(TWO_PI * one_minus_cos, 1.0e-30);
- let sun_mis = select(lgt_power_heuristic(prev_bsdf_pdf, pdf_nee), 1.0, is_camera_ray || mis_skip);
+ var sun_mis = 1.0;
+ if (!(is_camera_ray || mis_skip)) {
+ let pdf_nee = lgt_selection_probability(index, light.selection_pdf) / max(TWO_PI * one_minus_cos, 1.0e-30);
+ sun_mis = lgt_power_heuristic(prev_bsdf_pdf, pdf_nee);
+ }
total += light.radiance * sun_mis;
}
@@ -934,7 +1014,17 @@ fn lgt_emissive_surface_weight(
return 0.0;
}
}
- if (is_camera_ray || mis_skip || emitter.selection_pdf <= 0.0 || emitter.area <= 0.0) {
+ if (is_camera_ray || mis_skip || emitter.area <= 0.0) {
+ return 1.0;
+ }
+ if ((kernel_params.kernel_flags & KERNEL_FLAG_TEST_NEE_ONLY) != 0u) {
+ return 0.0;
+ }
+ if ((kernel_params.kernel_flags & KERNEL_FLAG_TEST_BSDF_ONLY) != 0u) {
+ return 1.0;
+ }
+ let selection_probability = lgt_selection_probability(kernel_params.light_count + emissive_index, emitter.selection_pdf);
+ if (selection_probability <= 0.0) {
return 1.0;
}
let mat = materials[emitter.material_index];
@@ -945,6 +1035,6 @@ fn lgt_emissive_surface_weight(
if (cos_light <= 1.0e-8) {
return 0.0;
}
- let pdf_nee = emitter.selection_pdf * (hit_distance * hit_distance) / max(emitter.area * cos_light, 1.0e-20);
+ let pdf_nee = selection_probability * (hit_distance * hit_distance) / max(emitter.area * cos_light, 1.0e-20);
return lgt_power_heuristic(prev_bsdf_pdf, pdf_nee);
}
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 77a44928..444f2920 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -15,6 +15,7 @@ const BOOTSTRAP_MAIN_SOURCE: &str = include_str!("bootstrap_main.wgsl");
include!(concat!(env!("OUT_DIR"), "/cycles_manifest_files.rs"));
// ---- KernelParamsV2 byte offsets (verified against pack-input-v2.mjs and abi.wgsl) ----
+const KERNEL_FLAG_LIGHT_TREE_PROBE: u32 = 128;
const KP_KERNEL_FLAGS_BYTE: usize = 32; // u32[8]
const KP_ENV_WIDTH_BYTE: usize = 192; // u32[48]
const KP_ENV_HEIGHT_BYTE: usize = 196; // u32[49]
@@ -163,6 +164,16 @@ pub(crate) fn check_counts_match_kernel_params(input: &NativeTraceInputV2) -> Re
Ok(())
}
+/// The compute entry point to run: `main`, or `light_tree_probe` when the input carries `KERNEL_FLAG_LIGHT_TREE_PROBE` (tests).
+pub(crate) fn trace_entry_point(input: &NativeTraceInputV2) -> &'static str {
+ let kernel_flags = read_u32_le(&input.kernel_params, KP_KERNEL_FLAGS_BYTE);
+ if (kernel_flags & KERNEL_FLAG_LIGHT_TREE_PROBE) != 0 {
+ "light_tree_probe"
+ } else {
+ "main"
+ }
+}
+
/// Specializes the assembled Cycles kernel source for the given scene input, replacing
/// `const SCENE_HAS_*: bool = true;` sentinel declarations with the actual scene-derived values.
/// The sentinel pattern is `true` (conservative default) so the kernel compiles and renders
@@ -185,6 +196,7 @@ pub(crate) fn specialize_cycles_kernel(source: &str, input: &NativeTraceInputV2)
let has_volume = (kernel_flags & 2) != 0 && volume_density > 0.0;
let has_env_importance = env_width > 0 && env_height > 0 && env_total_weight > 0.0;
+ let has_light_tree = (kernel_flags & 1) != 0 && input.light_tree_node_count > 0;
let has_emissive_triangles = input.emissive_triangle_count > 0;
let has_analytic_lights = input.light_count > 0;
@@ -357,6 +369,7 @@ pub(crate) fn specialize_cycles_kernel(source: &str, input: &NativeTraceInputV2)
specialize!(FINITE_LIGHTS, has_finite_lights);
specialize!(ENV_IMPORTANCE, has_env_importance);
specialize!(LIGHT_LINKING, has_light_linking);
+ specialize!(LIGHT_TREE, has_light_tree);
if max_closure_lobes < 4 {
result = result.replace(
"const MAX_CLOSURE_LOBES: u32 = 4u; // SPECIALIZE_LOBES",
@@ -478,6 +491,7 @@ mod specialization_tests {
const SCENE_HAS_FINITE_LIGHTS: bool = true;\n\
const SCENE_HAS_ENV_IMPORTANCE: bool = true;\n\
const SCENE_HAS_LIGHT_LINKING: bool = true;\n\
+ const SCENE_HAS_LIGHT_TREE: bool = true;\n\
const MAX_CLOSURE_LOBES: u32 = 4u; // SPECIALIZE_LOBES
const MAX_CLOSURE_CANDIDATES: u32 = 7u; // SPECIALIZE_CANDIDATES";
let result = specialize_cycles_kernel(source, &input);
@@ -496,6 +510,7 @@ mod specialization_tests {
assert!(result.contains("const SCENE_HAS_FINITE_LIGHTS: bool = false;"), "FINITE_LIGHTS should be false");
assert!(result.contains("const SCENE_HAS_ENV_IMPORTANCE: bool = false;"), "ENV_IMPORTANCE should be false");
assert!(result.contains("const SCENE_HAS_LIGHT_LINKING: bool = false;"), "LIGHT_LINKING should be false");
+ assert!(result.contains("const SCENE_HAS_LIGHT_TREE: bool = false;"), "LIGHT_TREE should be false");
assert!(result.contains("const MAX_CLOSURE_LOBES: u32 = 2u; // SPECIALIZE_LOBES"), "MAX_CLOSURE_LOBES should be 2u");
assert!(
result.contains("const MAX_CLOSURE_CANDIDATES: u32 = 2u; // SPECIALIZE_CANDIDATES"),
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index 8dc30cdd..eabfa61a 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -8,7 +8,7 @@ use std::time::Instant;
use napi::Result;
use wgpu::util::DeviceExt;
-use crate::cycles::{check_counts_match_kernel_params, specialize_cycles_kernel, unit_filter_table_words, CYCLES_LUT_WORDS};
+use crate::cycles::{check_counts_match_kernel_params, specialize_cycles_kernel, trace_entry_point, unit_filter_table_words, CYCLES_LUT_WORDS};
use crate::host::accel::{
build_acceleration_structure, build_cycles_acceleration_structure, build_empty_cycles_acceleration,
create_vertex_buffer, unpack_triangles, CyclesAcceleration, INSTANCE_RECORD_BYTES, TRIANGLE_FLOATS,
@@ -650,7 +650,7 @@ pub(crate) fn prepare_cycles_scene(
// Specialise the kernel source for this scene (replaces SCENE_HAS_* sentinels).
check_counts_match_kernel_params(input)?;
let specialized_source = specialize_cycles_kernel(&shader_source, input);
- let pipeline = get_or_compile_cycles_pipeline("main", specialized_source)?;
+ let pipeline = get_or_compile_cycles_pipeline(trace_entry_point(input), specialized_source)?;
let compile_seconds = compile_started.elapsed().as_secs_f64();
let upload_started = Instant::now();
diff --git a/tests/native-light-tree-kernel.test.js b/tests/native-light-tree-kernel.test.js
new file mode 100644
index 00000000..82123ee1
--- /dev/null
+++ b/tests/native-light-tree-kernel.test.js
@@ -0,0 +1,141 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ buildNativeInputV2,
+ findNativeAddon,
+ traceNative,
+} from '../packages/render-native/index.mjs';
+import {
+ KERNEL_FLAG_USE_LIGHT_TREE,
+ LIGHT_TREE_AUTO_MIN_EMITTERS,
+ resolveUseLightTree,
+ validatePackOptions,
+} from '../packages/render-native/pack-input-v2.mjs';
+import { createCamera } from '../src/path-tracer.js';
+
+const hasAddon = findNativeAddon() !== null;
+const skipWithoutAddon = hasAddon ? false : 'the native addon is not built';
+
+const UNIT_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]),
+};
+
+// A quad scaled by `scale`, turned to face up (floor) or down (ceiling) and moved to `height`.
+function horizontalQuadMatrix(scale, height, facesUp) {
+ const upOrDown = facesUp ? 1 : -1;
+ return [scale, 0, 0, 0, 0, 0, -upOrDown * scale, 0, 0, upOrDown * scale, 0, 0, 0, height, 0, 1];
+}
+
+function buildRoomScene(extraLights) {
+ return {
+ materials: [{ color: [0.6, 0.6, 0.6], roughness: 0.8 }, { color: [1, 0.95, 0.9], emission: 5, roughness: 1 }],
+ instances: [
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(8, 0, true), materialIndex: 0 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(2, 3, false), materialOverride: 1 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(1, 2, false), materialOverride: 1 },
+ ],
+ lights: extraLights,
+ };
+}
+
+function trace(scene, options) {
+ const width = options.width;
+ const height = options.height;
+ const camera = createCamera({ eye: [0, 2.2, 6], target: [0, 0.5, 0], fov: 45 }, width, height);
+ const input = buildNativeInputV2(scene, camera, { ...options, samples: options.samples });
+ return traceNative(input, { ...options, kernel: 'cycles' });
+}
+
+function meanRgb(rgba) {
+ const sum = [0, 0, 0];
+ const pixelCount = rgba.length / 4;
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
+ for (let channel = 0; channel < 3; channel++) {
+ sum[channel] += rgba[pixel * 4 + channel];
+ }
+ }
+ return sum.map((value) => value / pixelCount);
+}
+
+test('lightSampling "auto" turns the tree on from two emitters, "tree" from one, "uniform" never', () => {
+ assert.equal(LIGHT_TREE_AUTO_MIN_EMITTERS, 1);
+ assert.equal(resolveUseLightTree('auto', 1, 1), false);
+ assert.equal(resolveUseLightTree(undefined, 2, 3), true);
+ assert.equal(resolveUseLightTree('tree', 1, 1), true);
+ assert.equal(resolveUseLightTree('tree', 0, 0), false);
+ assert.equal(resolveUseLightTree('uniform', 50, 99), false);
+ assert.equal(KERNEL_FLAG_USE_LIGHT_TREE, 1);
+});
+
+test('traceNative rejects an unknown lightSampling before it reaches the GPU', () => {
+ assert.throws(
+ () => validatePackOptions({ lightSampling: 'bvh' }, 'test'),
+ /`lightSampling` must be "auto" \(default\), "tree" or "uniform", got "bvh"/
+ );
+ assert.doesNotThrow(() => validatePackOptions({ lightSampling: 'tree' }, 'test'));
+});
+
+test('pick probabilities from random shading points sum to 1 over all emitters and match what the sampler returns', { skip: skipWithoutAddon }, () => {
+ const scene = buildRoomScene({
+ points: [
+ { position: [2, 1.5, 1], intensity: 10, radius: 0.1 },
+ { position: [-2.5, 0.8, -1], intensity: 4, radius: 0.05 },
+ ],
+ sun: { color: [1, 1, 1], direction: [0.3, -1, 0.2] },
+ });
+ const samples = 64;
+ const probe = trace(scene, {
+ width: 100,
+ height: 16,
+ samples,
+ samplesPerDispatch: samples,
+ lightSampling: 'tree',
+ lightTreeProbe: true,
+ });
+ const pointCount = 100 * 16;
+ let pointsWithSumOne = 0;
+ let transmissivePointsWithSumOne = 0;
+ for (let point = 0; point < pointCount; point++) {
+ const probabilitySum = probe.rgba[point * 4];
+ const foundFraction = probe.rgba[point * 4 + 1];
+ const pickGap = probe.rgba[point * 4 + 2];
+ assert.ok(probabilitySum <= 1 + 1e-4, `point ${point}: probabilities add up to ${probabilitySum}`);
+ assert.ok(pickGap < 1e-4, `point ${point}: sampler and pdf differ by ${pickGap}`);
+ assert.ok(Math.abs(foundFraction - probabilitySum) < 0.05, `point ${point}: ${foundFraction} of the picks found an emitter, pdf sum ${probabilitySum}`);
+ if (Math.abs(probabilitySum - 1) < 1e-4) {
+ pointsWithSumOne += 1;
+ if (point % 2 === 1) {
+ transmissivePointsWithSumOne += 1;
+ }
+ }
+ }
+ assert.equal(transmissivePointsWithSumOne, pointCount / 2, 'every point that sees through the surface sums to 1');
+ assert.ok(pointsWithSumOne > pointCount * 0.8, `${pointsWithSumOne} of ${pointCount} points sum to 1`);
+});
+
+test('a large emissive quad renders the same mean with NEE only, BSDF only and both', { skip: skipWithoutAddon }, () => {
+ const scene = buildRoomScene(undefined);
+ const common = { width: 48, height: 32, samples: 256, samplesPerDispatch: 32, lightSampling: 'tree', seed: 3 };
+ const both = meanRgb(trace(scene, { ...common, directLighting: 'both' }).rgba);
+ const neeOnly = meanRgb(trace(scene, { ...common, directLighting: 'nee-only' }).rgba);
+ const bsdfOnly = meanRgb(trace(scene, { ...common, directLighting: 'bsdf-only' }).rgba);
+ for (let channel = 0; channel < 3; channel++) {
+ assert.ok(both[channel] > 0.05, `channel ${channel} is lit`);
+ assert.ok(Math.abs(neeOnly[channel] / both[channel] - 1) < 0.02, `NEE only ${neeOnly[channel]} against both ${both[channel]}`);
+ assert.ok(Math.abs(bsdfOnly[channel] / both[channel] - 1) < 0.02, `BSDF only ${bsdfOnly[channel]} against both ${both[channel]}`);
+ }
+});
+
+test('the tree and the flat pick render the same mean', { skip: skipWithoutAddon }, () => {
+ const scene = buildRoomScene({ points: [{ position: [2, 1.5, 1], intensity: 10, radius: 0.1 }] });
+ const common = { width: 48, height: 32, samples: 256, samplesPerDispatch: 32, seed: 5 };
+ const tree = meanRgb(trace(scene, { ...common, lightSampling: 'tree' }).rgba);
+ const flat = meanRgb(trace(scene, { ...common, lightSampling: 'uniform' }).rgba);
+ for (let channel = 0; channel < 3; channel++) {
+ assert.ok(Math.abs(tree[channel] / flat[channel] - 1) < 0.02, `tree ${tree[channel]} against flat ${flat[channel]}`);
+ }
+});