Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Render sphere lights as spheres in the Cycles reference script (#1040)

Nguyen Xuan An2903d312bd26
diff --git a/bench/cycles-parity/make-sphere-light-scenes.mjs b/bench/cycles-parity/make-sphere-light-scenes.mjs
new file mode 100644
index 00000000..58d8b831
--- /dev/null
+++ b/bench/cycles-parity/make-sphere-light-scenes.mjs
@@ -0,0 +1,87 @@
+// Writes the scenes that isolate a sphere light (a point light with a radius) from an exported `lit-interior` scene (#1040):
+// a bare room with one lamp, and the same lamp inside a small open-bottomed shade, with the shade seen or hidden by shadow rays.
+// node bench/cycles-parity/make-sphere-light-scenes.mjs <exportedSceneJson> <outputDirectory>
+// Run it with --grey-diffuse on both renderers so only the light differs. A shade part carries `rayVisibility: { shadow: false }`
+// when hidden from shadow rays; trace-native.mjs needs --instancing to read it.
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+
+const ROOM_PART_COUNT = 5;
+const LAMP_POSITION = [0, 1.6, -0.5];
+const LAMP_INTENSITY = 8;
+const SHADE_WALL_THICKNESS = 0.02;
+const SHADE_CLEARANCE_BELOW_LAMP = 0.25;
+const SHADE_CLEARANCE_ABOVE_LAMP = 0.25;
+
+function createBoxPart(name, center, size, materialIndex, rayVisibility) {
+ const part = {
+ name,
+ geometry: 0,
+ matrix: [size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1],
+ material: materialIndex,
+ };
+ if (rayVisibility) {
+ part.rayVisibility = rayVisibility;
+ }
+ return part;
+}
+
+// Four walls and a lid, open at the bottom, centred on the lamp.
+function createShadeParts(halfWidth, rayVisibility) {
+ const [lampX, lampY, lampZ] = LAMP_POSITION;
+ const bottom = lampY - SHADE_CLEARANCE_BELOW_LAMP;
+ const top = lampY + SHADE_CLEARANCE_ABOVE_LAMP;
+ const height = top - bottom;
+ const middleY = (top + bottom) / 2;
+ const span = 2 * halfWidth + 2 * SHADE_WALL_THICKNESS;
+ return [
+ createBoxPart('shade-lid', [lampX, top + SHADE_WALL_THICKNESS / 2, lampZ], [span, SHADE_WALL_THICKNESS, span], 0, rayVisibility),
+ createBoxPart('shade-left', [lampX - halfWidth - SHADE_WALL_THICKNESS / 2, middleY, lampZ], [SHADE_WALL_THICKNESS, height, span], 0, rayVisibility),
+ createBoxPart('shade-right', [lampX + halfWidth + SHADE_WALL_THICKNESS / 2, middleY, lampZ], [SHADE_WALL_THICKNESS, height, span], 0, rayVisibility),
+ createBoxPart('shade-back', [lampX, middleY, lampZ - halfWidth - SHADE_WALL_THICKNESS / 2], [span, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
+ createBoxPart('shade-front', [lampX, middleY, lampZ + halfWidth + SHADE_WALL_THICKNESS / 2], [span, height, SHADE_WALL_THICKNESS], 0, rayVisibility),
+ ];
+}
+
+function createVariant(baseDescription, id, lampRadius, shade) {
+ const roomParts = baseDescription.parts.slice(0, ROOM_PART_COUNT);
+ const shadeParts = shade ? createShadeParts(shade.halfWidth, shade.hiddenFromShadowRays ? { shadow: false } : undefined) : [];
+ return {
+ ...baseDescription,
+ id,
+ parts: [...roomParts, ...shadeParts],
+ environment: {
+ ...baseDescription.environment,
+ pointLights: [{ position: LAMP_POSITION, color: [1, 1, 1], intensity: LAMP_INTENSITY, radius: lampRadius, castShadow: true }],
+ spotLights: [],
+ areaLights: [],
+ },
+ };
+}
+
+function listVariants() {
+ const variants = [];
+ for (const radius of [0, 0.05, 0.18, 0.5]) {
+ variants.push({ id: `bare-r${radius}`, radius, shade: null });
+ }
+ for (const radius of [0, 0.18]) {
+ variants.push({ id: `enclosed-r${radius}`, radius, shade: { halfWidth: 0.3, hiddenFromShadowRays: false } });
+ variants.push({ id: `enclosed-hidden-r${radius}`, radius, shade: { halfWidth: 0.3, hiddenFromShadowRays: true } });
+ }
+ variants.push({ id: 'poking-r0.18', radius: 0.18, shade: { halfWidth: 0.12, hiddenFromShadowRays: false } });
+ variants.push({ id: 'poking-hidden-r0.18', radius: 0.18, shade: { halfWidth: 0.12, hiddenFromShadowRays: true } });
+ return variants;
+}
+
+const argumentList = process.argv.slice(2);
+if (argumentList.length < 2) {
+ throw new RangeError('Usage: node bench/cycles-parity/make-sphere-light-scenes.mjs <exportedSceneJson> <outputDirectory>');
+}
+const baseDescription = JSON.parse(await readFile(resolve(argumentList[0]), 'utf8'));
+const scenesDirectory = join(resolve(argumentList[1]), 'scenes');
+await mkdir(scenesDirectory, { recursive: true });
+for (const variant of listVariants()) {
+ const description = createVariant(baseDescription, variant.id, variant.radius, variant.shade);
+ await writeFile(join(scenesDirectory, `${variant.id}.json`), JSON.stringify(description));
+ console.log(variant.id);
+}
diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.py
index ef64f012..cbea8497 100644
--- a/bench/cycles-parity/render-cycles.py
+++ b/bench/cycles-parity/render-cycles.py
@@ -18,6 +18,9 @@ WATTS_PER_AREA_INTENSITY = math.pi
SUN_ANGULAR_DIAMETER = math.radians(1.0)
ENVIRONMENT_ROTATION_Z = -math.pi / 2.0
PART_ID_STEPS = 64
+# Set by --soft-falloff. Blender 4 and later build a point or spot light with a radius as an oriented disk while Light.use_soft_falloff
+# is on (the default) and as a sphere while it is off. Cook models the sphere, so the default here is off; None keeps the Blender default.
+soft_falloff_setting = None
Y_UP_TO_Z_UP = Matrix((
(1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, -1.0, 0.0),
@@ -54,7 +57,7 @@ def parse_cli_arguments():
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] [--transparent-bounces 8] [--seed 1] [--width 960] [--height 540] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--keep-exr] [--part-ids] [--grey-diffuse] [--z-depth] [--depth-samples 64] [--denoise none|oidn-gpu|oidn-cpu] [--f-stop 2.8 [--focus-distance m] [--aperture-blades 0|3..64] [--aperture-rotation degrees] [--sensor-width 36]]")
+ raise ValueError("Usage: blender -b --factory-startup --python bench/cycles-parity/render-cycles.py -- <sceneJsonPath> <outputPrefix> [--samples 256] [--bounces 8] [--transparent-bounces 8] [--seed 1] [--width 960] [--height 540] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--keep-exr] [--part-ids] [--grey-diffuse] [--soft-falloff default|on|off] [--z-depth] [--depth-samples 64] [--denoise none|oidn-gpu|oidn-cpu] [--f-stop 2.8 [--focus-distance m] [--aperture-blades 0|3..64] [--aperture-rotation degrees] [--sensor-width 36]]")
return {
"scene_json_path": os.path.abspath(argument_list[0]),
"output_prefix": os.path.abspath(argument_list[1]),
@@ -81,6 +84,7 @@ def parse_cli_arguments():
"aperture_blades": int(read_flag_value(argument_list, "--aperture-blades", "0")),
"aperture_rotation": float(read_flag_value(argument_list, "--aperture-rotation", "0")),
"sensor_width": float(read_flag_value(argument_list, "--sensor-width", "36")),
+ "soft_falloff": {"default": None, "on": True, "off": False}[read_flag_value(argument_list, "--soft-falloff", "off")],
}
@@ -380,11 +384,17 @@ def attach_light_receivers(light_object, receiver_names):
light_object.light_linking.receiver_collection = receiver_collection
+def apply_soft_falloff_setting(light_data):
+ if soft_falloff_setting is not None:
+ light_data.use_soft_falloff = soft_falloff_setting
+
+
def add_spot_light(scene, light_index, spot_entry):
light_data = bpy.data.lights.new(f"Spot-{light_index}", "SPOT")
light_data.energy = spot_entry["intensity"] * WATTS_PER_POINT_INTENSITY
light_data.color = spot_entry["color"]
light_data.shadow_soft_size = spot_entry["radius"]
+ apply_soft_falloff_setting(light_data)
light_data.spot_size = 2.0 * spot_entry["angle"]
light_data.spot_blend = spot_entry["penumbra"]
spot_object = bpy.data.objects.new(f"Spot-{light_index}", light_data)
@@ -442,6 +452,7 @@ def build_scene_lights(scene, environment_entry):
point_data.energy = point_entry["intensity"] * WATTS_PER_POINT_INTENSITY
point_data.color = point_entry["color"]
point_data.shadow_soft_size = point_entry["radius"]
+ apply_soft_falloff_setting(point_data)
point_object = bpy.data.objects.new(f"Point-{light_index}", point_data)
point_object.location = convert_position_to_blender(point_entry["position"])
scene.collection.objects.link(point_object)
@@ -701,6 +712,8 @@ def main():
build_started = time.perf_counter()
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
+ global soft_falloff_setting
+ soft_falloff_setting = options["soft_falloff"]
build_scene_objects(scene, description)
build_world_shader(scene, description["world"], repository_root)
build_scene_lights(scene, description["environment"])
diff --git a/bench/cycles-parity/run-sphere-light-parity.py b/bench/cycles-parity/run-sphere-light-parity.py
new file mode 100644
index 00000000..3f329a00
--- /dev/null
+++ b/bench/cycles-parity/run-sphere-light-parity.py
@@ -0,0 +1,202 @@
+"""Sphere light parity matrix (#1040): Cook against Blender Cycles on small scenes with one lamp that has a radius.
+
+Run from the repository root on a machine with Blender 5.3, Node, a GPU and the built render-native addon:
+ uv run --no-project --with numpy python bench/cycles-parity/run-sphere-light-parity.py <outputDirectory> [options]
+
+It exports `lit-interior`, writes the scenes of make-sphere-light-scenes.mjs, renders each one with Cycles (grey diffuse
+everywhere) and with Cook, and prints one result line per scene. Options:
+ --samples 1024 --width 480 --height 270 --bounces 8
+ --soft-falloff default,off Cycles `use_soft_falloff` settings to render (default: the Blender default and off)
+ --scenes a,b only these scenes
+ --label before name of the Cook run in the output
+ --repeat-cycles-seed2 also render Cycles with seed 2 for the seed-to-seed floor
+ --reference-scenes a,b also run these scenes of bench/reference/scenes.js with their own materials
+ --no-sphere-scenes skip the sphere light scenes
+"""
+import glob
+import hashlib
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import numpy
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+from compare import compare_image_pair, load_linear_rgb_image # noqa: E402
+
+sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+DIRECT_ONLY_SCENES = ("bare-r0", "bare-r0.18", "enclosed-r0", "enclosed-r0.18", "enclosed-hidden-r0", "enclosed-hidden-r0.18")
+INSTANCED_CONTROL_SCENES = ("enclosed-r0.18", "poking-r0.18")
+HIDDEN_PREFIXES = ("enclosed-hidden", "poking-hidden")
+SPHERE_SCENE_PREFIXES = ("bare-", "enclosed-", "poking-")
+
+
+def read_flag(argument_list, flag_name, fallback):
+ if flag_name not in argument_list:
+ return fallback
+ return argument_list[argument_list.index(flag_name) + 1]
+
+
+def find_blender():
+ found = shutil.which("blender")
+ if found:
+ return found
+ patterns = (
+ os.path.join(os.path.expanduser("~"), "blender", "blender"),
+ os.path.join(os.sep + "opt", "*", "blender"),
+ os.path.join(os.path.expanduser("~"), "*", "blender"),
+ )
+ for pattern in patterns:
+ matches = glob.glob(pattern)
+ if matches:
+ return matches[0]
+ raise RuntimeError("Blender was not found on this machine.")
+
+
+def run(command):
+ print("RUN", " ".join(command), flush=True)
+ completed = subprocess.run(command, cwd=os.getcwd(), capture_output=True, text=True)
+ if completed.returncode != 0:
+ print(completed.stdout[-1500:], completed.stderr[-1500:], flush=True)
+ raise RuntimeError(f"command failed with {completed.returncode}")
+
+
+def render_cycles(blender, scene_path, prefix, options, bounces, seed, soft_falloff, grey_diffuse=True):
+ if os.path.exists(f"{prefix}.npy"):
+ return
+ command = [blender, "-b", "--factory-startup", "--python", os.path.join(HERE, "render-cycles.py"), "--", scene_path, prefix,
+ "--samples", str(options["samples"]), "--bounces", str(bounces), "--seed", str(seed),
+ "--width", str(options["width"]), "--height", str(options["height"]),
+ "--soft-falloff", soft_falloff]
+ if grey_diffuse:
+ command.append("--grey-diffuse")
+ run(command)
+
+
+def render_cook(scene_path, prefix, options, bounces, instancing, grey_diffuse=True):
+ command = ["node", os.path.join(HERE, "trace-native.mjs"), scene_path, prefix, "--kernel", "cycles",
+ "--samples", str(options["samples"]), "--bounces", str(bounces), "--seed", "1",
+ "--width", str(options["width"]), "--height", str(options["height"]),
+ "--firefly-clamp", "1000000000", "--noise-threshold", "0"]
+ if grey_diffuse:
+ command.append("--grey-diffuse")
+ if instancing:
+ command.append("--instancing")
+ run(command)
+
+
+def tile_ratio_rows(reference_rgb, candidate_rgb, grid=8):
+ height, width = reference_rgb.shape[0], reference_rgb.shape[1]
+ rows = []
+ for row in range(grid):
+ cells = []
+ for column in range(grid):
+ rows_slice = slice(row * height // grid, (row + 1) * height // grid)
+ columns_slice = slice(column * width // grid, (column + 1) * width // grid)
+ reference_sum = float(numpy.sum(reference_rgb[rows_slice, columns_slice]))
+ cells.append(round(float(numpy.sum(candidate_rgb[rows_slice, columns_slice])) / reference_sum, 3) if reference_sum > 0 else None)
+ rows.append(cells)
+ return rows
+
+
+def summarize(reference_path, candidate_path):
+ comparison = compare_image_pair(load_linear_rgb_image(reference_path), load_linear_rgb_image(candidate_path), include_flip=False)
+ tile_grid = comparison["tileGrid8x8"]
+ return {
+ "tileRatios": tile_ratio_rows(load_linear_rgb_image(reference_path), load_linear_rgb_image(candidate_path)),
+ "meanRatio": comparison["channelMeanRatio"],
+ "relMse": round(comparison["relMse"], 6),
+ "tilesWithinFivePercent": tile_grid["withinFivePercentCount"],
+ "tilesEligible": tile_grid["eligibleTileCount"],
+ "tileMinMax": [tile_grid["minRatio"], tile_grid["maxRatio"]],
+ }
+
+
+def sha256_of(path):
+ with open(path, "rb") as handle:
+ return hashlib.sha256(handle.read()).hexdigest()
+
+
+def run_pair(blender, scene_path, name, suffix, bounces, options, falloff_settings, label, instancing, grey_diffuse, results):
+ cook_prefix = os.path.join(options["output_directory"], "renders", f"{name}{suffix}-{label}")
+ render_cook(scene_path, cook_prefix, options, bounces, instancing, grey_diffuse)
+ for setting in falloff_settings:
+ cycles_prefix = os.path.join(options["output_directory"], "renders", f"{name}{suffix}-cycles-{setting}")
+ render_cycles(blender, scene_path, cycles_prefix, options, bounces, 1, setting, grey_diffuse)
+ key = f"{name}{suffix}|{setting}"
+ results[key] = summarize(f"{cycles_prefix}.npy", f"{cook_prefix}.npy")
+ print("PARITY", key, json.dumps(results[key]), flush=True)
+ results[f"{name}{suffix}|cookSha256"] = sha256_of(f"{cook_prefix}.npy")
+
+
+def run_sphere_scenes(blender, scene_names, options, falloff_settings, label, results):
+ for name in scene_names:
+ scene_path = os.path.join(options["output_directory"], "scenes", f"{name}.json")
+ hidden = name.startswith(HIDDEN_PREFIXES)
+ bounce_counts = [options["bounces"], 1] if name in DIRECT_ONLY_SCENES else [options["bounces"]]
+ for bounces in bounce_counts:
+ suffix = "" if bounces == options["bounces"] else f"-b{bounces}"
+ run_pair(blender, scene_path, name, suffix, bounces, options, falloff_settings, label, hidden, True, results)
+ if name in INSTANCED_CONTROL_SCENES:
+ run_pair(blender, scene_path, name, "-instanced", options["bounces"], options, falloff_settings, label, True, True, results)
+
+
+def run_reference_scenes(blender, scene_names, options, falloff_settings, label, results):
+ for name in scene_names:
+ run(["node", os.path.join(HERE, "export-scene.mjs"), options["output_directory"], "--scene", name])
+ scene_path = os.path.join(options["output_directory"], "scenes", f"{name}.json")
+ run_pair(blender, scene_path, name, "", options["bounces"], options, falloff_settings, label, False, False, results)
+
+
+def run_seed_floor(blender, scene_names, options, falloff_settings):
+ floor = {}
+ for name in scene_names:
+ scene_path = os.path.join(options["output_directory"], "scenes", f"{name}.json")
+ for setting in falloff_settings:
+ first = os.path.join(options["output_directory"], "renders", f"{name}-cycles-{setting}")
+ second = f"{first}-seed2"
+ render_cycles(blender, scene_path, second, options, options["bounces"], 2, setting)
+ key = f"{name}|{setting}|seed2VsSeed1"
+ floor[key] = summarize(f"{first}.npy", f"{second}.npy")
+ print("FLOOR", key, json.dumps(floor[key]), flush=True)
+ return floor
+
+
+def main():
+ argument_list = sys.argv[1:]
+ options = {
+ "output_directory": os.path.abspath(argument_list[0]),
+ "samples": int(read_flag(argument_list, "--samples", "1024")),
+ "width": int(read_flag(argument_list, "--width", "480")),
+ "height": int(read_flag(argument_list, "--height", "270")),
+ "bounces": int(read_flag(argument_list, "--bounces", "8")),
+ }
+ falloff_settings = read_flag(argument_list, "--soft-falloff", "default,off").split(",")
+ label = read_flag(argument_list, "--label", "cook")
+ reference_names = [name for name in read_flag(argument_list, "--reference-scenes", "").split(",") if name]
+ blender = find_blender()
+ results = {}
+ os.makedirs(os.path.join(options["output_directory"], "renders"), exist_ok=True)
+ if "--no-sphere-scenes" not in argument_list:
+ run(["node", os.path.join(HERE, "export-scene.mjs"), options["output_directory"], "--scene", "lit-interior"])
+ base_scene = os.path.join(options["output_directory"], "scenes", "lit-interior.json")
+ run(["node", os.path.join(HERE, "make-sphere-light-scenes.mjs"), base_scene, options["output_directory"]])
+ scene_names = sorted(os.path.basename(path)[:-5] for path in glob.glob(os.path.join(options["output_directory"], "scenes", "*.json")) if os.path.basename(path).startswith(SPHERE_SCENE_PREFIXES))
+ wanted = read_flag(argument_list, "--scenes", "")
+ if wanted:
+ scene_names = [name for name in scene_names if name in wanted.split(",")]
+ run_sphere_scenes(blender, scene_names, options, falloff_settings, label, results)
+ if "--repeat-cycles-seed2" in argument_list:
+ results.update(run_seed_floor(blender, scene_names, options, falloff_settings))
+ run_reference_scenes(blender, reference_names, options, falloff_settings, label, results)
+ with open(os.path.join(options["output_directory"], f"sphere-light-{label}.json"), "w", encoding="utf-8") as handle:
+ json.dump(results, handle, indent=1)
+ print("DONE", len(results))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/changes/1040.md b/changes/1040.md
new file mode 100644
index 00000000..01c7e8c3
--- /dev/null
+++ b/changes/1040.md
@@ -0,0 +1 @@
+- The Cycles reference script renders point and spot lights with a radius as spheres (Soft Falloff off, which Cook models) instead of Blender's default oriented disk, so Cook and Cycles agree on sphere lights again, and `render-cycles.py --soft-falloff default|on|off` picks the other behaviour (#1040).
diff --git a/packages/render-native/src/cycles/mod.rs b/packages/render-native/src/cycles/mod.rs
index 0942b714..4ed11b9d 100644
--- a/packages/render-native/src/cycles/mod.rs
+++ b/packages/render-native/src/cycles/mod.rs
@@ -1144,6 +1144,24 @@ mod tests {
assert!(kernel.contains("texture_decode_filtered(texture_fetch_texel(desc, ix, iy, format), format)"));
}
+ /// A point or spot light with a radius is a sphere (Blender's `use_soft_falloff` off, #1040): outside it Cook samples the cone
+ /// of the sphere and a path that hits it uses the same cone pdf, inside it samples the surface, and the packed radiance is
+ /// intensity over pi r^2 so the power does not change with the radius. The Cycles reference script switches
+ /// `use_soft_falloff` off to render the same light; with it on Cycles uses an oriented disk this kernel does not model.
+ #[test]
+ fn a_light_with_a_radius_is_a_sphere_with_one_pdf_for_sampling_and_hits() {
+ let kernel = assemble_cycles_kernel().expect("the kernel assembles");
+ let sampler_start = kernel.find("fn lgt_sample_point_or_spot_light(").expect("the point and spot sampler exists");
+ let sampler_end = sampler_start + kernel[sampler_start..].find("\nfn lgt_sample_area_light(").expect("the sampler ends");
+ let sampler = &kernel[sampler_start..sampler_end];
+ assert!(sampler.contains("lgt_sample_uniform_cone(center_dir, one_minus_cos_sphere, rand_uv, &cos_theta)"));
+ assert!(sampler.contains("pdf_solid_angle = 1.0 / max(TWO_PI * one_minus_cos_sphere, 1.0e-30)"));
+ assert!(sampler.contains("lgt_sample_uniform_sphere(rand_uv)"));
+ assert!(kernel.contains("lgt_sphere_solid_angle_pdf(dist_sq, light.radius, hit_t, ray_origin, ray_dir, light.position)"));
+ assert!(kernel.contains("if (hit_t <= t_min || hit_t >= t_max) {"));
+ assert!(!kernel.contains("disk_light_sample"));
+ }
+
#[test]
fn the_bootstrap_entry_samples_alpha_through_the_shared_sampler() {
let bootstrap = include_str!("bootstrap_main.wgsl");
diff --git a/tests/cycles-sphere-light-parity.test.js b/tests/cycles-sphere-light-parity.test.js
new file mode 100644
index 00000000..86c62bf0
--- /dev/null
+++ b/tests/cycles-sphere-light-parity.test.js
@@ -0,0 +1,65 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+
+import { buildNativeInput, findNativeAddon, traceNative } from '../packages/render-native/index.mjs';
+import { box } from '../src/geometry.js';
+import { createCamera } from '../src/path-tracer.js';
+import * as pack from '../src/path-tracer-gpu-pack.js';
+import { buildTraceScene } from '../src/path-tracer-scene.js';
+
+const skipWithoutAddon = findNativeAddon() === null ? 'the native addon is not built' : false;
+const SIZE = 16;
+const FLOOR_ALBEDO = 0.8;
+const LAMP_HEIGHT = 2;
+const LAMP_INTENSITY = 8;
+const cameraDescription = { eye: [0, 6, 0], target: [0, 0, 0], up: [0, 0, -1], fov: 30 };
+
+function floorPart() {
+ const matrix = new Float32Array([20, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 20, 0, 0, -0.05, 0, 1]);
+ const material = { tag: 'surface', metallic: 0, roughness: 1, specular: 0, emission: 0, color: [FLOOR_ALBEDO, FLOOR_ALBEDO, FLOOR_ALBEDO] };
+ return { name: 'floor', geometry: box(0, 1), matrix, material };
+}
+
+function renderFloorUnderLamp(radius) {
+ const environment = {
+ keyColor: [0, 0, 0],
+ lightDirection: [0, 1, 0],
+ ambientIntensity: 0,
+ fillIntensity: 0,
+ pointLights: [{ position: [0, LAMP_HEIGHT, 0], color: [1, 1, 1], intensity: LAMP_INTENSITY, radius, castShadow: true }],
+ };
+ const scene = buildTraceScene([floorPart()], environment);
+ const camera = createCamera(cameraDescription, SIZE, SIZE);
+ const input = buildNativeInput(scene, camera, { width: SIZE, height: SIZE, samples: 256, bounces: 2, seed: 1 }, pack);
+ return traceNative(input, { width: SIZE, height: SIZE, samples: 256, bounces: 2, kernel: 'cycles' }).rgba;
+}
+
+function centreRadiance(rgba) {
+ let sum = 0;
+ const first = SIZE / 2 - 2;
+ for (let row = first; row < first + 4; row++) {
+ for (let column = first; column < first + 4; column++) {
+ sum += rgba[(row * SIZE + column) * 4 + 1];
+ }
+ }
+ return sum / 16;
+}
+
+test('the Cycles reference script renders point and spot lights as spheres unless asked otherwise', () => {
+ const source = readFileSync(new URL('../bench/cycles-parity/render-cycles.py', import.meta.url), 'utf8');
+ assert.match(source, /read_flag_value\(argument_list, "--soft-falloff", "off"\)/, 'the default turns Light.use_soft_falloff off');
+ assert.match(source, /light_data\.use_soft_falloff = soft_falloff_setting/, 'the setting reaches the light');
+ const callCount = source.split('apply_soft_falloff_setting(').length - 1;
+ assert.equal(callCount, 3, 'the definition and one call each for point lights and spot lights');
+});
+
+// A sphere light of intensity I seen from a distance d beyond its radius lights a facing diffuse surface with I / d^2, whatever
+// its radius, so the floor under the lamp is albedo / pi * I / d^2 for every radius (power stays fixed as the radius grows).
+for (const radius of [0, 0.18, 0.5]) {
+ test(`the native cycles kernel keeps the power of a point light of radius ${radius} m`, { skip: skipWithoutAddon }, () => {
+ const expected = (FLOOR_ALBEDO / Math.PI) * (LAMP_INTENSITY / (LAMP_HEIGHT * LAMP_HEIGHT));
+ const measured = centreRadiance(renderFloorUnderLamp(radius));
+ assert.ok(Math.abs(measured / expected - 1) < 0.03, `floor radiance ${measured} against the closed form ${expected}`);
+ });
+}