Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Validate native v2 boundary options and tighten parity harness (#894)

Nguyen Xuan Andb16e8512aac
diff --git a/bench/cycles-parity/compare.py b/bench/cycles-parity/compare.py
index 7de12451..18b450e4 100644
--- a/bench/cycles-parity/compare.py
+++ b/bench/cycles-parity/compare.py
@@ -83,6 +83,8 @@ def compute_tile_grid_ratios(reference_rgb, candidate_rgb):
row_strips_cand = numpy.array_split(candidate_rgb, TILE_GRID_SIZE, axis=0)
grid_ratios = []
eligible_entries = []
+ dark_tile_abs_error_sum = 0.0
+ dark_tile_value_count = 0
for row_index in range(TILE_GRID_SIZE):
cols_ref = numpy.array_split(row_strips_ref[row_index], TILE_GRID_SIZE, axis=1)
cols_cand = numpy.array_split(row_strips_cand[row_index], TILE_GRID_SIZE, axis=1)
@@ -108,7 +110,17 @@ def compute_tile_grid_ratios(reference_rgb, candidate_rgb):
"candidateMean": round(cand_mean, 5),
"channelRatios": channel_ratios,
})
+ else:
+ dark_tile_abs_error_sum += float(numpy.abs(cand_tile - ref_tile).sum())
+ dark_tile_value_count += int(ref_tile.size)
grid_ratios.append(row_values)
+ total_tile_count = TILE_GRID_SIZE * TILE_GRID_SIZE
+ excluded_dark_tile_count = total_tile_count - len(eligible_entries)
+ excluded_dark_tile_mae = (
+ round(dark_tile_abs_error_sum / dark_tile_value_count, 6)
+ if dark_tile_value_count > 0
+ else None
+ )
ratios_only = [entry["ratioExact"] for entry in eligible_entries]
within_tolerance = [entry for entry in eligible_entries if entry["absDeviation"] <= TILE_RATIO_TOLERANCE]
min_tile_index = min(range(len(eligible_entries)), key=lambda idx: eligible_entries[idx]["ratioExact"]) if eligible_entries else None
@@ -120,7 +132,10 @@ def compute_tile_grid_ratios(reference_rgb, candidate_rgb):
return {
"gridShape": [TILE_GRID_SIZE, TILE_GRID_SIZE],
"eligibleMeanThreshold": TILE_ELIGIBLE_MEAN_THRESHOLD,
+ "totalTileCount": total_tile_count,
"eligibleTileCount": len(eligible_entries),
+ "excludedDarkTileCount": excluded_dark_tile_count,
+ "excludedDarkTileMeanAbsError": excluded_dark_tile_mae,
"withinFivePercentCount": len(within_tolerance),
"outsideFivePercentCount": len(eligible_entries) - len(within_tolerance),
"minRatio": round(min(ratios_only), 4) if ratios_only else None,
@@ -297,13 +312,16 @@ def format_parity_summary_line(comparison):
flip_text += f" (ceil {gates['flipLdrCeiling']:.4f}, A/B {gates['flipLdrAVsB']:.4f}, pass={gates['flipPass']})"
tile_text = (
f"tiles={tile_grid['withinFivePercentCount']}/{tile_grid['eligibleTileCount']} "
+ f"(of {tile_grid['totalTileCount']} total, {tile_grid['excludedDarkTileCount']} dark excluded) "
f"[{tile_grid['minRatio']}, {tile_grid['maxRatio']}] pass={gates['tileGridPass']}"
)
+ rel_mse_trimmed = comparison.get("relMseTrimmed")
+ rel_mse_trimmed_text = f"{rel_mse_trimmed:.6f}" if rel_mse_trimmed is not None else "n/a"
return (
f"{os.path.basename(comparison['image'])}: "
f"allGatesPass={gates['allGatesPass']} "
f"RGB={ratios} (pass={gates['channelMeanPass']}) "
- f"{tile_text} {flip_text} relMSE={comparison['relMse']:.6f}"
+ f"{tile_text} {flip_text} relMSE={comparison['relMse']:.6f} relMSETrimmed={rel_mse_trimmed_text}"
)
diff --git a/bench/cycles-parity/test-lobes.mjs b/bench/cycles-parity/test-lobes.mjs
index 9983a91f..571f7e7d 100644
--- a/bench/cycles-parity/test-lobes.mjs
+++ b/bench/cycles-parity/test-lobes.mjs
@@ -190,6 +190,42 @@ export const LOBE_PROBE_CASES = [
flags: MATERIAL_FLAG_MULTISCATTER_GGX | MATERIAL_FLAG_F82_METALLIC,
},
},
+ {
+ id: 'anisotropic-conductor-gold-grazing',
+ family: 'anisotropic_ggx',
+ wo: [0.92, 0.0, 0.3919],
+ frontFace: true,
+ expectWhiteFurnace: false,
+ expectColorOrder: [0, 1, 2],
+ expectChiSquare: true,
+ material: {
+ baseColor: [1.0, 0.782, 0.344],
+ f82Tint: [0.92, 0.86, 0.65],
+ metallic: 1.0,
+ roughness: 0.35,
+ anisotropy: 0.7,
+ anisotropyRotation: 0.25,
+ flags: MATERIAL_FLAG_MULTISCATTER_GGX | MATERIAL_FLAG_F82_METALLIC,
+ },
+ },
+ {
+ id: 'anisotropic-conductor-gold-oblique',
+ family: 'anisotropic_ggx',
+ wo: [0.5, 0.3, 0.8124],
+ frontFace: true,
+ expectWhiteFurnace: false,
+ expectColorOrder: [0, 1, 2],
+ expectChiSquare: true,
+ material: {
+ baseColor: [1.0, 0.782, 0.344],
+ f82Tint: [0.92, 0.86, 0.65],
+ metallic: 1.0,
+ roughness: 0.35,
+ anisotropy: 0.7,
+ anisotropyRotation: 0.25,
+ flags: MATERIAL_FLAG_MULTISCATTER_GGX | MATERIAL_FLAG_F82_METALLIC,
+ },
+ },
{
id: 'glass-ggx-frontface-sharp',
family: 'glass_ggx',
diff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjs
index b157f13b..a7564f4a 100644
--- a/bench/cycles-parity/trace-native.mjs
+++ b/bench/cycles-parity/trace-native.mjs
@@ -77,6 +77,9 @@ function parseTraceArguments(argumentList) {
filterGlossy: parseNumberOption(argumentList, '--filter-glossy', 1.0, 0),
fireflyClamp: parseNumberOption(argumentList, '--firefly-clamp', 1e9, 0),
noiseThreshold: parseNumberOption(argumentList, '--noise-threshold', 0, 0),
+ samplesPerDispatch: argumentList.includes('--samples-per-dispatch')
+ ? parseIntegerOption(argumentList, '--samples-per-dispatch', 16, 1)
+ : undefined,
maxSeconds: parseNumberOption(argumentList, '--max-seconds', 1800, 1),
};
}
@@ -113,7 +116,9 @@ async function runCli() {
const traceSource = await reconstructTraceSceneSource(description);
const traceScene = buildTraceScene(traceSource.parts, traceSource.environment);
const camera = createCamera(traceSource.camera, options.width, options.height);
- const samplesPerDispatch = options.noiseThreshold > 0 ? 8 : Math.min(options.samples, 16);
+ const samplesPerDispatch = options.samplesPerDispatch !== undefined
+ ? options.samplesPerDispatch
+ : (options.noiseThreshold > 0 ? 8 : undefined);
const nativeInput = packSceneForKernel(traceScene, camera, { ...options, samplesPerDispatch, parts: traceSource.parts });
const sceneBuildSeconds = (performance.now() - buildStarted) / 1000;
const traced = renderNative.traceNative(nativeInput, {
diff --git a/bench/cycles-parity/verify-lobes.py b/bench/cycles-parity/verify-lobes.py
index 7e1acd9b..eec9594c 100644
--- a/bench/cycles-parity/verify-lobes.py
+++ b/bench/cycles-parity/verify-lobes.py
@@ -16,7 +16,7 @@ CHI_SQUARE_MIN_EXPECTED = 5.0
HISTOGRAM_PHI_BINS = 32
HISTOGRAM_Z_BINS = 32
EVAL_CONSISTENCY_TOLERANCE = 2e-3
-PDF_INTEGRAL_TOLERANCE = 0.015
+PDF_INTEGRAL_TOLERANCE = 0.005
def regularized_gamma_upper(shape_a, value_x):
@@ -115,11 +115,8 @@ def evaluate_spherical_chi_square(mode_zero_rows, pdf_grid):
observed_bins = numpy.bincount(flat_indices, minlength=HISTOGRAM_Z_BINS * HISTOGRAM_PHI_BINS).astype(numpy.float64)
expected_probs = bin_probabilities.ravel().copy()
- if raw_pdf_integral > 1.0:
- expected_probs = expected_probs / raw_pdf_integral
- invalid_prob = 0.0
- else:
- invalid_prob = max(0.0, 1.0 - raw_pdf_integral)
+ # Do not rescale when integral > 1; fail hard via integral_valid check below.
+ invalid_prob = max(0.0, 1.0 - raw_pdf_integral)
all_observed = numpy.append(observed_bins, float(invalid_count))
all_expected = numpy.append(expected_probs, invalid_prob) * float(sample_count)
pooled_obs, pooled_exp, leaked_zero_pdf = pool_histogram_bins(all_observed, all_expected)
@@ -388,6 +385,28 @@ def run_self_test():
})
assert not scene_bad["pass"] and not scene_bad["limbPass"], "Dark-rim grazing energy loss was not rejected"
+ # Verify that a synthetic PDF integrating to 1.006 fails without rescaling.
+ over_integral_grid = build_synthetic_pdf_grid(
+ grid_h, grid_w,
+ lambda z, _p: numpy.maximum(z, 0.0) / math.pi * (1.006 / 1.0),
+ )
+ over_integral_m1 = os.path.join(temp_dir, "over-integral-m1.npy")
+ numpy.save(over_integral_m1, over_integral_grid)
+ over_integral_res = evaluate_lobe_probe({
+ "id": "self-over-integral",
+ "family": "diffuse",
+ "frontFace": True,
+ "wo": [0, 0, 1],
+ "expectWhiteFurnace": True,
+ "expectChiSquare": True,
+ "modeZeroPath": lambert_m0,
+ "modeOnePath": over_integral_m1,
+ })
+ assert not over_integral_res["pass"], (
+ f"PDF integral {over_integral_res['chiSquare']['rawPdfIntegral']:.4f} "
+ "should FAIL (> 1.005) — no rescaling"
+ )
+
print(json.dumps({
"selfTest": "ok",
"lambertPValue": lambert_res["chiSquare"]["pValue"],
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index 33b49e11..174624f6 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -9,9 +9,11 @@ import {
FORMAT_V2_MAGIC,
FORMAT_V2_VERSION,
STRUCT_STRIDES_V2,
+ KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,
buildNativeInputV2,
packMaterialRecordV2,
upgradeNativeInputV1ToV2,
+ validatePackOptions,
} from './pack-input-v2.mjs';
export { buildNativeInput, buildNativeTexelInput } from './pack-input.mjs';
@@ -19,6 +21,7 @@ export {
FORMAT_V2_MAGIC,
FORMAT_V2_VERSION,
STRUCT_STRIDES_V2,
+ KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,
buildNativeInputV2,
packMaterialRecordV2,
upgradeNativeInputV1ToV2,
@@ -55,6 +58,7 @@ export function resolveNativeKernel(kernel) {
* run that long. `kernel` selects `"legacy"` (default) or `"cycles"` (falling back to `JS67_NATIVE_KERNEL` when omitted).
*/
export function traceNative(input, options = {}) {
+ validatePackOptions(options, 'traceNative', true);
const { width, height, samples, maxSeconds, kernel, samplesPerDispatch, bootstrapKernel } = options;
const selectedKernel = resolveNativeKernel(kernel);
const addon = loadAddon();
@@ -74,7 +78,7 @@ export function traceNative(input, options = {}) {
const rawFilterGlossy = Number(explicitFilterGlossy);
const resolvedFilterGlossy = Number.isFinite(rawFilterGlossy) && rawFilterGlossy > 0 ? rawFilterGlossy : 0.0;
const patchedParams = new Uint8Array(v2Input.kernelParams);
- new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength).setFloat32(300, resolvedFilterGlossy, true);
+ new DataView(patchedParams.buffer, patchedParams.byteOffset, patchedParams.byteLength).setFloat32(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, resolvedFilterGlossy, true);
v2Input = { ...v2Input, kernelParams: patchedParams };
}
return addon.traceSceneCycles(v2Input, {
@@ -122,8 +126,8 @@ function buildProbeKernelParams({ width, height, mode, seed, wo, frontFace, mate
export function probeCyclesLobe(options = {}) {
const width = options.width ?? 512;
const height = options.height ?? 512;
- if (!Number.isInteger(width) || width < 1 || !Number.isInteger(height) || height < 1) {
- throw new RangeError('probeCyclesLobe requires positive integer `width` and `height`.');
+ if (!Number.isInteger(width) || width < 1 || width > 16384 || !Number.isInteger(height) || height < 1 || height > 16384) {
+ throw new RangeError(`probeCyclesLobe requires integer \`width\` and \`height\` in [1, 16384]; got width=${width}, height=${height}.`);
}
const wo = options.wo ?? [0, 0, 1];
if (!Array.isArray(wo) && !ArrayBuffer.isView(wo) || wo.length !== 3) {
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index 7fe756f3..5a1a6148 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -5,6 +5,10 @@ export const FORMAT_V2_MAGIC = 0x36375054;
export const FORMAT_V2_VERSION = 2;
export const INVALID_INDEX_V2 = 0xffffffff;
+// Byte offset of `filter_glossy` inside a `KernelParamsV2` buffer (u32[75] * 4 = 300).
+// 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 STRUCT_STRIDES_V2 = Object.freeze({
kernelParams: 320,
instance: 160,
@@ -1430,6 +1434,70 @@ function packEnvironmentTexelsV2(environment, options = {}) {
};
}
+function requireFiniteIntegerInRange(value, name, min, max, callerName) {
+ const n = Number(value);
+ if (!Number.isFinite(n)) {
+ throw new RangeError(
+ `${callerName}: \`${name}\` must be a finite integer in [${min}, ${max}]; got ${value === null ? 'null' : JSON.stringify(value)}.`
+ );
+ }
+ if (!Number.isInteger(n)) {
+ throw new RangeError(
+ `${callerName}: \`${name}\` must be an integer (no fractional part); got ${value}.`
+ );
+ }
+ if (n < min || n > max) {
+ throw new RangeError(
+ `${callerName}: \`${name}\` must be in [${min}, ${max}]; got ${n}.`
+ );
+ }
+}
+
+function requireFiniteIntegerInRangeIfPresent(value, name, min, max, callerName) {
+ if (value === undefined) {
+ return;
+ }
+ requireFiniteIntegerInRange(value, name, min, max, callerName);
+}
+
+/**
+ * Validates public boundary options for `buildNativeInputV2`, `upgradeNativeInputV1ToV2`, and
+ * `traceNative`. Throws `RangeError` or `TypeError` with a descriptive message on failure.
+ */
+export function validatePackOptions(options, callerName, requireDimensionsAndSamples = false) {
+ if (!options || typeof options !== 'object') {
+ throw new TypeError(`${callerName}: \`options\` must be an object.`);
+ }
+ const { width, height, samples, samplesPerDispatch } = options;
+ if (requireDimensionsAndSamples || width !== undefined) {
+ requireFiniteIntegerInRange(width, 'width', 1, 16384, callerName);
+ }
+ if (requireDimensionsAndSamples || height !== undefined) {
+ requireFiniteIntegerInRange(height, 'height', 1, 16384, callerName);
+ }
+ if (requireDimensionsAndSamples || samples !== undefined) {
+ requireFiniteIntegerInRange(samples, 'samples', 1, 1048576, callerName);
+ }
+ // samplesPerDispatch is optional (undefined means "let the addon choose"); only validate when provided.
+ requireFiniteIntegerInRangeIfPresent(samplesPerDispatch, 'samplesPerDispatch', 1, 65536, callerName);
+
+ // Bounce limits — each is optional; when provided must be a finite integer in [0, 1024].
+ const bounceFields = [
+ 'bounces', 'maxBounces',
+ 'diffuseBounces', 'maxDiffuseBounces',
+ 'glossyBounces', 'maxGlossyBounces',
+ 'transmissionBounces', 'maxTransmissionBounces',
+ 'volumeBounces', 'maxVolumeBounces',
+ 'transparentBounces', 'maxTransparentBounces',
+ 'minBounceRr',
+ ];
+ for (const field of bounceFields) {
+ if (options[field] !== undefined) {
+ requireFiniteIntegerInRange(options[field], field, 0, 1024, callerName);
+ }
+ }
+}
+
function effectiveCyclesClamp(value) {
if (value === undefined || value === null) {
return 0.0;
@@ -1623,7 +1691,8 @@ function packKernelParamsV2({
f32[72] = Number(options.exposure ?? 1.0);
f32[73] = packedEnvironment.envWidth > 0 && packedEnvironment.envTotalWeight > 0 ? 1.0 : 0.0;
u32[74] = 0;
- f32[75] = filterGlossy;
+ // KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET / 4 = 75
+ f32[KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET / 4] = filterGlossy;
u32[76] = 0;
u32[77] = 0;
@@ -2058,6 +2127,7 @@ export function buildNativeInputV2(scene, camera, options = {}) {
if (!camera || typeof camera !== 'object') {
throw new TypeError('buildNativeInputV2 requires a camera object.');
}
+ validatePackOptions(options, 'buildNativeInputV2');
const textureCollector = createTextureCollector();
const explicitInstances = options.instances ?? scene.instances;
@@ -2137,6 +2207,7 @@ export function upgradeNativeInputV1ToV2(v1Input, options = {}) {
if (!v1Input || !(v1Input.parameters instanceof Uint8Array) || v1Input.parameters.byteLength !== 256) {
throw new TypeError('upgradeNativeInputV1ToV2 requires a v1 NativeTraceInput with a 256-byte parameters block, or a FORMAT-v2 input.');
}
+ validatePackOptions(options, 'upgradeNativeInputV1ToV2');
const paramBuffer = v1Input.parameters.buffer;
const paramByteOffset = v1Input.parameters.byteOffset;
diff --git a/tests/native-pack-v2.test.js b/tests/native-pack-v2.test.js
index cdd84b3f..b2cd38f7 100644
--- a/tests/native-pack-v2.test.js
+++ b/tests/native-pack-v2.test.js
@@ -3,6 +3,7 @@ import test from 'node:test';
import {
FORMAT_V2_MAGIC,
FORMAT_V2_VERSION,
+ KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET,
STRUCT_STRIDES_V2,
buildNativeInput,
buildNativeInputV2,
@@ -553,3 +554,166 @@ test('Cycles v2 host executes multi-BLAS/TLAS ray queries, cutout alpha masking,
assert.throws(() => probeCyclesLobe({ width: 8, height: 8, wo: [0, 0, 0], bootstrapKernel: true }), /non-zero finite 3D vector/);
});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: shared filterGlossy offset constant
+// ---------------------------------------------------------------------------
+
+test('KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET equals 300 (f32[75] * 4)', () => {
+ assert.equal(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, 300);
+ // Verify pack-input-v2 writes filterGlossy at that offset.
+ const parts = [{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }];
+ const scene = buildTraceScene(parts, {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const v2 = buildNativeInputV2(scene, camera, { width: 8, height: 8, samples: 1, filterGlossy: 2.5 });
+ const kp = new DataView(v2.kernelParams.buffer, v2.kernelParams.byteOffset, v2.kernelParams.byteLength);
+ assert.ok(Math.abs(kp.getFloat32(KERNEL_PARAMS_V2_FILTER_GLOSSY_BYTE_OFFSET, true) - 2.5) < 1e-6, 'filterGlossy at byte 300');
+});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: width and height
+// ---------------------------------------------------------------------------
+
+test('buildNativeInputV2 rejects non-finite, non-integer, out-of-range width and height', () => {
+ const minimalScene = buildTraceScene([{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }], {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const ok = { width: 8, height: 8, samples: 1 };
+ const build = (opts) => buildNativeInputV2(minimalScene, camera, { ...ok, ...opts });
+
+ // NaN
+ assert.throws(() => build({ width: NaN }), /width/, 'width NaN');
+ assert.throws(() => build({ height: NaN }), /height/, 'height NaN');
+ // Infinity
+ assert.throws(() => build({ width: Infinity }), /width/, 'width Infinity');
+ assert.throws(() => build({ height: -Infinity }), /height/, 'height -Infinity');
+ // Float
+ assert.throws(() => build({ width: 1.5 }), /width/, 'width float');
+ assert.throws(() => build({ height: 8.3 }), /height/, 'height float');
+ // Zero
+ assert.throws(() => build({ width: 0 }), /width/, 'width 0');
+ assert.throws(() => build({ height: 0 }), /height/, 'height 0');
+ // Negative
+ assert.throws(() => build({ width: -1 }), /width/, 'width -1');
+ assert.throws(() => build({ height: -100 }), /height/, 'height -100');
+ // Over bound
+ assert.throws(() => build({ width: 16385 }), /width/, 'width 16385');
+ assert.throws(() => build({ height: 99999 }), /height/, 'height 99999');
+ // Exact bounds pass
+ assert.doesNotThrow(() => build({ width: 1, height: 1 }), 'min bounds');
+ assert.doesNotThrow(() => build({ width: 16384, height: 16384 }), 'max bounds');
+});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: samples
+// ---------------------------------------------------------------------------
+
+test('buildNativeInputV2 rejects non-finite, non-integer, out-of-range samples', () => {
+ const minimalScene = buildTraceScene([{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }], {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const ok = { width: 8, height: 8, samples: 1 };
+ const build = (opts) => buildNativeInputV2(minimalScene, camera, { ...ok, ...opts });
+
+ assert.throws(() => build({ samples: NaN }), /samples/, 'samples NaN');
+ assert.throws(() => build({ samples: Infinity }), /samples/, 'samples Infinity');
+ assert.throws(() => build({ samples: -Infinity }), /samples/, 'samples -Infinity');
+ assert.throws(() => build({ samples: 1.5 }), /samples/, 'samples float');
+ assert.throws(() => build({ samples: 0 }), /samples/, 'samples 0');
+ assert.throws(() => build({ samples: -1 }), /samples/, 'samples -1');
+ assert.throws(() => build({ samples: 1048577 }), /samples/, 'samples 1048577');
+ // Exact bounds pass
+ assert.doesNotThrow(() => build({ samples: 1 }), 'samples 1');
+ assert.doesNotThrow(() => build({ samples: 1048576 }), 'samples 1048576');
+});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: samplesPerDispatch (optional)
+// ---------------------------------------------------------------------------
+
+test('buildNativeInputV2 accepts undefined samplesPerDispatch but rejects invalid values', () => {
+ const minimalScene = buildTraceScene([{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }], {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const ok = { width: 8, height: 8, samples: 1 };
+ const build = (opts) => buildNativeInputV2(minimalScene, camera, { ...ok, ...opts });
+
+ // undefined: must be accepted (addon chooses default)
+ assert.doesNotThrow(() => build({ samplesPerDispatch: undefined }), 'undefined');
+ // Invalid values
+ assert.throws(() => build({ samplesPerDispatch: NaN }), /samplesPerDispatch/, 'NaN');
+ assert.throws(() => build({ samplesPerDispatch: Infinity }), /samplesPerDispatch/, 'Infinity');
+ assert.throws(() => build({ samplesPerDispatch: 1.5 }), /samplesPerDispatch/, 'float');
+ assert.throws(() => build({ samplesPerDispatch: 0 }), /samplesPerDispatch/, 'zero');
+ assert.throws(() => build({ samplesPerDispatch: -1 }), /samplesPerDispatch/, 'negative');
+ assert.throws(() => build({ samplesPerDispatch: 65537 }), /samplesPerDispatch/, '65537');
+ // Exact bounds pass
+ assert.doesNotThrow(() => build({ samplesPerDispatch: 1 }), 'min 1');
+ assert.doesNotThrow(() => build({ samplesPerDispatch: 65536 }), 'max 65536');
+});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: bounce limits (non-finite / negative / float / over-bound rejection)
+// ---------------------------------------------------------------------------
+
+test('buildNativeInputV2 rejects non-finite and out-of-range bounce limit values', () => {
+ const minimalScene = buildTraceScene([{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }], {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const ok = { width: 8, height: 8, samples: 1 };
+ const build = (opts) => buildNativeInputV2(minimalScene, camera, { ...ok, ...opts });
+
+ const bounceFields = [
+ 'bounces', 'maxBounces',
+ 'diffuseBounces', 'maxDiffuseBounces',
+ 'glossyBounces', 'maxGlossyBounces',
+ 'transmissionBounces', 'maxTransmissionBounces',
+ 'volumeBounces', 'maxVolumeBounces',
+ 'transparentBounces', 'maxTransparentBounces',
+ 'minBounceRr',
+ ];
+
+ for (const field of bounceFields) {
+ // Infinity previously packed to 0 (now rejected)
+ assert.throws(() => build({ [field]: Infinity }), new RegExp(field), `${field}: Infinity`);
+ assert.throws(() => build({ [field]: -Infinity }), new RegExp(field), `${field}: -Infinity`);
+ assert.throws(() => build({ [field]: NaN }), new RegExp(field), `${field}: NaN`);
+ assert.throws(() => build({ [field]: -1 }), new RegExp(field), `${field}: -1`);
+ assert.throws(() => build({ [field]: 1.5 }), new RegExp(field), `${field}: 1.5`);
+ assert.throws(() => build({ [field]: 1025 }), new RegExp(field), `${field}: 1025`);
+ // Valid bounds pass
+ assert.doesNotThrow(() => build({ [field]: 0 }), `${field}: 0`);
+ assert.doesNotThrow(() => build({ [field]: 1024 }), `${field}: 1024`);
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Boundary validation: upgradeNativeInputV1ToV2 validates options too
+// ---------------------------------------------------------------------------
+
+test('upgradeNativeInputV1ToV2 validates width, height, samples, samplesPerDispatch, and bounce fields', () => {
+ // Minimal valid v1 input (parameters = 256-byte Uint8Array with triangleCount = 0 triangle data).
+ const parameters = new Uint8Array(256);
+ const v1Input = { parameters, triangleCount: 0, triangles: new Float32Array(0), materials: new Float32Array(0) };
+
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { width: NaN }), /width/, 'width NaN');
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { height: Infinity }), /height/, 'height Inf');
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { samples: 0 }), /samples/, 'samples 0');
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { samplesPerDispatch: -1 }), /samplesPerDispatch/, 'spd -1');
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { bounces: Infinity }), /bounces/, 'bounces Inf');
+ assert.throws(() => upgradeNativeInputV1ToV2(v1Input, { maxGlossyBounces: 1.5 }), /maxGlossyBounces/, 'float');
+ // Valid options pass
+ assert.doesNotThrow(
+ () => upgradeNativeInputV1ToV2(v1Input, { width: 32, height: 32, samples: 4, bounces: 8 }),
+ 'valid options'
+ );
+});
+
+test('traceNative and probeCyclesLobe validate options at the public boundary even on pre-built v2 inputs', () => {
+ const minimalScene = buildTraceScene([{ name: 'q', geometry: quadGeometry(0), material: { color: [0.5, 0.5, 0.5] } }], {});
+ const camera = createCamera({ eye: [0, 0, 3], target: [0, 0, 0], fov: 50 }, 8, 8);
+ const v2Input = buildNativeInputV2(minimalScene, camera, { width: 8, height: 8, samples: 1 });
+
+ assert.throws(() => traceNative(v2Input, { width: Infinity, height: 8, samples: 1, kernel: 'cycles' }), /width/);
+ assert.throws(() => traceNative(v2Input, { width: 8, height: 8, samples: NaN, kernel: 'cycles' }), /samples/);
+ assert.throws(() => traceNative(v2Input, { width: 8, height: 8, samples: 1, samplesPerDispatch: Infinity, kernel: 'cycles' }), /samplesPerDispatch/);
+ assert.throws(() => traceNative(v2Input, { width: 8, height: 8, samples: 1, bounces: Infinity, kernel: 'cycles' }), /bounces/);
+ assert.throws(() => traceNative(v2Input, { height: 8, samples: 1, kernel: 'cycles' }), /width/);
+ assert.throws(() => probeCyclesLobe({ width: 16385, height: 8 }), /16384/);
+});