3D engine that AI agents drive
Isolate the metal floor's direct-light offset: the script capped the sky after the lookup (#1104)
Nguyen Xuan An97d0b5139390
diff --git a/bench/cycles-parity/floor-closed-form.py b/bench/cycles-parity/floor-closed-form.pynew file mode 100644index 00000000..9dbe8706--- /dev/null+++ b/bench/cycles-parity/floor-closed-form.py@@ -0,0 +1,133 @@+"""Closed-form pixel values of the top-down floor scenes against what Cycles and Cook measured (#1104).++ uv run --no-project --with numpy python bench/cycles-parity/floor-closed-form.py <dataDirectory> [--tags td-sun,td-sky,...]++The floor is Lambert with albedo 0.8, the camera looks straight down and nothing shadows the floor, so a pixel is+ sun: albedo / pi * sunColor * cos(angle between the sun and the floor normal)+ sky: albedo / pi * the integral of sky radiance times cosine over the upper hemisphere (a flat sky of radiance L gives albedo * L).+For the Kloofendal map the integral is taken twice from the Radiance file's own bytes: with the texel decoded as mantissa times+2^(exponent-136) (what Cook's parser and the Radiance format give) and as (mantissa + 0.5) times 2^(exponent-136).+Prints, per tag, the closed forms, each renderer's mean over the seeds with its standard error, and each mean over the closed form.+"""+import glob+import math+import os+import sys++import numpy++sys.stdout.reconfigure(encoding="utf-8", errors="replace")++ALBEDO = 0.8+SUN_COLOR = numpy.array([3.0, 2.8, 2.5])+SUN_DIRECTION = numpy.array([-3.0, 6.0, 4.0])+RADIANCE_LIMIT = 16.0+SKY_FILE = "public/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr"+POLAR_STEPS = 200000+++def decode_radiance_bytes(path):+ with open(path, "rb") as handle:+ content = handle.read()+ header_end = content.index(b"\n\n") + 2+ resolution_end = content.index(b"\n", header_end)+ _, height_text, _, width_text = content[header_end:resolution_end].decode("ascii").split()+ height = int(height_text)+ width = int(width_text)+ position = resolution_end + 1+ rgbe = numpy.zeros((height, width, 4), dtype=numpy.uint8)+ for row in range(height):+ position += 4+ for channel in range(4):+ column = 0+ while column < width:+ count = content[position]+ if count > 128:+ run = count - 128+ rgbe[row, column:column + run, channel] = content[position + 1]+ position += 2+ else:+ rgbe[row, column:column + count, channel] = numpy.frombuffer(content[position + 1:position + 1 + count], dtype=numpy.uint8)+ position += 1 + count+ column += run if count > 128 else count+ return rgbe+++def decode_texels(rgbe, mantissa_offset):+ scale = numpy.where(rgbe[..., 3] == 0, 0.0, 2.0 ** (rgbe[..., 3].astype(numpy.float64) - 136.0))+ texels = (rgbe[..., :3].astype(numpy.float64) + mantissa_offset) * scale[..., None]+ return numpy.minimum(texels, RADIANCE_LIMIT)+++def cosine_irradiance_over_pi(texels):+ """Hemisphere integral of radiance times cosine, over pi, for a map whose up axis is the row axis (bilinear in rows, row means in azimuth)."""+ height = texels.shape[0]+ row_means = texels.mean(axis=1)+ polar = (numpy.arange(POLAR_STEPS) + 0.5) / POLAR_STEPS * (math.pi / 2.0)+ texel_y = polar / math.pi * height - 0.5+ lower = numpy.floor(texel_y).astype(int)+ fraction = (texel_y - lower)[:, None]+ low_row = row_means[numpy.clip(lower, 0, height - 1)]+ high_row = row_means[numpy.clip(lower + 1, 0, height - 1)]+ radiance = low_row * (1.0 - fraction) + high_row * fraction+ weight = (numpy.cos(polar) * numpy.sin(polar) * (math.pi / 2.0 / POLAR_STEPS))[:, None]+ return 2.0 * (radiance * weight).sum(axis=0)+++def sun_pixel():+ normal_cosine = SUN_DIRECTION[1] / numpy.linalg.norm(SUN_DIRECTION)+ return ALBEDO / math.pi * SUN_COLOR * normal_cosine+++def closed_forms():+ rgbe = decode_radiance_bytes(SKY_FILE)+ sky_plain = ALBEDO * cosine_irradiance_over_pi(decode_texels(rgbe, 0.0))+ sky_half = ALBEDO * cosine_irradiance_over_pi(decode_texels(rgbe, 0.5))+ flat_a = numpy.full(3, ALBEDO * 128 / 256)+ flat_b = numpy.full(3, ALBEDO * 255 / 256)+ return {+ "td-sun": (sun_pixel(), sun_pixel()),+ "td-flat-a": (flat_a, flat_a * 128.5 / 128.0),+ "td-flat-b": (flat_b, flat_b * 255.5 / 255.0),+ "td-const": (numpy.full(3, ALBEDO * 0.5), numpy.full(3, ALBEDO * 0.5)),+ "td-sky": (sky_plain, sky_half),+ "td-both": (sky_plain + sun_pixel(), sky_half + sun_pixel()),+ }+++def seed_means(pattern):+ paths = sorted(glob.glob(pattern))+ if not paths:+ return None+ means = numpy.array([numpy.load(path).astype(numpy.float64).reshape(-1, 3).mean(axis=0) for path in paths])+ error = means.std(axis=0, ddof=1) / math.sqrt(len(paths)) if len(paths) > 1 else numpy.full(3, numpy.nan)+ return means.mean(axis=0), error, len(paths)+++def format_channels(values, digits=5):+ return "[" + ", ".join(f"{value:.{digits}f}" for value in values) + "]"+++def main():+ data_directory = sys.argv[1]+ tags = sys.argv[sys.argv.index("--tags") + 1].split(",") if "--tags" in sys.argv else list(closed_forms())+ forms = closed_forms()+ for tag in tags:+ plain, half = forms[tag.split("@")[0]]+ print(f"{tag}: closed form {format_channels(plain)} with +0.5 texel decode {format_channels(half)}")+ measured = {}+ for side, prefix in (("cycles", "cycles"), ("cook", "cookcycles")):+ found = seed_means(os.path.join(data_directory, f"{prefix}-{tag}-s*.npy"))+ if found is None:+ continue+ mean, error, count = found+ measured[side] = (mean, error)+ print(f" {side:<6} mean {format_channels(mean)} +- {format_channels(error, 6)} ({count} seeds) over closed form {format_channels(mean / plain)} over +0.5 form {format_channels(mean / half)}")+ if len(measured) == 2:+ ratio = measured["cook"][0] / measured["cycles"][0]+ relative = numpy.sqrt((measured["cook"][1] / measured["cook"][0]) ** 2 + (measured["cycles"][1] / measured["cycles"][0]) ** 2)+ print(f" cook over cycles {format_channels(ratio)} +- {format_channels(ratio * relative, 6)}")+++if __name__ == "__main__":+ main()diff --git a/bench/cycles-parity/floor-direct-light-suite.sh b/bench/cycles-parity/floor-direct-light-suite.shnew file mode 100644index 00000000..237a30ee--- /dev/null+++ b/bench/cycles-parity/floor-direct-light-suite.sh@@ -0,0 +1,134 @@+#!/usr/bin/env bash+# Where does the metal floor's direct-light offset between Cook and Cycles come from? (#1104)+# bash bench/cycles-parity/floor-direct-light-suite.sh <dataDirectory> [render|probe|report]...+# render: floor-only variants of the metal scene (sun, flat sky, constant sky, the real sky, both; straight down and from the metal+# camera) with zero bounces on a Lambert floor, on both renderers.+# probe: the sky seen directly (no lighting), and the sky floor under other sampling choices, to say what Cycles does differently.+# report: each mean over its closed form, Cook over Cycles, the sky lookup fits.+# Needs a GPU box with Blender 5.3 (BLENDER_BIN, default ~/blender/blender) and the built addon. Existing images are kept.+set -uo pipefail++repository=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)+data=$(mkdir -p "$1" && cd "$1" && pwd)+shift+blender_binary=${BLENDER_BIN:-$HOME/blender/blender}+uv_binary=${UV_BIN:-$HOME/.local/bin/uv}+width=256+height=144+samples=${SAMPLES:-256}+cd "$repository"++# A tag is <scene>[@<variant>]; the variant picks extra flags for one side.+cycles_flags_for() { # tag+ case "${1#*@}" in+ nosample) echo '--world-property sampling_method="NONE"' ;;+ res4096) echo '--world-property sample_map_resolution=4096' ;;+ nosun) echo '--world-property sun_threshold=0' ;;+ capafter) echo '--radiance-cap after-lookup' ;;+ esac+}++cook_flags_for() { # tag+ case "${1#*@}" in+ esac+}++render_cycles() { # tag seed samples extra...+ local tag=$1 seed=$2 spp=$3+ shift 3+ local prefix="$data/cycles-$tag-s$seed"+ [ -f "$prefix.npy" ] && return 0+ # shellcheck disable=SC2046+ "$blender_binary" -b --factory-startup --python bench/cycles-parity/render-cycles.py -- "$data/scenes/floor-${tag%%@*}.json" "$prefix" \+ --samples "$spp" --seed "$seed" --bounces 0 --width "$width" --height "$height" --grey-diffuse $(cycles_flags_for "$tag") "$@" > "$prefix.log" 2>&1 || echo "cycles $tag $seed failed" >&2+}++render_cook() { # tag seed samples extra...+ local tag=$1 seed=$2 spp=$3+ shift 3+ local prefix="$data/cookcycles-$tag-s$seed"+ [ -f "$prefix.npy" ] && return 0+ # shellcheck disable=SC2046+ node bench/cycles-parity/trace-native.mjs "$data/scenes/floor-${tag%%@*}.json" "$prefix" \+ --kernel cycles --samples "$spp" --seed "$seed" --bounces 0 --width "$width" --height "$height" --grey-diffuse $(cook_flags_for "$tag") "$@" > "$prefix.log" 2>&1 || echo "cook $tag $seed failed" >&2+}++render_variants() { # side entry... entry = tag:seeds+ local side=$1 entry tag seed+ shift+ for entry in "$@"; do+ tag=${entry%%:*}+ for seed in $(seq 1 "${entry##*:}"); do+ "render_$side" "$tag" "$seed" "$samples"+ done+ done+}++both_sides() { # entry...+ render_variants cook "$@" &+ local cook_job=$!+ render_variants cycles "$@"+ wait "$cook_job"+}++stage_render() {+ mkdir -p "$data/scenes" "$data/hdri"+ [ -f "$data/scenes/metal.json" ] || node bench/cycles-parity/export-scene.mjs "$data" --scene metal | tail -1+ "$uv_binary" run --no-project python bench/cycles-parity/make-floor-scenes.py "$data"+ "$blender_binary" --version | head -1+ both_sides td-sun:4 td-flat-a:4 td-flat-b:4 td-const:4 td-sky:8 td-both:8 ob-sun:4 ob-sky:8 ob-both:8+ # Accumulation precision: the same sun-only picture at 32 and at 4096 samples.+ local spp+ for spp in 32 4096; do+ for seed in 1 2; do+ render_cook "td-sun@spp$spp" "$seed" "$spp"+ render_cycles "td-sun@spp$spp" "$seed" "$spp"+ done+ done+ local tag+ for tag in ob-sun ob-sky ob-both; do+ render_cycles "$tag@parts" 1 64 --part-ids+ done+}++stage_probe() {+ # The sky floor in Cycles with the sky found by BSDF sampling only, with a bigger importance map, and with its sun extraction off, and with the radiance limit applied after the lookup (what the script did before #1104).+ render_variants cycles td-sky@nosample:8 td-sky@res4096:8 td-sky@nosun:8 td-both@nosun:8 td-sky@capafter:8 td-both@capafter:8++ # The sky itself: 512 x 288 pictures of the background from level, 45 degrees up and straight up.+ width=512+ height=288+ both_sides sk-h:2 sk-45:2 sk-up:2+ render_variants cycles sk-45@capafter:2+}++fit_sky() { # label cyclesTag cookTag rows+ "$uv_binary" run --no-project --with numpy python bench/cycles-parity/sky-lookup-shift.py --label "$1" \+ --reference "$data/cycles-$2-s*.npy" --candidate "$data/cookcycles-${3}-s*.npy" --sky-rows "$4"+}++stage_report() {+ local tags="td-sun,td-flat-a,td-flat-b,td-const,td-sky,td-both,td-sky@nosample,td-sky@res4096,td-sky@nosun,td-both@nosun,td-sky@capafter,td-both@capafter"+ "$uv_binary" run --no-project --with numpy python bench/cycles-parity/floor-closed-form.py "$data" --tags "$tags"+ local tag+ for tag in ob-sun ob-sky ob-both; do+ "$uv_binary" run --no-project --with numpy python bench/cycles-parity/mean-ratio-seeds.py --label "oblique $tag, floor pixels" \+ --reference "$data/cycles-$tag-s*.npy" --candidate "$data/cookcycles-$tag-s*.npy" --parts "$data/cycles-$tag@parts-s1" | grep -av '^JSON'+ done+ local spp+ for spp in 32 4096; do+ "$uv_binary" run --no-project --with numpy python bench/cycles-parity/mean-ratio-seeds.py --label "td-sun at $spp spp" \+ --reference "$data/cycles-td-sun@spp$spp-s*.npy" --candidate "$data/cookcycles-td-sun@spp$spp-s*.npy" | grep -av '^JSON'+ done+ fit_sky "sky seen from the metal camera (rows above the horizon)" ob-sky ob-sky 18+ fit_sky "sky level, upper half" sk-h sk-h 130+ fit_sky "sky 45 degrees up" sk-45 sk-45 288+ fit_sky "sky 45 degrees up, Cycles with the old cap after the lookup" sk-45@capafter sk-45 288+ fit_sky "sky straight up" sk-up sk-up 288+}++if [ $# -eq 0 ]; then set -- render report; fi+for stage in "$@"; do+ echo "== stage $stage"+ "stage_$stage"+donediff --git a/bench/cycles-parity/make-floor-scenes.py b/bench/cycles-parity/make-floor-scenes.pynew file mode 100644index 00000000..f075c40e--- /dev/null+++ b/bench/cycles-parity/make-floor-scenes.py@@ -0,0 +1,113 @@+"""Floor-only variants of the metal scene that split the floor's direct light into sun, flat sky and the real sky (#1104).++ uv run --no-project python bench/cycles-parity/make-floor-scenes.py <dataDirectory>++Reads <dataDirectory>/scenes/metal.json and writes floor-<variant>.json beside it, plus two flat skies as Radiance files in+<dataDirectory>/hdri. Run it from the repository root: the world file paths are relative to it.++Variants (all keep only the floor part; the suite renders them with --grey-diffuse, so the floor is a Lambert surface of albedo 0.8):+ td-* camera straight down at the floor, so every pixel sees the same light and no horizon, edge or shadow is in the picture+ ob-* the metal scene's own camera, to bring the horizon and the grazing floor back+ sun sun only, black constant sky+ flat-a / flat-b no sun, a flat sky Radiance file whose texels are RGBE (128,128,128,128) and (255,255,255,128)+ const no sun, constant world 0.5 (no environment table)+ sky no sun, the Kloofendal 1k sky+ both sun and the Kloofendal sky+ sk-* no sun, the Kloofendal sky seen from 1.5 m: level (sk-h), 45 degrees up (sk-45), straight up (sk-up); the background pixels of these+ pictures give the sky lookup itself, without any lighting+"""+import json+import os+import sys++sys.stdout.reconfigure(encoding="utf-8", errors="replace")++FLAT_WIDTH = 1024+FLAT_HEIGHT = 512+MAXIMUM_RUN_LENGTH = 127+SUN_COLOR = [3.0, 2.8, 2.5]+KLOOFENDAL = {"type": "hdri", "file": "public/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr", "intensity": 1, "radianceLimit": 16}+TOP_DOWN_CAMERA = {"eye": [0, 3, 0], "target": [0, 0, 0], "up": [0, 0, -1], "fov": 35, "near": 0.1, "far": 200}+++def encode_run_length_channel(value, width):+ encoded = bytearray()+ remaining = width+ while remaining > 0:+ run = min(MAXIMUM_RUN_LENGTH, remaining)+ encoded += bytes([128 + run, value])+ remaining -= run+ return bytes(encoded)+++def write_flat_radiance(path, mantissa, exponent):+ header = f"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y {FLAT_HEIGHT} +X {FLAT_WIDTH}\n".encode("ascii")+ scanline = bytes([2, 2, FLAT_WIDTH >> 8, FLAT_WIDTH & 255])+ for channel_value in (mantissa, mantissa, mantissa, exponent):+ scanline += encode_run_length_channel(channel_value, FLAT_WIDTH)+ with open(path, "wb") as handle:+ handle.write(header + scanline * FLAT_HEIGHT)+++def looking_at(target, up):+ return {"eye": [0, 1.5, 0], "target": target, "up": up, "fov": 60, "near": 0.1, "far": 200}+++def floor_only(description):+ floor_index = next(index for index, part in enumerate(description["parts"]) if part["name"] == "floor")+ floor_part = dict(description["parts"][floor_index])+ floor_geometry = description["geometries"][floor_part["geometry"]]+ floor_part["geometry"] = 0+ reduced = dict(description)+ reduced["parts"] = [floor_part]+ reduced["geometries"] = [floor_geometry]+ return reduced+++def variant(description, name, camera, key_color, world):+ scene = dict(description)+ scene["id"] = f"floor-{name}"+ scene["camera"] = camera+ scene["environment"] = dict(description["environment"], keyColor=key_color)+ scene["world"] = world+ return scene+++def main():+ data_directory = sys.argv[1]+ repository_root = os.getcwd()+ with open(os.path.join(data_directory, "scenes", "metal.json"), encoding="utf-8") as handle:+ metal = json.load(handle)+ floor = floor_only(metal)+ hdri_directory = os.path.join(data_directory, "hdri")+ os.makedirs(hdri_directory, exist_ok=True)+ flat_worlds = {}+ for name, mantissa in (("flat-a", 128), ("flat-b", 255)):+ path = os.path.join(hdri_directory, f"{name}.hdr")+ write_flat_radiance(path, mantissa, 128)+ relative = os.path.relpath(path, repository_root).replace(os.sep, "/")+ flat_worlds[name] = {"type": "hdri", "file": relative, "intensity": 1, "radianceLimit": 16}+ black = {"type": "constant", "value": 0}+ no_sun = [0, 0, 0]+ oblique = metal["camera"]+ scenes = {+ "td-sun": (TOP_DOWN_CAMERA, SUN_COLOR, black),+ "td-flat-a": (TOP_DOWN_CAMERA, no_sun, flat_worlds["flat-a"]),+ "td-flat-b": (TOP_DOWN_CAMERA, no_sun, flat_worlds["flat-b"]),+ "td-const": (TOP_DOWN_CAMERA, no_sun, {"type": "constant", "value": 0.5}),+ "td-sky": (TOP_DOWN_CAMERA, no_sun, KLOOFENDAL),+ "td-both": (TOP_DOWN_CAMERA, SUN_COLOR, KLOOFENDAL),+ "ob-sun": (oblique, SUN_COLOR, black),+ "ob-sky": (oblique, no_sun, KLOOFENDAL),+ "ob-both": (oblique, SUN_COLOR, KLOOFENDAL),+ "sk-h": (looking_at([0, 1.5, -10], [0, 1, 0]), no_sun, KLOOFENDAL),+ "sk-45": (looking_at([0, 2.5, -1], [0, 1, 0]), no_sun, KLOOFENDAL),+ "sk-up": (looking_at([0, 5, 0], [0, 0, -1]), no_sun, KLOOFENDAL),+ }+ for name, (camera, key_color, world) in scenes.items():+ with open(os.path.join(data_directory, "scenes", f"floor-{name}.json"), "w", encoding="utf-8") as handle:+ json.dump(variant(floor, name, camera, key_color, world), handle)+ print(f"wrote {len(scenes)} floor scenes and {len(flat_worlds)} flat skies; sun direction {metal['environment']['lightDirection']}")+++main()diff --git a/bench/cycles-parity/metal-mean-suite.sh b/bench/cycles-parity/metal-mean-suite.shindex a4532418..34040710 100644--- a/bench/cycles-parity/metal-mean-suite.sh+++ b/bench/cycles-parity/metal-mean-suite.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# Mean radiance of Cook against Cycles on the metal scene over many seeds, and the splits that find where a gap comes from (#959).# bash bench/cycles-parity/metal-mean-suite.sh <dataDirectory> <stage>...-# Stages: build, main, relmse, splits. Needs a GPU box with Blender 5.3 (BLENDER_BIN, default ~/blender/blender) and the built addon.+# Stages: build, main, relmse, splits, direct (the zero-bounce split alone). Needs a GPU box with Blender 5.3 (BLENDER_BIN, default ~/blender/blender) and the built addon.# Every image is <dataDirectory>/<side>-<tag>-s<seed>.npy; existing images are kept, so a stage can be repeated.set -uo pipefail@@ -83,6 +83,11 @@ split_pair() { # tag samples seeds cookFlags -- cyclesFlagsreport "split $tag" "$data/cycles-$tag-s*.npy" "$data/cookcycles-$tag-s*.npy" --parts "$data/cycles-parts4096-s1"}+stage_direct() {+ render_cycles parts4096 4096 1 --part-ids+ split_pair b0 512 6 --bounces 0 -- --bounces 0+}+stage_splits() {split_pair b0 512 6 --bounces 0 -- --bounces 0split_pair b1 512 6 --bounces 1 -- --bounces 1diff --git a/bench/cycles-parity/render-cycles.py b/bench/cycles-parity/render-cycles.pyindex f03a83a9..dc4c0160 100644--- a/bench/cycles-parity/render-cycles.py+++ b/bench/cycles-parity/render-cycles.py@@ -29,6 +29,9 @@ RAY_VISIBILITY_ATTRIBUTES = {soft_falloff_setting = None# Set by --light-mis off: lights stop being hit by BSDF rays and are sampled by next event estimation only (a diagnostic).light_mis_enabled = True+# Set by --radiance-cap. Cook and the 67js runtime limit the texels of a sky map before they are interpolated (before-lookup, the default);+# the Blender world used to limit the interpolated value instead (after-lookup), which lets the texels beside a very bright spot add energy.+radiance_cap_before_lookup = True# Set by --cycles-property name=value (repeatable): diagnostic overrides of scene.cycles properties, such as light_sampling_threshold=0.cycles_property_assignments = []Y_UP_TO_Z_UP = Matrix((@@ -72,12 +75,19 @@ def read_soft_falloff(argument_list):return SOFT_FALLOFF_VALUES[value]+def read_radiance_cap_order(argument_list):+ value = read_flag_value(argument_list, "--radiance-cap", "before-lookup")+ if value not in ("before-lookup", "after-lookup"):+ raise ValueError(f"--radiance-cap must be before-lookup or after-lookup, got {value!r}.")+ return value == "before-lookup"++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] [--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]]")+ 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] [--radiance-cap before-lookup|after-lookup] [--world-property name=value] [--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]),@@ -106,6 +116,7 @@ def parse_cli_arguments():"sensor_width": float(read_flag_value(argument_list, "--sensor-width", "36")),"soft_falloff": read_soft_falloff(argument_list),"light_mis": read_flag_value(argument_list, "--light-mis", "on") != "off",+ "radiance_cap_before_lookup": read_radiance_cap_order(argument_list),}@@ -368,6 +379,16 @@ def build_scene_objects(scene, description):scene.collection.objects.link(mesh_object)+def limit_image_radiance(image, radiance_limit):+ channel_count = image.channels+ pixels = numpy.empty(image.size[0] * image.size[1] * channel_count, dtype=numpy.float32)+ image.pixels.foreach_get(pixels)+ colors = pixels.reshape(-1, channel_count)+ colors[:, :3] = numpy.minimum(colors[:, :3], radiance_limit)+ image.pixels.foreach_set(colors.reshape(-1))+ image.update()++def build_world_shader(scene, world_description, repository_root):world = bpy.data.worlds.new("World")scene.world = world@@ -385,6 +406,8 @@ def build_world_shader(scene, world_description, repository_root):mapping_node.inputs["Rotation"].default_value = (0.0, 0.0, ENVIRONMENT_ROTATION_Z)environment_node = nodes.new("ShaderNodeTexEnvironment")environment_node.image = bpy.data.images.load(os.path.join(repository_root, world_description["file"]))+ if radiance_cap_before_lookup:+ limit_image_radiance(environment_node.image, world_description["radianceLimit"])links.new(coordinate_node.outputs["Generated"], mapping_node.inputs["Vector"])links.new(mapping_node.outputs["Vector"], environment_node.inputs["Vector"])cap_node = nodes.new("ShaderNodeVectorMath")@@ -611,6 +634,20 @@ def apply_cycles_property(scene, property_assignment):setattr(scene.cycles, property_name, type(current_value)(property_value))+# One --world-property name=value (a diagnostic): sets a property of the world's Cycles settings, such as sampling_method="NONE"+# (the sky is then found by BSDF sampling only) or sample_map_resolution=4096. Blender versions keep these on world.cycles or on world.+def apply_world_property(world, property_assignment):+ property_name, property_text = property_assignment.split("=", 1)+ property_value = json.loads(property_text)+ for owner in (world.cycles, world):+ if hasattr(owner, property_name):+ setattr(owner, property_name, property_value)+ print("WORLD_PROPERTY " + json.dumps({"name": property_name, "value": property_value, "readBack": str(getattr(owner, property_name))}))+ return+ sampling_names = [name for name in dir(world.cycles) + dir(world) if "sampl" in name or "resolution" in name]+ raise ValueError(f"--world-property {property_name!r} is on neither world.cycles nor world; names that mention sampling: {sampling_names}")++def parse_megabytes_from_stats(stats_text):matches = PEAK_MEMORY_PATTERN.findall(stats_text)if not matches:@@ -766,6 +803,8 @@ def main():soft_falloff_setting = options["soft_falloff"]global light_mis_enabledlight_mis_enabled = options["light_mis"]+ global radiance_cap_before_lookup+ radiance_cap_before_lookup = options["radiance_cap_before_lookup"]global cycles_property_assignmentscycles_property_assignments = []for index, token in enumerate(sys.argv):@@ -776,6 +815,9 @@ def main():cycles_property_assignments.append(sys.argv[index + 1])build_scene_objects(scene, description)build_world_shader(scene, description["world"], repository_root)+ for index, token in enumerate(sys.argv):+ if token == "--world-property":+ apply_world_property(scene.world, sys.argv[index + 1])build_scene_lights(scene, description["environment"])lens_options = resolve_lens_options(options, description["camera"])build_camera_object(scene, description["camera"], lens_options, options["width"] / options["height"])diff --git a/bench/cycles-parity/sky-lookup-shift.py b/bench/cycles-parity/sky-lookup-shift.pynew file mode 100644index 00000000..a6ab9ab4--- /dev/null+++ b/bench/cycles-parity/sky-lookup-shift.py@@ -0,0 +1,52 @@+"""How does Cycles' picture of the sky differ from Cook's, pixel by pixel? (#1104)++ uv run --no-project --with numpy python bench/cycles-parity/sky-lookup-shift.py --label name \+ --reference "<cycles glob>" --candidate "<cook glob>" [--sky-rows <count>]++Averages each side's pictures over the seeds, keeps the pixels that show only sky (all rows, or the first --sky-rows rows), and fits+ cycles - cook = scale * cook + shift_rows * d(cook)/d(row) + shift_columns * d(cook)/d(column)+per channel by least squares. A pure brightness difference lands in `scale`; a sky that Cycles reads slightly higher or lower on the+map lands in `shift_rows` (in pixels of the picture). The residual is the share of the difference the three terms leave unexplained.+"""+import glob+import sys++import numpy++sys.stdout.reconfigure(encoding="utf-8", errors="replace")+++def read_flag(name, fallback=None):+ return sys.argv[sys.argv.index(name) + 1] if name in sys.argv else fallback+++def mean_image(pattern):+ paths = sorted(glob.glob(pattern))+ if not paths:+ raise ValueError(f"No image matches {pattern!r}.")+ return numpy.mean([numpy.load(path).astype(numpy.float64) for path in paths], axis=0), len(paths)+++def fit_channel(reference, candidate, row_limit):+ gradient_rows, gradient_columns = numpy.gradient(candidate)+ window = (slice(2, row_limit - 2), slice(2, candidate.shape[1] - 2))+ difference = (reference - candidate)[window].ravel()+ design = numpy.stack([candidate[window].ravel(), gradient_rows[window].ravel(), gradient_columns[window].ravel()], axis=1)+ coefficients, *_ = numpy.linalg.lstsq(design, difference, rcond=None)+ residual = difference - design @ coefficients+ return coefficients, float(numpy.sqrt((residual ** 2).mean() / (difference ** 2).mean()))+++def main():+ reference, reference_count = mean_image(read_flag("--reference"))+ candidate, candidate_count = mean_image(read_flag("--candidate"))+ row_limit = int(read_flag("--sky-rows", reference.shape[0]))+ print(f"{read_flag('--label', '')}: {candidate_count} cook, {reference_count} cycles pictures, rows 2..{row_limit - 2}")+ for channel, name in enumerate("RGB"):+ coefficients, residual_share = fit_channel(reference[..., channel], candidate[..., channel], row_limit)+ print(f" {name}: scale {coefficients[0]:+.5f} shift_rows {coefficients[1]:+.4f} px shift_columns {coefficients[2]:+.4f} px unexplained {residual_share:.3f}")+ ratio = reference[:row_limit].reshape(-1, 3).mean(axis=0) / candidate[:row_limit].reshape(-1, 3).mean(axis=0)+ print(f" mean cycles over cook {numpy.array2string(ratio, precision=5)}")+++main()diff --git a/docs/cycles-parity.md b/docs/cycles-parity.mdindex c93efd84..ecf6b943 100644--- a/docs/cycles-parity.md+++ b/docs/cycles-parity.md@@ -1528,8 +1528,51 @@ Each pair is Cook `cycles` against Cycles, 6 seeds, 512 spp `[measured]`.| 4 bounces | 0.99889 / 0.99904 / 0.99932 | 0.9991 / 0.9992 / 0.9994 || both sides clamp at 10 (direct and indirect) | 1.00117 / 1.00079 / 1.00017 | 0.9991 / 0.9992 / 0.9994 |-The floor's 0.06 to 0.09 percent deficit is already there with direct light only and does not change with the bounce count, so it is not a glossy, multiscatter or bounce-depth effect `[measured]`; it sits in how the sun and sky light the floor (sun disk or sky table, one scale for all channels) `[inferred, not isolated]`. With a clamp of 10 on both sides, the means move apart by up to 1.9 percent on gold: the two clamps are not the same operation, and the default (no clamp) is the one compared above. Two further splits were tried and are not valid: `filter_glossy = 0` on the Cycles side was refused by the render script, and Cook's `nee-only` against Cycles' `--light-mis off` differ by 15 to 20 percent because they do not switch off the same thing.+The floor's 0.06 to 0.09 percent deficit is already there with direct light only and does not change with the bounce count, so it is not a glossy, multiscatter or bounce-depth effect `[measured]`; it sits in how the sky lights the floor `[measured in the next section, #1104: Blender's world capped the interpolated sky value, Cook caps the texels; the harness now caps the texels]`. The ratios in this table and in the one above were measured with the older script that capped after the lookup. With a clamp of 10 on both sides, the means move apart by up to 1.9 percent on gold: the two clamps are not the same operation, and the default (no clamp) is the one compared above. Two further splits were tried and are not valid: `filter_glossy = 0` on the Cycles side was refused by the render script, and Cook's `nee-only` against Cycles' `--light-mis off` differ by 15 to 20 percent because they do not switch off the same thing.### What this says about #959-The `cycles` kernel meets both open boxes of #959 on `metal`: the mean is within 0.1 percent per channel, and the error without the 100 worst pixels is below Cycles' own. The `legacy` kernel meets the second and not the first (blue 0.37 percent low). Not proven: the 0.06 to 0.09 percent floor deficit has no isolated cause.+The `cycles` kernel meets both open boxes of #959 on `metal`: the mean is within 0.1 percent per channel, and the error without the 100 worst pixels is below Cycles' own. The `legacy` kernel meets the second and not the first (blue 0.37 percent low). The 0.06 to 0.09 percent floor deficit is isolated in the next section.++## The floor's direct light on the `metal` scene (#1104)++Question: why is the noise-free floor 0.06 to 0.09 percent darker in Cook's `cycles` kernel than in Cycles with direct light only? `[measured]` on the same RTX 4090 box (Blender 5.3.0 on OptiX, Cook on Vulkan). [`floor-direct-light-suite.sh`](../bench/cycles-parity/floor-direct-light-suite.sh) renders it; [`make-floor-scenes.py`](../bench/cycles-parity/make-floor-scenes.py) writes the scenes and [`floor-closed-form.py`](../bench/cycles-parity/floor-closed-form.py) the closed forms.++Setup: the `metal` floor alone, as a Lambert surface of albedo 0.8 (`--grey-diffuse`), zero bounces, 256 x 144 pixels, 256 spp, 4 to 8 seeds a side, the camera straight down (every pixel sees the same light, no horizon, edge or shadow) or the `metal` camera with the floor pixels picked by Cycles' part ids. Standard errors come from the spread across seeds ([`mean-ratio-seeds.py`](../bench/cycles-parity/mean-ratio-seeds.py)).++### The offset is the sky, not the sun, and it is not shadows or the metal objects++Cook over Cycles, straight-down floor, with the script as it was (the interpolated sky value capped), R / G / B:++| Light | Cook over Cycles | Cook over its closed form | Cycles over its closed form |+| --- | --- | --- | --- |+| sun only | 1.00002 (all channels, error below 0.000005) | 1.00000 | 0.99998 |+| flat sky, texels 128 and 255 (importance table, no structure) | 1.00000 | 1.00000 | 1.00000 |+| constant world 0.5 | 1.00000 | 1.00000 | 1.00000 |+| Kloofendal sky | 0.99832 / 0.99874 / 0.99936, +- 0.000004 / 0.000003 / 0.000002 | 1.00000 | 1.00168 / 1.00126 / 1.00064 |+| sun and Kloofendal sky | 0.99941 / 0.99949 / 0.99967, +- 0.000002 | 1.00000 | 1.00059 / 1.00051 / 1.00033 |++The closed forms are albedo / pi times the sun colour times the cosine of the sun against the floor normal, and albedo / pi times the cosine-weighted hemisphere integral of the sky read from the Radiance file's own bytes (bilinear in the map, 200,000 polar steps). Cook agrees with all of them to 0.001 percent. From the `metal` camera, with no metal objects in the scene, the floor pixels give the same: sun 1.0000, sky 0.9983 / 0.9988 / 0.9994, both 0.9994 / 0.9995 / 0.9997. So the offset is there without the objects (not their shadows or occlusion), is the same from a grazing view as from above (not the pixel filter, the horizon or a ray offset), and sits wholly in the sky. The sun disc size and normalisation are right (sun only, Cook 1.00000 of the closed form), and so is the accumulation: the sun-only picture at 32 and at 4096 spp gives 1.00002 both times.++### Not the sampling++On Cycles' side the sky floor stays at 1.00168 / 1.00126 / 1.00064 of the closed form with the world's sampling set to none (the sky found by BSDF sampling only, so no importance map at all), with the importance map at 4096 instead of 1024, and with the world's sun extraction off (`sun_threshold = 0`). The flat skies show Cycles decodes a Radiance texel without a +0.5 mantissa offset. A pass over the pictures of the sky itself (`sky-lookup-shift.py`, background pixels, no lighting) finds identical pixels looking level, straight up and from the `metal` camera, and a difference only 45 degrees up (Cycles 1.1 / 0.9 / 0.5 percent brighter in the fit, 0.27 percent in the mean).++### Cause++`bench/cycles-parity/render-cycles.py` limited the sky by a `Minimum` node after the Environment Texture node, so it capped the interpolated value. Cook and the 67js runtime cap the texels (`radianceLimit`, 16) before the map is interpolated and sampled. The Kloofendal map has 244 texels above 16 (the largest is about 59,900) (probably what is left of the sun in the original map `[guessed]`), and bilinear interpolation of the raw texels next to them gives values above 16 that the cap then cuts to 16 where Cook's neighbours stay at their own lower values. Computed from the file with a 2-D hemisphere integral: capping after the lookup raises the floor's sky term by 1.00177 / 1.00132 / 1.00067 against capping before. That is what was measured on Cycles (1.00168 / 1.00126 / 1.00064); the two differ by 0.01 percent, which a 1024 by 2048 grid of the integral can account for `[inferred]`. Cook was right. It is a difference of the comparison, not a defect of the kernel.++### After the change to the script++The script now caps the image's texels before the lookup (`--radiance-cap before-lookup`, the default); `--radiance-cap after-lookup` reproduces the old behaviour. Same scenes, Cycles rendered again:++| Light | Cook over Cycles | Cycles over its closed form |+| --- | --- | --- |+| Kloofendal sky, straight down | 0.99999 / 0.99999 / 0.99999, +- 0.000003 / 0.000003 / 0.000002 | 1.00001 |+| sun and Kloofendal sky, straight down | 1.00001, +- 0.000001 | 0.99999 |+| `metal` camera, floor pixels: sun, sky, both | 1.0000, 1.0000, 1.0000 | |+| `metal` scene, 0 bounces, 6 seeds at 512 spp, floor part (270,046 pixels) | 0.9998 / 0.9998 / 0.9998 | |++The same `metal` scene with direct light only, whole picture: 0.99931 / 0.99938 / 0.99951, +- 0.0009 / 0.0008 / 0.0006 (fireflies on the chrome set the error), copper 1.0000 / 0.9999 / 0.9999. The earlier 0.9991 / 0.9992 / 0.9994 floor became 0.9998.++Not isolated: the `metal` floor keeps a 0.02 percent deficit with the metal objects in the scene and its own material (roughness 0.8, not the Lambert override), which the floor-only Lambert scenes do not show. What it comes from (the objects' shadows and occlusion edges, or the floor's specular lobe) was not split. The #959 tables above were measured before the script change and were not repeated.