3D engine that AI agents drive
Sample the pixel filter from the Cycles 1024-entry table, validate filter options and measure box against Blackman-Harris (#895)
Nguyen Xuan An163f11a304a6
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.pyindex 1fc9877a..d60bd158 100644--- a/bench/cycles-parity/render-cycles.py+++ b/bench/cycles-parity/render-cycles.py@@ -43,12 +43,15 @@ def read_flag_value(argument_list, flag_name, fallback_value):return argument_list[flag_index + 1]+PIXEL_FILTER_TYPES = {"box": "BOX", "gaussian": "GAUSSIAN", "blackman-harris": "BLACKMAN_HARRIS"}++def parse_cli_arguments():if "--" not in sys.argv:raise ValueError("Pass script arguments after '--': <sceneJsonPath> <outputPrefix> [options].")argument_list = sys.argv[sys.argv.index("--") + 1:]if len(argument_list) < 2 or argument_list[0].startswith("--") or argument_list[1].startswith("--"):- raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--keep-exr] [--part-ids]")+ raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--keep-exr] [--part-ids]")return {"scene_json_path": os.path.abspath(argument_list[0]),"output_prefix": os.path.abspath(argument_list[1]),@@ -57,6 +60,8 @@ def parse_cli_arguments():"seed": int(read_flag_value(argument_list, "--seed", "1")),"width": int(read_flag_value(argument_list, "--width", "960")),"height": int(read_flag_value(argument_list, "--height", "540")),+ "filter_type": read_flag_value(argument_list, "--filter-type", "box"),+ "filter_width": float(read_flag_value(argument_list, "--filter-width", "1.0")),"keep_exr": "--keep-exr" in argument_list,"part_ids": "--part-ids" in argument_list,}@@ -440,8 +445,8 @@ def configure_cycles_parity(scene, options):scene.cycles.seed = options["seed"]scene.cycles.use_denoising = Falsescene.cycles.use_adaptive_sampling = False- scene.cycles.pixel_filter_type = "BOX"- scene.cycles.filter_width = 1.0+ scene.cycles.pixel_filter_type = PIXEL_FILTER_TYPES[options["filter_type"]]+ scene.cycles.filter_width = options["filter_width"]scene.cycles.sample_clamp_direct = 0.0scene.cycles.sample_clamp_indirect = 0.0scene.cycles.caustics_reflective = Truediff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjsindex 8f3d810f..2538f938 100644--- a/bench/cycles-parity/trace-native.mjs+++ b/bench/cycles-parity/trace-native.mjs@@ -11,7 +11,7 @@ import { writeFloat32Npy } from './npy.mjs';import { reconstructTraceSceneSource } from './scene-bridge.mjs';const SUPPORTED_KERNELS = new Set(['legacy', 'cycles']);-const SUPPORTED_FILTERS = new Set(['box', 'blackman-harris']);+const SUPPORTED_FILTERS = new Set(['box', 'gaussian', 'blackman-harris']);const SUPPORTED_SAMPLERS = new Set(['white', 'sobol-burley']);function readFlagValue(argumentList, flagName, fallbackValue) {@@ -53,7 +53,7 @@ function parseKernelOption(argumentList) {function parseFilterTypeOption(argumentList) {const filterType = String(readFlagValue(argumentList, '--filter-type', 'box'));if (!SUPPORTED_FILTERS.has(filterType)) {- throw new RangeError(`Option --filter-type must be "box" or "blackman-harris", got "${filterType}".`);+ throw new RangeError(`Option --filter-type must be "box", "gaussian" or "blackman-harris", got "${filterType}".`);}return filterType;}@@ -68,7 +68,7 @@ function parseSamplerOption(argumentList) {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|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] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0]');}return {sceneJsonPath: resolve(argumentList[0]),diff --git a/docs/cycles-parity.md b/docs/cycles-parity.mdindex 3f526a61..a5a34546 100644--- a/docs/cycles-parity.md+++ b/docs/cycles-parity.md@@ -38,7 +38,7 @@ Exported losslessly from [`bench/reference/scenes.js`](../bench/reference/scenes| Filter glossy | `filter_glossy = 1.0` (`bsdf_blur` on secondary glossy bounces) | `filterGlossy: 1.0` in `--kernel cycles` (none in `legacy`) | Matches Cycles secondary-bounce roughness blur (`alpha >= filter_glossy * min_ray_pdf`) on reflective/refractive caustics || Denoising | `use_denoising = False` | Raw `traced.rgba` (no wavelet/OIDN) | Measure raw Monte Carlo estimator || Adaptive sampling | `use_adaptive_sampling = False` | `noiseThreshold: 0` | Draw exact `N` samples at every pixel |-| Pixel filter | `pixel_filter_type = 'BOX'`, `filter_width = 1.0` | Uniform jitter in `[0, 1)^2` | Cycles default Blackman-Harris `1.5 px` blurs/rings across pixel boundaries |+| Pixel filter | `pixel_filter_type = 'BOX'`, `filter_width = 1.0` (the references; Cycles' own default is Blackman-Harris `1.5 px`) | `filterType: 'box'`, `filterWidth: 1.0` by default; `'blackman-harris'` (default width `1.5`) and `'gaussian'` sample the Cycles 1024-entry inverse-CDF table (`filter_table.rs`, translated from `film.cpp`) | With each filter the native image matches a Cycles reference rendered with the same filter; the measured relMSE and FLIP are in the table below || Color space | `OPEN_EXR` `32`-bit float RGB, `view_transform = 'Raw'`, `look = 'None'` | Linear `Float32Array` RGB `.npy` | Scene-referred linear float32 with no tone map |### Bounce-Count Semantics Verification@@ -342,6 +342,19 @@ These are per-sample times on one scene. An equal-error comparison between the `---+### Pixel filter: box versus Blackman-Harris++The six-scene references use the box filter of width 1, so the box filter stays the default of the `cycles` kernel. Cycles' own default is Blackman-Harris with width 1.5. To show which choice matches Cycles, `render-cycles.py --filter-type blackman-harris --filter-width 1.5` rendered a second Cycles 5.3 reference (4096 spp, seed 1, OptiX) and the `cycles` kernel ran at 1024 spp, seed 1, 8 bounces, 960 x 540 with each filter `[measured]`:++| Scene | Native filter | vs Cycles box 1 (relMSE / FLIP LDR) | vs Cycles Blackman-Harris 1.5 (relMSE / FLIP LDR) |+| :--- | :--- | :--- | :--- |+| `lit-interior` | box 1 | 0.00105 / 0.0272 | 0.00106 / 0.0273 |+| `lit-interior` | Blackman-Harris 1.5 | 0.00106 / 0.0273 | 0.00105 / 0.0272 |+| `glass` | box 1 | 0.00009 / 0.0073 | 0.00016 / 0.0084 |+| `glass` | Blackman-Harris 1.5 | 0.00061 / 0.0082 | 0.00010 / 0.0073 |++`lit-interior` is smooth, so the filter hides under its noise. `glass` has hard caustic edges: each native filter scores best against the Cycles reference rendered with the same filter, and the mismatched pair is 4 to 7 times worse in relMSE.+## Reproducible CommandsRun from the repository root in PowerShell. Set `$env:BLENDER_BIN` if Blender 5.3 is installed outside `C:\Program Files\Blender Foundation\Blender 5.3\blender.exe`, and pass an untracked `<out-dir>` (such as `artifacts/cycles-parity`) so binary `.exr` and `.npy` files stay out of Git:diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjsindex edf0c7e3..9304bf19 100644--- a/packages/render-native/pack-input-v2.mjs+++ b/packages/render-native/pack-input-v2.mjs@@ -1539,6 +1539,7 @@ export function validatePackOptions(options, callerName, requireDimensionsAndSamrequireFiniteIntegerInRangeIfPresent(samplesPerDispatch, 'samplesPerDispatch', 1, 65536, callerName);validateMaxSeconds(options.maxSeconds, callerName);validateSamplerOption(options.sampler, callerName);+ validateFilterOptions(options, callerName);if (width !== undefined && height !== undefined) {validateImagePixelCount(width, height, callerName);if (samplesPerDispatch !== undefined) {@@ -1574,16 +1575,40 @@ function effectiveCyclesClamp(value) {return numeric * 3.0;}-function resolveFilterParameters(options = {}) {- const filter = options.filterType ?? options.pixelFilter ?? 0;- let filterType = 0;- if (filter === 1 || filter === 'gaussian') {- filterType = 1;- } else if (filter === 2 || filter === 'blackman-harris' || filter === 'blackman_harris') {- filterType = 2;+const FILTER_TYPE_CODES = Object.freeze({+ box: 0,+ gaussian: 1,+ 'blackman-harris': 2,+ blackman_harris: 2,+});++function filterTypeCode(filter) {+ if (filter === 0 || filter === 1 || filter === 2) {+ return filter;+ }+ return typeof filter === 'string' ? FILTER_TYPE_CODES[filter] : undefined;+}++/** Throws unless `filterType` (or `pixelFilter`) and `filterWidth` are absent or valid. Width is in pixels, 0.01 to 16. */+export function validateFilterOptions(options, callerName) {+ const filter = options.filterType !== undefined ? options.filterType : options.pixelFilter;+ if (filter !== undefined && filterTypeCode(filter) === undefined) {+ throw new RangeError(+ `${callerName}: \`filterType\` must be "box" (default), "gaussian" or "blackman-harris", got ${JSON.stringify(filter)}.`+ );+ }+ const width = options.filterWidth;+ if (width !== undefined && !(typeof width === 'number' && Number.isFinite(width) && width >= 0.01 && width <= 16)) {+ throw new RangeError(+ `${callerName}: \`filterWidth\` must be a number of pixels from 0.01 to 16 (1.5 is the Cycles Blackman-Harris default), got ${JSON.stringify(width)}.`+ );}+}++function resolveFilterParameters(options = {}) {+ const filterType = filterTypeCode(options.filterType ?? options.pixelFilter ?? 0) ?? 0;const defaultWidth = filterType === 0 ? 1.0 : 1.5;- const filterWidth = options.filterWidth !== undefined ? Math.max(0.01, Number(options.filterWidth)) : defaultWidth;+ const filterWidth = options.filterWidth ?? defaultWidth;return { filterType, filterWidth };}diff --git a/packages/render-native/src/cycles/filter.wgsl b/packages/render-native/src/cycles/filter.wgslindex 17001ab8..340f43f7 100644--- a/packages/render-native/src/cycles/filter.wgsl+++ b/packages/render-native/src/cycles/filter.wgsl@@ -1,60 +1,27 @@// SPDX-FileCopyrightText: 2011-2022 Blender Foundation// SPDX-License-Identifier: Apache-2.0//-// Pixel reconstruction filter importance sampling (`flt_*`), ported from Cycles `scene/film.cpp`.+// Pixel reconstruction filter importance sampling (`flt_*`), ported from Cycles `scene/film.cpp` and+// `kernel/util/lookup_table.h`. The host (`filter_table.rs`) builds the 1024-entry inverse-CDF tables for filter+// width 1 and appends them to the LUT buffer after `CYCLES_LUT_WORDS`. A table entry is a sample position inside+// the pixel centred on 0.5, so the offset from the pixel centre is `(entry - 0.5) * filter_width`.-const FLT_LUT_LAST_INDEX: u32 = 64u;+const FLT_TABLE_SIZE: u32 = 1024u;+const FLT_TABLE_GAUSSIAN_OFFSET: u32 = 29712u;+const FLT_TABLE_BLACKMAN_HARRIS_OFFSET: u32 = 30736u;-const FLT_GAUSSIAN_INV_CDF = array<f32, 65>(- 0.0000000, 0.0048961, 0.0097940, 0.0146957, 0.0196031,- 0.0245180, 0.0294425, 0.0343784, 0.0393277, 0.0442925,- 0.0492748, 0.0542767, 0.0593005, 0.0643484, 0.0694226,- 0.0745256, 0.0796598, 0.0848279, 0.0900325, 0.0952764,- 0.1005625, 0.1058940, 0.1112741, 0.1167063, 0.1221941,- 0.1277415, 0.1333524, 0.1390314, 0.1447830, 0.1506124,- 0.1565248, 0.1625260, 0.1686224, 0.1748208, 0.1811286,- 0.1875538, 0.1941054, 0.2007931, 0.2076277, 0.2146211,- 0.2217866, 0.2291392, 0.2366954, 0.2444744, 0.2524975,- 0.2607896, 0.2693789, 0.2782986, 0.2875873, 0.2972911,- 0.3074647, 0.3181747, 0.3295027, 0.3415510, 0.3544493,- 0.3683669, 0.3835301, 0.4002522, 0.4189849, 0.4404176,- 0.4656830, 0.4968570, 0.5384687, 0.6043897, 1.5000000,-);--const FLT_BLACKMAN_HARRIS_INV_CDF = array<f32, 65>(- 0.0000000, 0.0056058, 0.0112136, 0.0168255, 0.0224434,- 0.0280694, 0.0337057, 0.0393542, 0.0450171, 0.0506965,- 0.0563948, 0.0621141, 0.0678568, 0.0736252, 0.0794219,- 0.0852493, 0.0911102, 0.0970072, 0.1029432, 0.1089211,- 0.1149442, 0.1210157, 0.1271389, 0.1333176, 0.1395556,- 0.1458569, 0.1522258, 0.1586668, 0.1651850, 0.1717856,- 0.1784741, 0.1852566, 0.1921397, 0.1991303, 0.2062363,- 0.2134660, 0.2208285, 0.2283338, 0.2359932, 0.2438187,- 0.2518240, 0.2600243, 0.2684367, 0.2770803, 0.2859770,- 0.2951516, 0.3046328, 0.3144536, 0.3246529, 0.3352763,- 0.3463782, 0.3580243, 0.3702950, 0.3832900, 0.3971356,- 0.4119955, 0.4280867, 0.4457076, 0.4652846, 0.4874611,- 0.5132813, 0.5446273, 0.5855150, 0.6478121, 1.0000000,-);--fn flt_lookup_gaussian_1d(unit_value: f32) -> f32 {- let sign_scale = select(1.0, -1.0, unit_value < 0.5);- let folded = clamp(abs(2.0 * unit_value - 1.0), 0.0, 1.0);- let scaled = folded * f32(FLT_LUT_LAST_INDEX);- let index_lo = min(u32(floor(scaled)), FLT_LUT_LAST_INDEX - 1u);- let fraction = scaled - f32(index_lo);- let magnitude = mix(FLT_GAUSSIAN_INV_CDF[index_lo], FLT_GAUSSIAN_INV_CDF[index_lo + 1u], fraction);- return sign_scale * magnitude;-}--fn flt_lookup_blackman_harris_1d(unit_value: f32) -> f32 {- let sign_scale = select(1.0, -1.0, unit_value < 0.5);- let folded = clamp(abs(2.0 * unit_value - 1.0), 0.0, 1.0);- let scaled = folded * f32(FLT_LUT_LAST_INDEX);- let index_lo = min(u32(floor(scaled)), FLT_LUT_LAST_INDEX - 1u);- let fraction = scaled - f32(index_lo);- let magnitude = mix(FLT_BLACKMAN_HARRIS_INV_CDF[index_lo], FLT_BLACKMAN_HARRIS_INV_CDF[index_lo + 1u], fraction);- return sign_scale * magnitude;+// Cycles `lookup_table_read`: linear interpolation between neighbouring entries.+fn flt_table_read(table_offset: u32, unit_value: f32) -> f32 {+ let scaled = clamp(unit_value, 0.0, 1.0) * f32(FLT_TABLE_SIZE - 1u);+ let index = min(u32(scaled), FLT_TABLE_SIZE - 1u);+ let next_index = min(index + 1u, FLT_TABLE_SIZE - 1u);+ let fraction = scaled - f32(index);+ let lower = bitcast<f32>(cycles_lut[table_offset + index]);+ if (fraction == 0.0) {+ return lower;+ }+ let upper = bitcast<f32>(cycles_lut[table_offset + next_index]);+ return (1.0 - fraction) * lower + fraction * upper;}fn flt_sample_offset(unit_uv: vec2<f32>) -> vec2<f32> {@@ -63,10 +30,16 @@ fn flt_sample_offset(unit_uv: vec2<f32>) -> vec2<f32> {return vec2<f32>(0.0, 0.0);}if (kernel_params.filter_type == FILTER_GAUSSIAN) {- return vec2<f32>(flt_lookup_gaussian_1d(unit_uv.x), flt_lookup_gaussian_1d(unit_uv.y)) * width;+ let sampled = vec2<f32>(+ flt_table_read(FLT_TABLE_GAUSSIAN_OFFSET, unit_uv.x),+ flt_table_read(FLT_TABLE_GAUSSIAN_OFFSET, unit_uv.y));+ return (sampled - vec2<f32>(0.5, 0.5)) * width;}if (kernel_params.filter_type == FILTER_BLACKMAN_HARRIS) {- return vec2<f32>(flt_lookup_blackman_harris_1d(unit_uv.x), flt_lookup_blackman_harris_1d(unit_uv.y)) * width;+ let sampled = vec2<f32>(+ flt_table_read(FLT_TABLE_BLACKMAN_HARRIS_OFFSET, unit_uv.x),+ flt_table_read(FLT_TABLE_BLACKMAN_HARRIS_OFFSET, unit_uv.y));+ return (sampled - vec2<f32>(0.5, 0.5)) * width;}return (unit_uv - vec2<f32>(0.5, 0.5)) * width;}diff --git a/packages/render-native/src/cycles/filter_table.rs b/packages/render-native/src/cycles/filter_table.rsnew file mode 100644index 00000000..15ef2fa0--- /dev/null+++ b/packages/render-native/src/cycles/filter_table.rs@@ -0,0 +1,208 @@+// SPDX-FileCopyrightText: 2011-2022 Blender Foundation+// SPDX-License-Identifier: Apache-2.0+//+// Pixel filter importance sampling tables, translated from Cycles `scene/film.cpp` (`filter_table`) and+// `util/math_cdf.{h,cpp}` (`util_cdf_evaluate`, `util_cdf_invert`). Cycles builds one 1024-entry table per film;+// the table is the inverse CDF of the filter, centred on the pixel centre (0.5), and the kernel reads it with a+// linear lookup. The shape depends on the filter width only by a scale, so the host builds the tables once for+// filter width 1 and the kernel scales the offset from 0.5 by the width of the job.++use std::f32::consts::TAU;++/// Entries per table (`FILTER_TABLE_SIZE` in Cycles `kernel/types.h`).+pub(crate) const FILTER_TABLE_SIZE: usize = 1024;++/// Which importance-sampled filter a table describes. The box filter needs no table.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) enum FilterKind {+ Gaussian,+ BlackmanHarris,+}++fn filter_function(kind: FilterKind, value: f32, width: f32) -> f32 {+ match kind {+ FilterKind::Gaussian => {+ let scaled = value * (6.0 / width);+ (-2.0 * scaled * scaled).exp()+ }+ FilterKind::BlackmanHarris => {+ let angle = TAU * (value / width + 0.5);+ 0.35875 - 0.48829 * angle.cos() + 0.14128 * (2.0 * angle).cos() - 0.01168 * (3.0 * angle).cos()+ }+ }+}++/// `util_cdf_evaluate`: cumulative sum of |f| over `resolution` steps, normalised so the last entry is exactly 1.+fn evaluate_cdf(resolution: usize, from: f32, to: f32, function: &dyn Fn(f32) -> f32) -> Vec<f32> {+ let range = to - from;+ let mut cdf = vec![0.0f32; resolution + 1];+ for index in 0..resolution {+ let position = from + range * index as f32 / (resolution - 1) as f32;+ cdf[index + 1] = cdf[index] + function(position).abs();+ }+ let total = cdf[resolution];+ let factor = if total == 0.0 { 0.0 } else { 1.0 / total };+ for entry in cdf.iter_mut() {+ *entry *= factor;+ }+ cdf[resolution] = 1.0;+ cdf+}++/// `util_cdf_invert` with `make_symmetric = true`.+fn invert_cdf_symmetric(resolution: usize, range: f32, cdf: &[f32]) -> Vec<f32> {+ let cdf_size = cdf.len();+ let half_size = (resolution - 1) / 2;+ let mut inverse = vec![0.0f32; resolution];+ for offset in 0..=half_size {+ let probability = offset as f32 / half_size as f32;+ let mut index = cdf.partition_point(|&entry| entry <= probability);+ let fraction = if index < cdf_size - 1 {+ (probability - cdf[index]) / (cdf[index + 1] - cdf[index])+ } else {+ index = cdf_size - 1;+ 0.0+ };+ let distance = ((index as f32 + fraction) / (resolution - 1) as f32) * (2.0 * range);+ inverse[half_size + offset] = 0.5 * (1.0 + distance);+ inverse[half_size - offset] = 0.5 * (1.0 - distance);+ }+ inverse+}++/// 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.+pub(crate) fn build_filter_table(kind: FilterKind, filter_width: f32) -> Vec<f32> {+ let support_width = match kind {+ FilterKind::Gaussian => filter_width * 3.0,+ FilterKind::BlackmanHarris => filter_width * 2.0,+ };+ let range = support_width * 0.5;+ let cdf = evaluate_cdf(FILTER_TABLE_SIZE - 1, 0.0, range, &|position| {+ filter_function(kind, position, support_width)+ });+ invert_cdf_symmetric(FILTER_TABLE_SIZE, range, &cdf)+}++/// Both tables for filter width 1, Gaussian first, as raw f32 bits ready to append to the LUT buffer.+pub(crate) fn unit_filter_table_words() -> Vec<u32> {+ let mut words = Vec::with_capacity(2 * FILTER_TABLE_SIZE);+ for kind in [FilterKind::Gaussian, FilterKind::BlackmanHarris] {+ words.extend(build_filter_table(kind, 1.0).iter().map(|value| value.to_bits()));+ }+ words+}++#[cfg(test)]+mod filter_table_tests {+ use super::*;++ const KINDS: [FilterKind; 2] = [FilterKind::Gaussian, FilterKind::BlackmanHarris];++ fn read_linear(table: &[f32], unit_value: f32) -> f32 {+ let scaled = unit_value.clamp(0.0, 1.0) * (table.len() - 1) as f32;+ let index = (scaled as usize).min(table.len() - 1);+ let next_index = (index + 1).min(table.len() - 1);+ let fraction = scaled - index as f32;+ (1.0 - fraction) * table[index] + fraction * table[next_index]+ }++ #[test]+ // Cycles writes only entries 0..1022 of its even-sized table (see the TODO in `film.cpp`); entry 1023 stays 0.+ fn table_has_cycles_size_and_pixel_centred_ends() {+ for kind in KINDS {+ let table = build_filter_table(kind, 1.5);+ assert_eq!(table.len(), 1024);+ let support = match kind {+ FilterKind::Gaussian => 1.5 * 3.0,+ FilterKind::BlackmanHarris => 1.5 * 2.0,+ };+ assert!((table[1022] - (0.5 + support * 0.5)).abs() < 1e-5, "{kind:?} upper end {}", table[1022]);+ assert!((table[0] - (0.5 - support * 0.5)).abs() < 1e-5, "{kind:?} lower end {}", table[0]);+ assert!((table[511] - 0.5).abs() < 1e-6, "{kind:?} centre");+ }+ }++ #[test]+ fn table_is_symmetric_about_the_pixel_centre() {+ for kind in KINDS {+ let table = build_filter_table(kind, 1.5);+ for offset in 0..=511 {+ let upper = table[511 + offset] - 0.5;+ let lower = 0.5 - table[511 - offset];+ assert!((upper - lower).abs() < 1e-6, "{kind:?} offset {offset}");+ }+ }+ }++ #[test]+ fn inverse_cdf_is_monotonic() {+ for kind in KINDS {+ let table = build_filter_table(kind, 1.5);+ for pair in table[..1023].windows(2) {+ assert!(pair[1] >= pair[0], "{kind:?} decreases from {} to {}", pair[0], pair[1]);+ }+ }+ }++ #[test]+ fn sampling_the_table_reproduces_the_normalised_filter() {+ // The fraction of unit random numbers that land inside [-w/2, w/2] of the pixel centre must equal the+ // integral of the filter over that interval divided by its total integral.+ for kind in KINDS {+ let filter_width = 1.5f32;+ let table = build_filter_table(kind, filter_width);+ let support_width = match kind {+ FilterKind::Gaussian => filter_width * 3.0,+ FilterKind::BlackmanHarris => filter_width * 2.0,+ };+ let half_support = support_width * 0.5;+ let steps = 20000;+ let integral = |limit: f64| -> f64 {+ let mut sum = 0.0f64;+ for step in 0..steps {+ let position = (step as f64 + 0.5) / steps as f64 * limit;+ sum += filter_function(kind, position as f32, support_width) as f64;+ }+ sum * limit / steps as f64+ };+ let total = integral(half_support as f64);+ let inner_limit = 0.5f64;+ let expected_mass = integral(inner_limit) / total;+ let low = (0.5 - inner_limit) as f32;+ let high = (0.5 + inner_limit) as f32;+ let in_range = (0..100_000)+ .map(|index| read_linear(&table, (index as f32 + 0.5) / 100_000.0))+ .filter(|&position| position >= low && position <= high)+ .count() as f64+ / 100_000.0;+ assert!((in_range - expected_mass).abs() < 0.01, "{kind:?} mass {in_range} vs {expected_mass}");+ }+ }++ #[test]+ fn width_only_scales_the_offset_from_the_pixel_centre() {+ for kind in KINDS {+ let unit = build_filter_table(kind, 1.0);+ let wide = build_filter_table(kind, 1.5);+ for index in 0..FILTER_TABLE_SIZE - 1 {+ let scaled = 0.5 + (unit[index] - 0.5) * 1.5;+ assert!((scaled - wide[index]).abs() < 2e-5, "{kind:?} entry {index}");+ }+ }+ }++ #[test]+ fn wgsl_constants_match_the_host_tables() {+ let source = include_str!("filter.wgsl");+ assert!(source.contains(&format!("const FLT_TABLE_SIZE: u32 = {}u;", FILTER_TABLE_SIZE)));+ let offset = crate::cycles::CYCLES_LUT_WORDS.len();+ assert!(source.contains(&format!("const FLT_TABLE_GAUSSIAN_OFFSET: u32 = {}u;", offset)));+ assert!(source.contains(&format!(+ "const FLT_TABLE_BLACKMAN_HARRIS_OFFSET: u32 = {}u;",+ offset + FILTER_TABLE_SIZE+ )));+ }+}diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rsindex f8c39cc3..868c5a94 100644--- a/packages/render-native/src/cycles/mod.rs+++ b/packages/render-native/src/cycles/mod.rs@@ -1,5 +1,7 @@+mod filter_table;mod luts;+pub(crate) use filter_table::unit_filter_table_words;pub(crate) use luts::CYCLES_LUT_WORDS;use napi::Result;diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rsindex 033c2a03..ae58b128 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, CYCLES_LUT_WORDS};+use crate::cycles::{check_counts_match_kernel_params, specialize_cycles_kernel, 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,@@ -118,7 +118,9 @@ fn get_cached_device() -> Result<(wgpu::Device, wgpu::Queue, String, String, Strdevice.set_device_lost_callback(move |_reason, _message| {lost_flag.store(true, Ordering::SeqCst);});- let lut_bytes: &[u8] = bytemuck::cast_slice(&CYCLES_LUT_WORDS[..]);+ let mut lut_words: Vec<u32> = CYCLES_LUT_WORDS.to_vec();+ lut_words.extend(unit_filter_table_words());+ let lut_bytes: &[u8] = bytemuck::cast_slice(&lut_words);let lut_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {label: Some("cycles LUT binding 12"),contents: lut_bytes,@@ -299,7 +301,7 @@ fn create_cycles_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayo];layout_entries.extend((2..=10).map(|binding| storage_entry(binding, true)));layout_entries.push(storage_entry(11, false)); // film_accumulation (read_write)- layout_entries.push(storage_entry(12, true)); // cycles_lut (read-only, 118 848 bytes)+ layout_entries.push(storage_entry(12, true)); // cycles_lut (read-only: static LUTs, then the two pixel filter tables)device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {label: Some("cycles path tracer"),entries: &layout_entries,diff --git a/tests/native-filter.test.js b/tests/native-filter.test.jsnew file mode 100644index 00000000..00ded7ab--- /dev/null+++ b/tests/native-filter.test.js@@ -0,0 +1,31 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { validateFilterOptions, validatePackOptions } from '../packages/render-native/pack-input-v2.mjs';++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]) {+ assert.doesNotThrow(() => validateFilterOptions({ filterType }, 'test'), String(filterType));+ }+ for (const filterWidth of [undefined, 0.01, 1, 1.5, 16]) {+ assert.doesNotThrow(() => validateFilterOptions({ filterWidth }, 'test'), String(filterWidth));+ }+ assert.doesNotThrow(() => validatePackOptions({ filterType: 'blackman-harris', filterWidth: 1.5 }, 'test'));+});++test('pixel filter options reject an unknown filter and a width outside 0.01 to 16', () => {+ for (const filterType of ['tent', 'Box', 3, -1, null, {}]) {+ assert.throws(+ () => validateFilterOptions({ filterType }, 'test'),+ /`filterType` must be "box" \(default\), "gaussian" or "blackman-harris"/,+ String(filterType)+ );+ }+ for (const filterWidth of [0, -1, 0.001, 17, Number.NaN, Number.POSITIVE_INFINITY, '1.5', null]) {+ assert.throws(+ () => validateFilterOptions({ filterWidth }, 'test'),+ /`filterWidth` must be a number of pixels from 0.01 to 16/,+ String(filterWidth)+ );+ }+ assert.throws(() => validatePackOptions({ filterType: 'tent' }, 'test'), /`filterType`/);+});