Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Fix the review findings of the Cook light tree and pixel filter (#895)

Nguyen Xuan And5d221d88ec3
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index b2c45c36..98a0673b 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -13,7 +13,11 @@ import {
KERNEL_FLAG_WHITE_NOISE_SAMPLER,
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,
@@ -87,6 +91,9 @@ export function traceNative(input, options = {}) {
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) };
}
@@ -103,12 +110,48 @@ export function traceNative(input, options = {}) {
});
}
-function withLightSamplingFlag(v2Input, lightSampling) {
+function hasFilterOptions(options) {
+ return options.filterType !== undefined || options.pixelFilter !== undefined || options.filterWidth !== undefined;
+}
+
+// A packed input already carries its filter; explicit options replace it. A new type without a width gets that type's
+// default width, as the packer does; a width alone keeps the packed type.
+// Exported for tests; not part of the public API.
+export function withFilterOptions(kernelParams, options) {
+ const patchedParams = new Uint8Array(kernelParams);
+ const view = new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength);
+ const requestedType = options.filterType ?? options.pixelFilter;
+ const filterType = requestedType !== undefined
+ ? filterTypeCode(requestedType)
+ : view.getUint32(KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET, true);
+ const filterWidth = options.filterWidth !== undefined || requestedType !== undefined
+ ? resolveFilterParameters({ filterType, filterWidth: options.filterWidth }).filterWidth
+ : view.getFloat32(KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET, true);
+ view.setUint32(KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET, filterType, true);
+ view.setFloat32(KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET, filterWidth, true);
+ return patchedParams;
+}
+
+function hasLightTreeEmitterTables(v2Input) {
+ return Boolean(v2Input.lightTreeEmitters && v2Input.lightToTree && v2Input.lightTreeEmitterCount !== undefined);
+}
+
+// Exported for tests; not part of the public API.
+export 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);
+ let lightTreeNodeCount = v2Input.lightTreeNodeCount ?? 0;
+ if (lightTreeNodeCount > 0 && !hasLightTreeEmitterTables(v2Input)) {
+ if (lightSampling === 'tree') {
+ throw new TypeError(
+ 'traceNative: lightSampling "tree" needs the emitter tables (lightTreeEmitters, lightTreeEmitterCount, lightToTree), which this packed FORMAT-v2 input lacks. Repack the scene with buildNativeInputV2.'
+ );
+ }
+ lightTreeNodeCount = 0;
+ }
+ const useTree = resolveUseLightTree(lightSampling, emitterCount, lightTreeNodeCount);
const patchedFlags = useTree
? (flags | KERNEL_FLAG_USE_LIGHT_TREE) >>> 0
: (flags & ~KERNEL_FLAG_USE_LIGHT_TREE) >>> 0;
diff --git a/packages/render-native/light-tree-v2.mjs b/packages/render-native/light-tree-v2.mjs
index d8baff05..dae1a6b8 100644
--- a/packages/render-native/light-tree-v2.mjs
+++ b/packages/render-native/light-tree-v2.mjs
@@ -12,6 +12,8 @@ export const LIGHT_TREE_REVISION = 1;
export const LIGHT_TREE_NODE_BYTES = 64;
export const LIGHT_TREE_EMITTER_BYTES = 32;
export const LIGHT_TREE_MAX_LEAF_EMITTERS = 8;
+// The kernel reads at most this many emitters of one leaf (`LTR_MAX_LEAF_EMITTERS` in light_tree.wgsl); only the distant leaf can hold more than 8.
+export const LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS = 32;
export const LIGHT_TREE_MAX_EMITTERS = 4194304;
export const LIGHT_TREE_BUCKET_COUNT = 12;
export const LIGHT_TREE_MAX_DEPTH = 63;
@@ -273,7 +275,8 @@ function lightEmitter(view, index, unifiedIndex) {
function triangleEmitter(view, index, unifiedIndex) {
const floats = new Float32Array(view.buffer, view.byteOffset + index * EMISSIVE_TRIANGLE_BYTES, EMISSIVE_TRIANGLE_BYTES / 4);
const words = new Uint32Array(view.buffer, view.byteOffset + index * EMISSIVE_TRIANGLE_BYTES, EMISSIVE_TRIANGLE_BYTES / 4);
- assertFiniteNumbers(floats.subarray(0, 20), 'emissive triangle', index);
+ // Words 7, 11 and 15 are u32 indices; only the float fields are checked.
+ assertFiniteNumbers([...floats.subarray(0, 7), ...floats.subarray(8, 11), ...floats.subarray(12, 15), ...floats.subarray(16, 20)], 'emissive triangle', index);
const origin = [floats[0], floats[1], floats[2]];
const edgeOne = [floats[4], floats[5], floats[6]];
const edgeTwo = [floats[8], floats[9], floats[10]];
@@ -548,8 +551,11 @@ function buildDistantLeaf(state, start, end, depth, trailLow, trailHigh) {
emitter.trailHigh = trailHigh;
}
const count = end - start;
- if (count > LIGHT_TREE_NODE_COUNT_MASK) {
- throw new Error(`buildLightTree: ${count} distant lights exceed the leaf limit ${LIGHT_TREE_NODE_COUNT_MASK}.`);
+ if (count > LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS) {
+ throw new Error(
+ `buildLightTree: ${count} distant lights exceed the ${LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS} the kernel reads from one leaf. ` +
+ `Pass at most ${LIGHT_TREE_KERNEL_MAX_LEAF_EMITTERS} sun or distant lights, or merge some of them.`
+ );
}
state.nodes.push({
measure,
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index 6b28bf0b..78177de5 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -11,6 +11,9 @@ export const INVALID_INDEX_V2 = 0xffffffff;
// Used in `packKernelParamsV2` and in `index.mjs` when patching a pre-built buffer.
export const KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET = 300;
export const KERNEL_PARAMS_V2_KERNEL_FLAGS_BYTE_OFFSET = 32;
+// Byte offsets of `filter_type` (u32[19]) and `filter_width` (f32[20]); the packer and `traceNative` share them.
+export const KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET = 76;
+export const KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET = 80;
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. */
@@ -1586,7 +1589,7 @@ const FILTER_TYPE_CODES = Object.freeze({
blackman_harris: 2,
});
-function filterTypeCode(filter) {
+export function filterTypeCode(filter) {
if (filter === 0 || filter === 1 || filter === 2) {
return filter;
}
@@ -1609,7 +1612,7 @@ export function validateFilterOptions(options, callerName) {
}
}
-function resolveFilterParameters(options = {}) {
+export function resolveFilterParameters(options = {}) {
const filterType = filterTypeCode(options.filterType ?? options.pixelFilter ?? 0) ?? 0;
const defaultWidth = filterType === 0 ? 1.0 : 1.5;
const filterWidth = options.filterWidth ?? defaultWidth;
@@ -1726,9 +1729,9 @@ function packKernelParamsV2({
u32[16] = maxVolumeBounces >>> 0;
u32[17] = maxTransparentBounces >>> 0;
u32[18] = minBounceRr >>> 0;
- u32[19] = filterType >>> 0;
+ u32[KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET / 4] = filterType >>> 0;
- f32[20] = filterWidth;
+ f32[KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET / 4] = filterWidth;
u32[21] = counts.instanceCount >>> 0;
u32[22] = counts.triangleCount >>> 0;
u32[23] = counts.materialCount >>> 0;
diff --git a/packages/render-native/src/cycles/filter_table.rs b/packages/render-native/src/cycles/filter_table.rs
index 15ef2fa0..ad8540a0 100644
--- a/packages/render-native/src/cycles/filter_table.rs
+++ b/packages/render-native/src/cycles/filter_table.rs
@@ -73,7 +73,9 @@ fn invert_cdf_symmetric(resolution: usize, range: f32, cdf: &[f32]) -> Vec<f32>
/// Builds the Cycles filter table for `filter_width` (in pixels). Entry `i` is the sample position inside the
/// pixel, in pixels from its corner, for the unit random number `i / (FILTER_TABLE_SIZE - 1)`. Entry 1023 stays 0,
/// exactly as in Cycles: its even-sized symmetric table writes only entries 0..1022, so a unit random number above
-/// 1022/1023 interpolates toward 0 (about 0.1% of samples). It is kept so the kernel matches Cycles sample for sample.
+/// 1022/1023 interpolates toward 0 (about 0.1% of samples). It is kept so the Blackman-Harris and Gaussian tables match Cycles at
+/// filter width 1 (the kernel scales the sampled offset by the width, so the last interval differs at other widths). The box filter
+/// is analytic in the kernel and has no such quirk.
pub(crate) fn build_filter_table(kind: FilterKind, filter_width: f32) -> Vec<f32> {
let support_width = match kind {
FilterKind::Gaussian => filter_width * 3.0,
diff --git a/packages/render-native/src/cycles/light_tree.wgsl b/packages/render-native/src/cycles/light_tree.wgsl
index 2c8c8841..870ebf71 100644
--- a/packages/render-native/src/cycles/light_tree.wgsl
+++ b/packages/render-native/src/cycles/light_tree.wgsl
@@ -98,8 +98,9 @@ fn ltr_importance(
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));
+ // Cycles divides the maximum importance by the nearest distance and the minimum importance by the farthest one.
+ let safe_min_distance = max(min_distance, 1.0e-6);
+ let maximum_importance = abs(cos_min_incidence_angle * energy * cos_min_outgoing_angle / (safe_min_distance * safe_min_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)) {
@@ -107,8 +108,8 @@ fn ltr_importance(
}
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));
+ let safe_max_distance = max(max_distance, 1.0e-6);
+ let minimum_importance = abs(cos_max_incidence_angle * energy * cos_max_outgoing_angle / (safe_max_distance * safe_max_distance));
return vec2<f32>(maximum_importance, minimum_importance);
}
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 444f2920..3ad73030 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -416,6 +416,17 @@ mod specialization_tests {
}
}
+ #[test]
+ fn light_tree_flag_without_emitter_tables_is_rejected() {
+ let flagged = dummy_input(&make_kp(1, 0.0, 0, 0, 0.0), &[], &[], &[]);
+ let message = crate::host::session::validate_light_tree_tables(&flagged)
+ .expect_err("a flagged input without emitter tables must fail")
+ .to_string();
+ assert!(message.contains("buildNativeInputV2"), "{message}");
+ let unflagged = dummy_input(&make_kp(0, 0.0, 0, 0, 0.0), &[], &[], &[]);
+ assert!(crate::host::session::validate_light_tree_tables(&unflagged).is_ok());
+ }
+
fn make_kp(kernel_flags: u32, volume_density: f32, env_width: u32, env_height: u32, env_total_weight: f32) -> Vec<u8> {
let mut kp = vec![0u8; 320];
// magic & version at bytes 0-7
diff --git a/packages/render-native/src/cycles/sampler.wgsl b/packages/render-native/src/cycles/sampler.wgsl
index 50e736db..f937032e 100644
--- a/packages/render-native/src/cycles/sampler.wgsl
+++ b/packages/render-native/src/cycles/sampler.wgsl
@@ -5,7 +5,8 @@
// `KERNEL_FLAG_WHITE_NOISE_SAMPLER`:
// - default: Cycles 5.3 BLUE_NOISE_PURE, a translation of kernel/sample/{pattern,sobol_burley,util}.h and
// util/hash.h: one Owen-scrambled Sobol sequence (seed 0) where each pixel owns a section of
-// `total_samples` consecutive indices, found by a base-4 Owen scrambled Morton code of the pixel.
+// `total_samples` consecutive indices (modulo 2^32, as in Cycles, so sections can overlap when pixel rank times
+// `total_samples` exceeds 2^32), found by a base-4 Owen scrambled Morton code of the pixel.
// - white: a stateless PCG4D hash per draw, unstratified across samples.
// Sobol-Burley decisions are addressed by a dimension set. The path loop calls `smp_seek` before each decision so
// that a bounce that skips a light kind does not shift the sets of the others (Cycles reserves PRNG_BOUNCE_NUM = 16
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index eabfa61a..e4ed2467 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -564,19 +564,35 @@ fn validate_record_buffer(label: &str, bytes: &[u8], count: u32, stride: usize)
Ok(())
}
+/// Byte offset of `kernel_flags` in `KernelParamsV2` and its light-tree bit (`KERNEL_FLAG_USE_LIGHT_TREE` in pack-input-v2.mjs).
+const KERNEL_PARAMS_KERNEL_FLAGS_BYTE: usize = 32;
+const KERNEL_FLAG_USE_LIGHT_TREE: u32 = 1;
+
/// The emitter table and the emitter-to-slot table come together or not at all, and the slot table must cover
/// every analytic light and emissive triangle of the input.
-fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<()> {
+pub(crate) fn validate_light_tree_tables(input: &NativeTraceInputV2) -> Result<()> {
let (emitters, emitter_count, light_to_tree) = match (
&input.light_tree_emitters,
input.light_tree_emitter_count,
&input.light_to_tree,
) {
- (None, None, None) => return Ok(()),
+ (None, None, None) => {
+ let tree_flag_set = input
+ .kernel_params
+ .get(KERNEL_PARAMS_KERNEL_FLAGS_BYTE..KERNEL_PARAMS_KERNEL_FLAGS_BYTE + 4)
+ .map(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & KERNEL_FLAG_USE_LIGHT_TREE != 0)
+ .unwrap_or(false);
+ if tree_flag_set && input.light_tree_node_count > 0 {
+ return Err(failure(
+ "The light-tree kernel flag is set and the input has light tree nodes, but lightTreeEmitters, lightTreeEmitterCount and lightToTree are missing. Repack the scene with buildNativeInputV2.",
+ ));
+ }
+ return Ok(());
+ }
(Some(emitters), Some(emitter_count), Some(light_to_tree)) => (emitters, emitter_count, light_to_tree),
_ => {
return Err(failure(
- "lightTreeEmitters, lightTreeEmitterCount and lightToTree must all be present or all absent. Pack them together with packTraceSceneV2.",
+ "lightTreeEmitters, lightTreeEmitterCount and lightToTree must all be present or all absent. Pack them together with buildNativeInputV2.",
))
}
};
diff --git a/tests/native-filter.test.js b/tests/native-filter.test.js
index 00ded7ab..70359f6c 100644
--- a/tests/native-filter.test.js
+++ b/tests/native-filter.test.js
@@ -1,6 +1,13 @@
import assert from 'node:assert/strict';
import test from 'node:test';
-import { validateFilterOptions, validatePackOptions } from '../packages/render-native/pack-input-v2.mjs';
+import { STRUCT_STRIDES_V2, buildNativeInputV2, withFilterOptions } from '../packages/render-native/index.mjs';
+import {
+ KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET,
+ KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET,
+ validateFilterOptions,
+ validatePackOptions,
+} from '../packages/render-native/pack-input-v2.mjs';
+import { createCamera } from '../src/path-tracer.js';
test('pixel filter options accept the three filters and a width in pixels', () => {
for (const filterType of [undefined, 'box', 'gaussian', 'blackman-harris', 'blackman_harris', 0, 1, 2]) {
@@ -29,3 +36,35 @@ test('pixel filter options reject an unknown filter and a width outside 0.01 to
}
assert.throws(() => validatePackOptions({ filterType: 'tent' }, 'test'), /`filterType`/);
});
+
+test('filter options on an already packed v2 input patch the kernel params with the packer offsets', () => {
+ const kernelParams = new Uint8Array(STRUCT_STRIDES_V2.kernelParams);
+ const view = new DataView(kernelParams.buffer);
+ view.setUint32(KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET, 0, true);
+ view.setFloat32(KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET, 1, true);
+ const read = (params) => {
+ const readView = new DataView(params.buffer, params.byteOffset, params.byteLength);
+ return {
+ type: readView.getUint32(KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET, true),
+ width: readView.getFloat32(KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET, true),
+ };
+ };
+ assert.deepEqual(read(withFilterOptions(kernelParams, { filterType: 'blackman-harris' })), { type: 2, width: 1.5 });
+ assert.deepEqual(read(withFilterOptions(kernelParams, { filterType: 'gaussian', filterWidth: 2 })), { type: 1, width: 2 });
+ assert.deepEqual(read(withFilterOptions(kernelParams, { filterWidth: 3 })), { type: 0, width: 3 });
+ assert.deepEqual(read(kernelParams), { type: 0, width: 1 }, 'the packed buffer is not modified');
+});
+
+test('the packer writes the filter at the shared byte offsets', () => {
+ const camera = createCamera({ eye: [0, 0, 6], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const packed = buildNativeInputV2({ materials: [], instances: [], lights: {} }, camera, {
+ width: 8,
+ height: 8,
+ samples: 1,
+ filterType: 'gaussian',
+ filterWidth: 2.5,
+ });
+ const view = new DataView(packed.kernelParams.buffer, packed.kernelParams.byteOffset, packed.kernelParams.byteLength);
+ assert.equal(view.getUint32(KERNEL_PARAMS_V2_FILTER_TYPE_BYTE_OFFSET, true), 1);
+ assert.equal(view.getFloat32(KERNEL_PARAMS_V2_FILTER_WIDTH_BYTE_OFFSET, true), 2.5);
+});
diff --git a/tests/native-light-tree.test.js b/tests/native-light-tree.test.js
index 53d6a596..219e55bb 100644
--- a/tests/native-light-tree.test.js
+++ b/tests/native-light-tree.test.js
@@ -1,8 +1,10 @@
import assert from 'node:assert/strict';
import test from 'node:test';
-import { buildNativeInputV2 } from '../packages/render-native/index.mjs';
+import { 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,
@@ -494,3 +496,54 @@ test('buildNativeInputV2 packs the tree, fills tree_leaf_index and keeps counts
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);
+});