Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Score the water shadow pool against a Cycles reference (closes #349)

Nguyen Xuan Ane97c6206f4e3
diff --git a/bench/reference/README.md b/bench/reference/README.md
index f018ab64..8e52c6fb 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1781,3 +1781,20 @@ What was measured:
- Data only, this round (no engine byte changes): a 768 texel graph is not a valid resolution (256, 512 or 1024 only); 1024 is over the work limit of 30,000,000 (52 work units per pixel with 2 noise octaves, about 28 allowed), so a finer bake needs a smaller graph or a faster evaluator. Wider bevels in the scene graph (Blender gets the same graph and was rendered again): joint widths 0.10 to 0.36 and 0.06 to 0.26 gave `brick-graph` 0.0708 and `brick-flat` 0.0544 (excess 0.0164, EEVEE 0.0134 on the new renders), and 0.08 to 0.5 and 0.04 to 0.4 gave 0.0738 and 0.0529 (excess 0.0209, EEVEE 0.0166). The gap to EEVEE stays at 0.003 to 0.006 whichever bevel is used, and EEVEE's own excess moves with it, so changing the scene only moves the target. The scene was left as it is.
What would close it is a finer height-to-normal source than a 512 texel map (an analytic or 1024 texel bake of a graph that fits the work limit), which is engine work and costs memory or bytes; it is outside the data-only brief and the size goals. `brick-graph` is 0.0734 against Cycles, 0.1249 for EEVEE against Cycles on the same scene, so 67js is closer to Cycles than EEVEE is on this wall.
+
+## Water shadows against Cycles (2026-11-04, closes the last box of issue #349)
+
+`GPU_LOCK_WEIGHT=heavy bash ~/.agents/tools/gpu-lock.sh node scripts/score-water-shadows.mjs` draws the pool of the section above from overhead in 67js (480 x 270, 40 degree view) and in Blender 5.2 Cycles (CPU, 6 threads, 96 samples, denoised): the water is a box with Volume Absorption (`1 - absorption / density` as colour, so the coefficient is the preset's per metre) plus Volume Scatter (density = the preset's turbidity per metre, an assumed mapping, since turbidity has no physical unit). The sky and sun in Cycles are set from the dry bed 67js measured (sky = shadowed bed / albedo, sun from the lit minus shadowed difference), so a dry pool is the same exposure in both. `bench/reference/water-shadows-cycles.py` builds it and `bench/reference/water-shadows-score.py` scores it.
+
+Whole frame FLIP of 67js against Cycles (Cycles tone mapped like 67js), and the bed shadow contrast (lit minus shadowed against the same pool dry; red, green, blue):
+
+| Pool | FLIP | FLIP, same pool dry | 67js | Cycles | `exp(-absorption * depth)` |
+| --- | --- | --- | --- | --- | --- |
+| lake 0.2 m | 0.3027 | 0.3358 | 0.939, 0.970, 0.999 | 0.858, 0.964, 0.979 | 0.932, 0.986, 0.992 |
+| lake 1 m | 0.4530 | 0.3735 | 0.699, 0.918, 0.937 | 0.463, 0.842, 0.901 | 0.705, 0.932, 0.961 |
+| lake 4 m | 0.5628 | 0.4834 | 0.227, 0.694, 0.788 | 0.064, 0.527, 0.679 | 0.247, 0.756, 0.852 |
+| river 0.2 m | 0.4654 | 0.3358 | 0.734, 0.720, 0.631 | 0.710, 0.682, 0.513 | 0.852, 0.835, 0.726 |
+| river 1 m | 0.5890 | 0.3735 | 0.206, 0.179, 0.089 | 0.294, 0.276, 0.166 | 0.449, 0.407, 0.202 |
+| river 4 m | 0.5408 | 0.4834 | -0.042, -0.036, -0.035 | 0.254, 0.247, 0.159 | 0.041, 0.027, 0.002 |
+
+Reading it: the FLIP of the dry pool is already 0.34 to 0.48, so most of the score is the dry pool (the bed, the post, the sun's penumbra and the sky are not the same picture in the two renderers), and water adds 0.0 to 0.2 on top. The shadow contrast agrees in trend. Cycles fades the clear lake faster than the formula because the sun's path to the bed is longer than the eye's (slant of 1/cos 59 degrees), which `exp(-absorption * depth)` does not count: the shadow difference is lit (two paths) against shadowed (the eye's path only). The murky river is where the two differ most: Cycles keeps 0.25 of the contrast at 4 m, where scattered light still reaches the shadow, and 67js reaches zero (slightly negative, -0.04: the lift overshoots the lit side). A river that clears to nothing at 4 m is a known simplification of the in-scatter lift; it is recorded here and not changed.
diff --git a/bench/reference/water-shadows-cycles.py b/bench/reference/water-shadows-cycles.py
new file mode 100644
index 00000000..11af0623
--- /dev/null
+++ b/bench/reference/water-shadows-cycles.py
@@ -0,0 +1,135 @@
+# Cycles reference of the water shadow pool (scripts/water-shadow-scene.js, issue #349): a post in a 12 m pool seen from above,
+# the water a box of volume absorption and scatter. Reads cases.json from scripts/score-water-shadows.mjs and writes <name>.npy
+# (linear RGB, rows from the top) for each case.
+# blender -b --factory-startup -t 6 --python bench/reference/water-shadows-cycles.py -- <cases.json> <output directory>
+import json
+import math
+import sys
+from pathlib import Path
+
+import bpy
+import numpy as np
+from mathutils import Vector
+
+ALBEDO = 0.3
+POST_ALBEDO = (0.6, 0.4, 0.3)
+POOL_SIZE = 12.0
+POST_TOP = 1.5
+POST_WIDTH = 0.5
+SUN_DIRECTION_67JS = (-0.6, 1.0, 0.0)
+CAMERA_HEIGHT = 12.0
+
+
+def to_blender(point):
+ """67js is y up; Blender is z up: (x, y, z) becomes (x, -z, y)."""
+ return Vector((point[0], -point[2], point[1]))
+
+
+def diffuse_material(name, color):
+ material = bpy.data.materials.new(name)
+ material.use_nodes = True
+ shader = material.node_tree.nodes["Principled BSDF"]
+ shader.inputs["Base Color"].default_value = (*color, 1.0)
+ shader.inputs["Roughness"].default_value = 1.0
+ shader.inputs["Specular IOR Level"].default_value = 0.0
+ return material
+
+
+def volume_material(absorption, scatter_density):
+ material = bpy.data.materials.new("water")
+ material.use_nodes = True
+ nodes = material.node_tree.nodes
+ links = material.node_tree.links
+ nodes.remove(nodes["Principled BSDF"])
+ output = nodes["Material Output"]
+ density = max(max(absorption), 1.0)
+ absorb = nodes.new("ShaderNodeVolumeAbsorption")
+ absorb.inputs["Color"].default_value = (*[1.0 - channel / density for channel in absorption], 1.0)
+ absorb.inputs["Density"].default_value = density
+ scatter = nodes.new("ShaderNodeVolumeScatter")
+ scatter.inputs["Color"].default_value = (0.8, 0.85, 0.85, 1.0)
+ scatter.inputs["Density"].default_value = scatter_density
+ add = nodes.new("ShaderNodeAddShader")
+ links.new(absorb.outputs[0], add.inputs[0])
+ links.new(scatter.outputs[0], add.inputs[1])
+ links.new(add.outputs[0], output.inputs["Volume"])
+ return material
+
+
+def add_box(name, center, size, material):
+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=to_blender(center))
+ box = bpy.context.active_object
+ box.name = name
+ box.scale = (size[0], size[2], size[1])
+ box.data.materials.append(material)
+ return box
+
+
+def build_scene(case, calibration, width, height):
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ scene.render.engine = "CYCLES"
+ scene.cycles.device = "CPU"
+ scene.cycles.samples = 96
+ scene.cycles.use_denoising = True
+ scene.cycles.max_bounces = 12
+ scene.cycles.volume_bounces = 8
+ scene.render.resolution_x = width
+ scene.render.resolution_y = height
+ scene.render.resolution_percentage = 100
+ scene.render.image_settings.file_format = "OPEN_EXR"
+ scene.render.image_settings.color_depth = "32"
+ scene.view_settings.view_transform = "Standard"
+ scene.view_settings.look = "None"
+
+ depth = case["depth"]
+ # The sky and sun are set from the dry bed 67js measured: the shadowed bed is albedo times the sky, the lit bed adds the sun.
+ sky = float(np.mean(calibration["shadowed"])) / ALBEDO
+ cosine = SUN_DIRECTION_67JS[1] / math.hypot(SUN_DIRECTION_67JS[0], SUN_DIRECTION_67JS[1])
+ sun_strength = (float(np.mean(calibration["lit"])) - float(np.mean(calibration["shadowed"]))) * math.pi / (ALBEDO * cosine)
+ world = bpy.data.worlds.new("sky")
+ world.use_nodes = True
+ world.node_tree.nodes["Background"].inputs["Color"].default_value = (sky, sky, sky, 1.0)
+ world.node_tree.nodes["Background"].inputs["Strength"].default_value = 1.0
+ scene.world = world
+ sun = bpy.data.lights.new("sun", "SUN")
+ sun.energy = sun_strength
+ sun_object = bpy.data.objects.new("sun", sun)
+ scene.collection.objects.link(sun_object)
+ sun_object.rotation_euler = to_blender(SUN_DIRECTION_67JS).to_track_quat("Z", "Y").to_euler()
+
+ add_box("bed", (0, -depth - 0.5, 0), (POOL_SIZE, 1.0, POOL_SIZE), diffuse_material("bed", (ALBEDO,) * 3))
+ add_box("post", (0, (POST_TOP - depth) / 2, 0), (POST_WIDTH, POST_TOP + depth, POST_WIDTH), diffuse_material("post", POST_ALBEDO))
+ if case["absorption"] is not None:
+ # The volume stops 1 mm above the bed so the two surfaces never share a face.
+ thickness = depth - 0.001
+ add_box("water", (0, -thickness / 2, 0), (POOL_SIZE, thickness, POOL_SIZE), volume_material(case["absorption"], case["turbidity"]))
+
+ camera_data = bpy.data.cameras.new("camera")
+ camera_data.sensor_fit = "VERTICAL"
+ camera_data.lens_unit = "FOV"
+ camera_data.angle_y = math.radians(40)
+ camera = bpy.data.objects.new("camera", camera_data)
+ camera.location = to_blender((0, CAMERA_HEIGHT, 0))
+ scene.collection.objects.link(camera)
+ scene.camera = camera
+
+
+def main():
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ plan = json.loads(Path(arguments[0]).read_text(encoding="utf-8"))
+ output = Path(arguments[1])
+ output.mkdir(parents=True, exist_ok=True)
+ for case in plan["cases"]:
+ build_scene(case, plan["calibration"], plan["width"], plan["height"])
+ exr_path = output / f"{case['name']}.exr"
+ bpy.context.scene.render.filepath = str(exr_path)
+ bpy.ops.render.render(write_still=True)
+ image = bpy.data.images.load(str(exr_path))
+ image.colorspace_settings.name = "Non-Color"
+ pixels = np.array(image.pixels[:], dtype=np.float32).reshape(plan["height"], plan["width"], 4)[:, :, :3]
+ np.save(output / f"{case['name']}.npy", pixels[::-1])
+ print("rendered", case["name"], flush=True)
+
+
+main()
diff --git a/bench/reference/water-shadows-score.py b/bench/reference/water-shadows-score.py
new file mode 100644
index 00000000..7b5f09a9
--- /dev/null
+++ b/bench/reference/water-shadows-score.py
@@ -0,0 +1,82 @@
+# Scores the 67js water shadow pool against the Cycles reference: FLIP of the two pictures, and the bed shadow contrast
+# (lit minus shadowed, against the same pool dry) of each, next to exp(-absorption * depth).
+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/reference/water-shadows-score.py <work directory>
+import json
+import math
+import sys
+from pathlib import Path
+
+import flip_evaluator
+import numpy as np
+from PIL import Image
+
+GAMMA = 2.2
+LIT_X = -1.4
+SHADOW_X = 0.65
+FOV = 40
+
+
+def aces(linear):
+ color = np.maximum(linear, 0)
+ return np.clip((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0, 1)
+
+
+def inverse_aces(value):
+ low = np.zeros_like(value)
+ high = np.full_like(value, 40.0)
+ for _ in range(40):
+ middle = (low + high) / 2
+ below = aces(middle) < value
+ low = np.where(below, middle, low)
+ high = np.where(below, high, middle)
+ return (low + high) / 2
+
+
+def load_png(path):
+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255
+
+
+def bed_patch(linear, x, depth):
+ height, width = linear.shape[:2]
+ half_height = (12 + depth) * math.tan(math.radians(FOV / 2))
+ column = round(width / 2 + x / half_height * height / 2)
+ return linear[height // 2 - 3:height // 2 + 4, column - 3:column + 4].reshape(-1, 3).mean(axis=0)
+
+
+def contrast(wet, dry, depth):
+ wet_gap = bed_patch(wet, LIT_X, depth) - bed_patch(wet, SHADOW_X, depth)
+ dry_gap = bed_patch(dry, LIT_X, depth) - bed_patch(dry, SHADOW_X, depth)
+ return [round(float(value), 3) for value in wet_gap / dry_gap]
+
+
+def flip(reference, test):
+ _, mean_error, _ = flip_evaluator.evaluate(reference.astype(np.float32), test.astype(np.float32), "LDR", inputsRGB=True)
+ return round(float(mean_error), 4)
+
+
+def main():
+ work = Path(sys.argv[1])
+ plan = json.loads((work / "cases.json").read_text(encoding="utf-8"))
+ rows = []
+ for case in plan["cases"]:
+ if case["absorption"] is None:
+ continue
+ depth = case["depth"]
+ dry_name = f"dry-{depth}"
+ js_picture = load_png(work / f"js-{case['name']}.png")
+ js_dry_picture = load_png(work / f"js-{dry_name}.png")
+ cycles = np.load(work / f"{case['name']}.npy")
+ cycles_dry = np.load(work / f"{dry_name}.npy")
+ rows.append({
+ "case": case["name"],
+ "flip": flip(aces(cycles) ** (1 / GAMMA), js_picture),
+ "flipDry": flip(aces(cycles_dry) ** (1 / GAMMA), js_dry_picture),
+ "contrast67js": contrast(inverse_aces(js_picture ** GAMMA), inverse_aces(js_dry_picture ** GAMMA), depth),
+ "contrastCycles": contrast(cycles, cycles_dry, depth),
+ "beer": [round(math.exp(-sigma * depth), 3) for sigma in case["absorption"]],
+ })
+ print(rows[-1])
+ (work / "scores.json").write_text(json.dumps(rows, indent=1), encoding="utf-8")
+
+
+main()
diff --git a/changes/349-reference.md b/changes/349-reference.md
new file mode 100644
index 00000000..6cd2ba88
--- /dev/null
+++ b/changes/349-reference.md
@@ -0,0 +1 @@
+- A Blender Cycles reference of the water shadow pool (volume absorption and scatter) and its FLIP score against 67js sit in `bench/reference/README.md` and `scripts/score-water-shadows.mjs` (issue #349). No engine code changed.
diff --git a/scripts/score-water-shadows.mjs b/scripts/score-water-shadows.mjs
new file mode 100644
index 00000000..f0952e3b
--- /dev/null
+++ b/scripts/score-water-shadows.mjs
@@ -0,0 +1,67 @@
+// Scores the water shadow pool against a Cycles reference (issue #349):
+// GPU_LOCK_WEIGHT=heavy bash ~/.agents/tools/gpu-lock.sh node scripts/score-water-shadows.mjs [work directory]
+// Draws the pool from above in 67js, renders the same pool in Blender Cycles (volume absorption and scatter, CPU, 6 threads) with the sun and sky
+// taken from the dry bed 67js measured, then FLIP-scores each pair with bench/reference/water-shadows-score.py. Results land in <work directory>/scores.json.
+import { spawnSync } from 'node:child_process';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import { WATER_DEPTHS, openPage } from './measure-water-shadows.mjs';
+import { WATER_PRESETS } from '../src/world-material-shader.js';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const WIDTH = 480;
+const HEIGHT = 270;
+const BLENDER = process.env.BLENDER_PATH ?? 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe';
+const work = resolve(process.argv[2] ?? 'artifacts/water-shadows');
+await mkdir(work, { recursive: true });
+
+const cases = [];
+for (const depth of WATER_DEPTHS) {
+ cases.push({ name: `dry-${depth}`, depth, preset: null, absorption: null, turbidity: 0 });
+ for (const preset of ['lake', 'river']) {
+ cases.push({ name: `${preset}-${depth}`, depth, preset, absorption: WATER_PRESETS[preset].absorption, turbidity: WATER_PRESETS[preset].turbidity });
+ }
+}
+
+const { page, close } = await openPage(process.cwd());
+let calibration;
+try {
+ const result = await page.evaluate(async ({ cases, width, height }) => {
+ const scene = await import('/scripts/water-shadow-scene.js');
+ const pictures = {};
+ for (const entry of cases) {
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ canvas.style.cssText = `width:${width}px;height:${height}px;display:block`;
+ document.body.append(canvas);
+ const water = entry.preset ? { waterPreset: entry.preset } : { tag: 'surface' };
+ const renderer = scene.drawPool(canvas, entry.depth, water, { eye: [0, 12, 0], target: [0, 0, 0], up: [0, 0, -1] });
+ pictures[entry.name] = canvas.toDataURL('image/png');
+ renderer.dispose?.();
+ canvas.remove();
+ }
+ const probe = document.createElement('canvas');
+ probe.width = 200;
+ probe.height = 120;
+ document.body.append(probe);
+ return { pictures, dry: scene.measureBed(probe, 1, null) };
+ }, { cases, width: WIDTH, height: HEIGHT });
+ for (const [name, dataUrl] of Object.entries(result.pictures)) {
+ await writeFile(resolve(work, `js-${name}.png`), Buffer.from(dataUrl.split(',')[1], 'base64'));
+ }
+ calibration = result.dry;
+} finally {
+ await close();
+}
+
+await writeFile(resolve(work, 'cases.json'), JSON.stringify({ width: WIDTH, height: HEIGHT, calibration, cases }));
+const blender = spawnSync(BLENDER, ['-b', '--factory-startup', '-t', '6', '--python', resolve('bench/reference/water-shadows-cycles.py'), '--', resolve(work, 'cases.json'), work], { stdio: 'inherit' });
+if (blender.status !== 0) {
+ throw new Error(`Blender exited with ${blender.status}`);
+}
+const score = spawnSync('uv', ['run', '--no-project', '--python', '3.12', '--with', 'flip-evaluator', '--with', 'pillow', '--with', 'numpy', 'python', '-I', resolve('bench/reference/water-shadows-score.py'), work], { stdio: 'inherit' });
+if (score.status !== 0) {
+ throw new Error(`Scoring exited with ${score.status}`);
+}