3D engine that AI agents drive
Score 67.js renders against Blender on reference scenes
Nguyen Xuan Anc06bbe3b8e40
diff --git a/bench/reference/README.md b/bench/reference/README.mdnew file mode 100644index 00000000..e121a53a--- /dev/null+++ b/bench/reference/README.md@@ -0,0 +1,51 @@+# Reference renders++This suite scores how close a 67.js render is to Blender on 8 fixed scenes. Later work uses these scores as its starting point.++## Run it++Run `npm run reference`. It prints one row for each scene, and it rewrites `baseline.json` and `images/`.++The run needs Chrome, Blender 5.2, `uv` and an NVIDIA GPU, and it takes about 2 minutes on an RTX 3060. Use `CHROME_PATH` and `BLENDER_PATH` to change the program paths.++CI does not run this suite. `tests/reference-baseline.test.js` checks only that the committed baseline is complete.++## Baseline++Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.++| Scene | 67.js against Cycles | EEVEE against Cycles | 67.js against EEVEE | Largest visible gap against Cycles |+| --- | --- | --- | --- | --- |+| `outdoor-hdri` | 0.0676 | 0.0383 | 0.0520 | Soft shadow contact, and a darker ball base |+| `character` | 0.0995 | 0.0740 | 0.0833 | No contact shadow from the environment light |+| `glass` | 0.1450 | 0.1150 | 0.1469 | The sphere does not bend the view or reflect the sky |+| `foliage` | 0.1594 | 0.0783 | 0.1386 | Bright leaves from a built-in translucency trick |+| `material-spheres` | 0.1598 | 0.1006 | 0.1196 | No reflection between objects, and light shadows |+| `metal` | 0.1868 | 0.0934 | 0.1565 | No reflection between objects |+| `fog` | 0.2612 | 0.2662 | 0.0542 | No multiple scattering |+| `lit-interior` | 0.4997 | 0.5159 | 0.1204 | No indirect light, and point lights cast no shadows |++The mean against Cycles is 0.198 for 67.js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.++EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In `lit-interior` and `fog`, EEVEE scores no better than 67.js. Those two scenes depend on indirect light, and this suite does not use EEVEE light probes. A low score does not mean a good picture on its own, so read each score with its image in `images/`.++`baseline.json` also holds the scores for SwiftShader and each render time in Blender.++## How the two sides stay comparable++- **Geometry:** `scenes.js` builds each scene with the engine's code, and `harness.js` hands the same vertices, normals and textures to Blender. This replaces GLB, because GLB export can not write textures yet (issue #49).+- **Character:** Blender's glTF importer does not reproduce the rest pose of `RobotExpressive.glb`. three.js and 67.js agree on that pose. So `harness.js` skins the vertices first, and Blender gets the result as plain geometry.+- **Lights:** a measurement on a white plane gave the units. Sun strength equals irradiance in both. A Blender point light has 4π watts for each unit of 67.js intensity.+- **Environment:** the same HDRI at the same rotation. The clouds line up in the images.+- **Display:** Blender writes linear pixels, and `score.py` applies the tone curve and gamma from `src/post.js`. Both sides then use one display transform.+- **Lighting tricks:** the 67.js fill lights are off. All light comes from the sun, the environment and point lights.++## Limits++- Scores come from one camera for each scene and one machine. They do not measure motion or speed.+- 67.js reaches an HDRI only from code. A recipe can not set one yet, so these scores are better than what an agent gets today (issue #53).+- The Blender leaf material has no translucency, and the 67.js foliage shader adds it by a trick. `foliage` is therefore partly a difference in materials.+- `render-blender.py` does not read normal maps. No scene uses one yet, so a new scene with a normal map must add that first.+- `glass` compares the 67.js `liquid` material with a Blender glass material. 67.js has no glass material (issue #51).+- `fog` has no noise on either side. EEVEE and 67.js approximate scattering, and Cycles follows 8 volume bounces.+- Sample counts are fixed: 256 for Cycles with denoising, 64 for EEVEE and 4 MSAA samples for 67.js.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonnew file mode 100644index 00000000..1321a7d9--- /dev/null+++ b/bench/reference/baseline.json@@ -0,0 +1,108 @@+{+ "metric": "FLIP (LDR), mean error, lower is better",+ "blenderVersion": "5.2.2 LTS",+ "seconds": {+ "character": {+ "cycles": 4.5,+ "eevee": 1.1+ },+ "fog": {+ "cycles": 16.6,+ "eevee": 1.1+ },+ "foliage": {+ "cycles": 5.8,+ "eevee": 1.0+ },+ "glass": {+ "cycles": 5.8,+ "eevee": 0.4+ },+ "lit-interior": {+ "cycles": 10.0,+ "eevee": 0.6+ },+ "material-spheres": {+ "cycles": 6.7,+ "eevee": 0.4+ },+ "metal": {+ "cycles": 5.0,+ "eevee": 0.3+ },+ "outdoor-hdri": {+ "cycles": 4.1,+ "eevee": 0.4+ }+ },+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"+ },+ "scores": {+ "character": {+ "gpu-vs-cycles": 0.0995,+ "gpu-vs-eevee": 0.0833,+ "cpu-vs-cycles": 0.099,+ "cpu-vs-eevee": 0.0826,+ "eevee-vs-cycles": 0.074,+ "gpu-vs-cpu": 0.0068+ },+ "fog": {+ "gpu-vs-cycles": 0.2612,+ "gpu-vs-eevee": 0.0542,+ "cpu-vs-cycles": 0.2608,+ "cpu-vs-eevee": 0.0542,+ "eevee-vs-cycles": 0.2662,+ "gpu-vs-cpu": 0.0085+ },+ "foliage": {+ "gpu-vs-cycles": 0.1594,+ "gpu-vs-eevee": 0.1386,+ "cpu-vs-cycles": 0.159,+ "cpu-vs-eevee": 0.1384,+ "eevee-vs-cycles": 0.0783,+ "gpu-vs-cpu": 0.0096+ },+ "glass": {+ "gpu-vs-cycles": 0.145,+ "gpu-vs-eevee": 0.1469,+ "cpu-vs-cycles": 0.1447,+ "cpu-vs-eevee": 0.1471,+ "eevee-vs-cycles": 0.115,+ "gpu-vs-cpu": 0.0074+ },+ "lit-interior": {+ "gpu-vs-cycles": 0.4997,+ "gpu-vs-eevee": 0.1204,+ "cpu-vs-cycles": 0.4993,+ "cpu-vs-eevee": 0.1209,+ "eevee-vs-cycles": 0.5159,+ "gpu-vs-cpu": 0.006+ },+ "material-spheres": {+ "gpu-vs-cycles": 0.1598,+ "gpu-vs-eevee": 0.1196,+ "cpu-vs-cycles": 0.1595,+ "cpu-vs-eevee": 0.1194,+ "eevee-vs-cycles": 0.1006,+ "gpu-vs-cpu": 0.0069+ },+ "metal": {+ "gpu-vs-cycles": 0.1868,+ "gpu-vs-eevee": 0.1565,+ "cpu-vs-cycles": 0.1867,+ "cpu-vs-eevee": 0.1565,+ "eevee-vs-cycles": 0.0934,+ "gpu-vs-cpu": 0.0063+ },+ "outdoor-hdri": {+ "gpu-vs-cycles": 0.0676,+ "gpu-vs-eevee": 0.052,+ "cpu-vs-cycles": 0.0672,+ "cpu-vs-eevee": 0.0515,+ "eevee-vs-cycles": 0.0383,+ "gpu-vs-cpu": 0.0058+ }+ }+}diff --git a/bench/reference/harness.html b/bench/reference/harness.htmlnew file mode 100644index 00000000..4cb9a49a--- /dev/null+++ b/bench/reference/harness.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>+</head>+<body>+<canvas></canvas>+<script type="module" src="./harness.js"></script>+</body>+</html>diff --git a/bench/reference/harness.js b/bench/reference/harness.jsnew file mode 100644index 00000000..7c3c1dde--- /dev/null+++ b/bench/reference/harness.js@@ -0,0 +1,96 @@+// Runs in the page: draws one reference scene, and describes it as plain data for Blender.+import { Renderer67 } from '/src/renderer.js';+import { REFERENCE_SCENES } from './scenes.js';++function encodeBytes(typedArray) {+ const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);+ let text = '';+ const chunkSize = 0x8000;+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {+ text += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));+ }+ return btoa(text);+}++function plainData(value) {+ if (ArrayBuffer.isView(value)) return { type: value.constructor.name, base64: encodeBytes(value) };+ if (value instanceof ImageData) return { width: value.width, height: value.height, data: plainData(value.data) };+ if (Array.isArray(value)) return value.map(plainData);+ if (value && typeof value === 'object') {+ const result = {};+ for (const [key, entry] of Object.entries(value)) {+ if (typeof entry !== 'function') result[key] = plainData(entry);+ }+ return result;+ }+ return value;+}++function addWeightedTransform(output, offset, palette, joint, weight, x, y, z, translationWeight) {+ const base = joint * 16;+ output[offset] += weight * (palette[base] * x + palette[base + 4] * y + palette[base + 8] * z + palette[base + 12] * translationWeight);+ output[offset + 1] += weight * (palette[base + 1] * x + palette[base + 5] * y + palette[base + 9] * z + palette[base + 13] * translationWeight);+ output[offset + 2] += weight * (palette[base + 2] * x + palette[base + 6] * y + palette[base + 10] * z + palette[base + 14] * translationWeight);+}++// Blender's glTF importer cannot reproduce this rig's pose (three.js and 67.js agree on it), so Blender gets the+// skinned result as plain geometry. A score then measures shading, and not an importer's pose.+function bakeSkinnedGeometry(part) {+ const { geometry, skin } = part;+ const positions = new Float32Array(geometry.positions.length);+ const normals = new Float32Array(geometry.normals.length);+ const influenceCount = geometry.skinWeights.length / (geometry.positions.length / 3);+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ const offset = vertex * 3;+ for (let influence = 0; influence < influenceCount; influence++) {+ const weight = geometry.skinWeights[vertex * influenceCount + influence];+ if (weight === 0) continue;+ const joint = geometry.skinIndices[vertex * influenceCount + influence];+ addWeightedTransform(positions, offset, skin.jointMatrices, joint, weight, geometry.positions[offset], geometry.positions[offset + 1], geometry.positions[offset + 2], 1);+ addWeightedTransform(normals, offset, skin.jointMatrices, joint, weight, geometry.normals[offset], geometry.normals[offset + 1], geometry.normals[offset + 2], 0);+ }+ const length = Math.hypot(normals[offset], normals[offset + 1], normals[offset + 2]) || 1;+ for (let axis = 0; axis < 3; axis++) normals[offset + axis] /= length;+ }+ return { ...geometry, positions, normals };+}++function describeScene(id, scene) {+ const { map: _map, ...environment } = scene.environment;+ const geometries = new Map();+ const describedParts = scene.parts.map(part => {+ const geometry = part.skin ? bakeSkinnedGeometry(part) : part.geometry;+ if (!geometries.has(geometry)) geometries.set(geometry, geometries.size);+ return { name: part.name, geometry: geometries.get(geometry), matrix: [...part.matrix], material: plainData(part.material) };+ });+ return {+ id, camera: scene.camera, environment, world: scene.blenderWorld,+ parts: describedParts,+ geometries: [...geometries.keys()].map(({ positions, normals, uvs, colors, indices }) => plainData({ positions, normals, uvs, colors, indices })),+ };+}++async function renderReferenceScene(id, { describe }) {+ const scene = await REFERENCE_SCENES[id]();+ const canvas = document.querySelector('canvas');+ const renderer = new Renderer67(canvas, scene.parts, {+ ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,+ environment: scene.environment, shadowBounds: scene.shadow,+ });+ renderer.resize();+ const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: {} };+ renderer.render(frame);+ renderer.render(frame);+ const debug = renderer.context.getExtension('WEBGL_debug_renderer_info');+ const result = {+ image: canvas.toDataURL('image/png').split(',')[1],+ glError: renderer.context.getError(),+ graphics: renderer.context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : renderer.context.RENDERER),+ description: describe ? describeScene(id, scene) : null,+ };+ renderer.dispose();+ return result;+}++window.renderReferenceScene = renderReferenceScene;+window.referenceSceneIds = Object.keys(REFERENCE_SCENES);diff --git a/bench/reference/images/character.jpg b/bench/reference/images/character.jpgnew file mode 100644index 00000000..3e1c03dbBinary files /dev/null and b/bench/reference/images/character.jpg differdiff --git a/bench/reference/images/fog.jpg b/bench/reference/images/fog.jpgnew file mode 100644index 00000000..fc059c2fBinary files /dev/null and b/bench/reference/images/fog.jpg differdiff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpgnew file mode 100644index 00000000..f7211c79Binary files /dev/null and b/bench/reference/images/foliage.jpg differdiff --git a/bench/reference/images/glass.jpg b/bench/reference/images/glass.jpgnew file mode 100644index 00000000..b280c58bBinary files /dev/null and b/bench/reference/images/glass.jpg differdiff --git a/bench/reference/images/lit-interior.jpg b/bench/reference/images/lit-interior.jpgnew file mode 100644index 00000000..8c9b91edBinary files /dev/null and b/bench/reference/images/lit-interior.jpg differdiff --git a/bench/reference/images/material-spheres.jpg b/bench/reference/images/material-spheres.jpgnew file mode 100644index 00000000..8e64566aBinary files /dev/null and b/bench/reference/images/material-spheres.jpg differdiff --git a/bench/reference/images/metal.jpg b/bench/reference/images/metal.jpgnew file mode 100644index 00000000..48b06772Binary files /dev/null and b/bench/reference/images/metal.jpg differdiff --git a/bench/reference/images/outdoor-hdri.jpg b/bench/reference/images/outdoor-hdri.jpgnew file mode 100644index 00000000..f0bc3297Binary files /dev/null and b/bench/reference/images/outdoor-hdri.jpg differdiff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.pynew file mode 100644index 00000000..3bd64839--- /dev/null+++ b/bench/reference/render-blender.py@@ -0,0 +1,335 @@+# Renders each described scene in Cycles and EEVEE, and saves linear pixels as .npy for the scorer.+# blender -b --factory-startup --python bench/reference/render-blender.py -- <work directory>+# Light units were measured on a white plane: sun strength equals irradiance, and a point light has 4 pi watts for each+# unit of 67.js intensity.+import base64+import json+import math+import os+import sys+import time++import bpy+import numpy as np+from mathutils import Matrix, Vector++WIDTH = 960+HEIGHT = 540+CYCLES_SAMPLES = 256+EEVEE_SAMPLES = 64+WATTS_PER_INTENSITY = 4 * math.pi+SUN_ANGLE = math.radians(1)+# 67.js is Y up, and Blender is Z up.+Y_UP_TO_Z_UP = Matrix(((1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, 0, 1)))+# The centre of an environment image looks toward -Z in 67.js, which is +Y here. In Blender it looks toward -X.+ENVIRONMENT_ROTATION_Z = -math.pi / 2+NUMPY_TYPES = {+ "Float32Array": np.float32,+ "Uint32Array": np.uint32,+ "Uint16Array": np.uint16,+ "Uint8Array": np.uint8,+ "Uint8ClampedArray": np.uint8,+}+++def decode(entry):+ if entry is None:+ return None+ return np.frombuffer(base64.b64decode(entry["base64"]), dtype=NUMPY_TYPES[entry["type"]])+++def to_blender(position):+ return (position[0], -position[2], position[1])+++def clear_scene():+ bpy.ops.wm.read_factory_settings(use_empty=True)+++def build_mesh(name, geometry):+ positions = decode(geometry["positions"]).reshape(-1, 3)+ normals = decode(geometry["normals"]).reshape(-1, 3)+ triangles = decode(geometry["indices"]).reshape(-1, 3)+ mesh = bpy.data.meshes.new(name)+ mesh.from_pydata(positions.tolist(), [], triangles.tolist())+ mesh.normals_split_custom_set_from_vertices(normals.tolist())+ uvs = decode(geometry.get("uvs"))+ if uvs is not None:+ uv_pairs = uvs.reshape(-1, 2)+ layer = mesh.uv_layers.new(name="UVMap")+ corner_uvs = uv_pairs[triangles.reshape(-1)].copy()+ corner_uvs[:, 1] = 1 - corner_uvs[:, 1]+ layer.data.foreach_set("uv", corner_uvs.reshape(-1))+ colors = decode(geometry.get("colors"))+ if colors is not None:+ attribute = mesh.color_attributes.new("Col", "FLOAT_COLOR", "POINT")+ rgb = colors.reshape(-1, 3)+ rgba = np.concatenate([rgb, np.ones((len(rgb), 1), dtype=np.float32)], axis=1)+ attribute.data.foreach_set("color", rgba.reshape(-1))+ mesh.update()+ return mesh+++def build_image(name, descriptor):+ source = descriptor["image"]+ data = decode(source["data"])+ width = source["width"]+ height = source["height"]+ image = bpy.data.images.new(name, width, height, alpha=True)+ pixels = data.reshape(height, width, 4)[::-1].astype(np.float32) / 255+ image.pixels.foreach_set(pixels.reshape(-1))+ image.pack()+ return image+++def set_linear_color(socket, color):+ socket.default_value = (color[0], color[1], color[2], 1)+++def add_texture(material, principled, description, has_vertex_colors):+ nodes = material.node_tree.nodes+ links = material.node_tree.links+ texture = nodes.new("ShaderNodeTexImage")+ texture.image = build_image(f"{material.name}-map", description["map"])+ multiply = nodes.new("ShaderNodeMixRGB")+ multiply.blend_type = "MULTIPLY"+ multiply.inputs[0].default_value = 1+ set_linear_color(multiply.inputs[2], description["color"])+ links.new(texture.outputs["Color"], multiply.inputs[1])+ if has_vertex_colors:+ attribute = nodes.new("ShaderNodeVertexColor")+ attribute.layer_name = "Col"+ with_colors = nodes.new("ShaderNodeMixRGB")+ with_colors.blend_type = "MULTIPLY"+ with_colors.inputs[0].default_value = 1+ links.new(multiply.outputs["Color"], with_colors.inputs[1])+ links.new(attribute.outputs["Color"], with_colors.inputs[2])+ links.new(with_colors.outputs["Color"], principled.inputs["Base Color"])+ else:+ links.new(multiply.outputs["Color"], principled.inputs["Base Color"])+ if description.get("alphaMode") == "mask":+ cutoff = nodes.new("ShaderNodeMath")+ cutoff.operation = "GREATER_THAN"+ cutoff.inputs[1].default_value = description.get("alphaCutoff", 0.5)+ links.new(texture.outputs["Alpha"], cutoff.inputs[0])+ links.new(cutoff.outputs[0], principled.inputs["Alpha"])+++def add_vertex_colors(material, principled, description):+ nodes = material.node_tree.nodes+ links = material.node_tree.links+ attribute = nodes.new("ShaderNodeVertexColor")+ attribute.layer_name = "Col"+ multiply = nodes.new("ShaderNodeMixRGB")+ multiply.blend_type = "MULTIPLY"+ multiply.inputs[0].default_value = 1+ set_linear_color(multiply.inputs[2], description["color"])+ links.new(attribute.outputs["Color"], multiply.inputs[1])+ links.new(multiply.outputs["Color"], principled.inputs["Base Color"])+++def build_material(name, description, has_vertex_colors):+ material = bpy.data.materials.new(name)+ material.use_nodes = True+ principled = material.node_tree.nodes["Principled BSDF"]+ set_linear_color(principled.inputs["Base Color"], description["color"])+ principled.inputs["Metallic"].default_value = description.get("metallic", 0)+ principled.inputs["Roughness"].default_value = description.get("roughness", 0.5)+ if description.get("tag") == "liquid":+ principled.inputs["Transmission Weight"].default_value = 1+ principled.inputs["IOR"].default_value = description["liquid"]["ior"]+ if "map" in description:+ add_texture(material, principled, description, has_vertex_colors)+ elif has_vertex_colors:+ add_vertex_colors(material, principled, description)+ return material+++def build_parts(scene, description):+ meshes = {}+ for index, part in enumerate(description["parts"]):+ geometry_index = part["geometry"]+ geometry = description["geometries"][geometry_index]+ if geometry_index not in meshes:+ meshes[geometry_index] = build_mesh(f"geometry-{geometry_index}", geometry)+ mesh = meshes[geometry_index].copy()+ mesh.materials.append(build_material(f"{part['name']}-{index}", part["material"], geometry.get("colors") is not None))+ mesh_object = bpy.data.objects.new(part["name"], mesh)+ column_major = part["matrix"]+ local = Matrix([[column_major[column * 4 + row] for column in range(4)] for row in range(4)])+ mesh_object.matrix_world = Y_UP_TO_Z_UP @ local+ scene.collection.objects.link(mesh_object)+++def build_world(scene, world_description, root):+ world = bpy.data.worlds.new("World")+ world.use_nodes = True+ scene.world = world+ nodes = world.node_tree.nodes+ links = world.node_tree.links+ background = nodes["Background"]+ if world_description["type"] == "constant":+ value = world_description["value"]+ background.inputs[0].default_value = (value, value, value, 1)+ background.inputs[1].default_value = 1+ return+ coordinates = nodes.new("ShaderNodeTexCoord")+ mapping = nodes.new("ShaderNodeMapping")+ mapping.inputs["Rotation"].default_value = (0, 0, ENVIRONMENT_ROTATION_Z)+ texture = nodes.new("ShaderNodeTexEnvironment")+ texture.image = bpy.data.images.load(os.path.join(root, world_description["file"]))+ links.new(coordinates.outputs["Generated"], mapping.inputs["Vector"])+ links.new(mapping.outputs["Vector"], texture.inputs["Vector"])+ links.new(texture.outputs["Color"], background.inputs[0])+ background.inputs[1].default_value = world_description["intensity"]+++def build_lights(scene, environment):+ key = environment["keyColor"]+ if max(key) > 0:+ strength = max(key)+ light = bpy.data.lights.new("Sun", "SUN")+ light.energy = strength+ light.color = [channel / strength for channel in key]+ light.angle = SUN_ANGLE+ sun = bpy.data.objects.new("Sun", light)+ toward_light = Vector(to_blender(environment["lightDirection"])).normalized()+ sun.rotation_mode = "QUATERNION"+ sun.rotation_quaternion = toward_light.to_track_quat("Z", "Y")+ scene.collection.objects.link(sun)+ for index, point in enumerate(environment["pointLights"]):+ light = bpy.data.lights.new(f"Point-{index}", "POINT")+ light.energy = point["intensity"] * WATTS_PER_INTENSITY+ light.color = point["color"]+ light.shadow_soft_size = point["radius"]+ point_object = bpy.data.objects.new(f"Point-{index}", light)+ point_object.location = to_blender(point["position"])+ scene.collection.objects.link(point_object)+++def build_fog(scene, fog):+ minimum = Vector(to_blender(fog["minimum"]))+ maximum = Vector(to_blender(fog["maximum"]))+ low = Vector(min(first, second) for first, second in zip(minimum, maximum))+ high = Vector(max(first, second) for first, second in zip(minimum, maximum))+ vertices = [(x, y, z) for x in (low.x, high.x) for y in (low.y, high.y) for z in (low.z, high.z)]+ faces = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]+ mesh = bpy.data.meshes.new("Fog")+ mesh.from_pydata(vertices, [], faces)+ material = bpy.data.materials.new("Fog")+ material.use_nodes = True+ nodes = material.node_tree.nodes+ nodes.remove(nodes["Principled BSDF"])+ scatter = nodes.new("ShaderNodeVolumeScatter")+ scatter.inputs["Color"].default_value = (*fog["color"], 1)+ scatter.inputs["Density"].default_value = fog["density"]+ scatter.inputs["Anisotropy"].default_value = fog["anisotropy"]+ material.node_tree.links.new(scatter.outputs[0], nodes["Material Output"].inputs["Volume"])+ mesh.materials.append(material)+ scene.collection.objects.link(bpy.data.objects.new("Fog", mesh))+++def build_camera(scene, camera):+ data = bpy.data.cameras.new("Camera")+ data.sensor_fit = "VERTICAL"+ data.angle_y = math.radians(camera["fov"])+ data.clip_start = camera["near"]+ data.clip_end = camera["far"]+ camera_object = bpy.data.objects.new("Camera", data)+ eye = Vector(to_blender(camera["eye"]))+ target = Vector(to_blender(camera["target"]))+ camera_object.location = eye+ camera_object.rotation_mode = "QUATERNION"+ camera_object.rotation_quaternion = (target - eye).to_track_quat("-Z", "Y")+ scene.collection.objects.link(camera_object)+ scene.camera = camera_object+++def configure_output(scene):+ 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 = "Raw"+ scene.view_settings.look = "None"+++def configure_cycles(scene):+ scene.render.engine = "CYCLES"+ preferences = bpy.context.preferences.addons["cycles"].preferences+ preferences.compute_device_type = "OPTIX"+ preferences.get_devices()+ for device in preferences.devices:+ device.use = device.type == "OPTIX"+ scene.cycles.device = "GPU"+ scene.cycles.samples = CYCLES_SAMPLES+ scene.cycles.use_denoising = True+ scene.cycles.volume_step_rate = 1+ # The default of 0 bounces drops multiple scattering, which makes dense fog much too dark.+ scene.cycles.volume_bounces = 8+++def configure_eevee(scene):+ scene.render.engine = "BLENDER_EEVEE"+ scene.eevee.taa_render_samples = EEVEE_SAMPLES+ scene.eevee.use_raytracing = True+ scene.eevee.volumetric_tile_size = "2"+ scene.eevee.volumetric_samples = 128+++def render_to_numpy(scene, work_directory, name):+ path = os.path.join(work_directory, f"{name}.exr")+ scene.render.filepath = path+ started = time.perf_counter()+ bpy.ops.render.render(write_still=True)+ seconds = time.perf_counter() - started+ image = bpy.data.images.load(path)+ pixels = np.empty(WIDTH * HEIGHT * 4, dtype=np.float32)+ image.pixels.foreach_get(pixels)+ linear = pixels.reshape(HEIGHT, WIDTH, 4)[::-1, :, :3]+ np.save(os.path.join(work_directory, f"{name}.npy"), linear)+ bpy.data.images.remove(image)+ os.remove(path)+ return seconds+++def build_scene(description, root):+ clear_scene()+ scene = bpy.context.scene+ build_parts(scene, description)+ build_world(scene, description["world"], root)+ build_lights(scene, description["environment"])+ if "volumeFog" in description["environment"]:+ build_fog(scene, description["environment"]["volumeFog"])+ build_camera(scene, description["camera"])+ configure_output(scene)+ return scene+++def main():+ arguments = sys.argv[sys.argv.index("--") + 1:]+ work_directory = os.path.abspath(arguments[0])+ only = set(arguments[1:])+ root = os.getcwd()+ timings = {}+ scene_directory = os.path.join(work_directory, "scenes")+ for file_name in sorted(os.listdir(scene_directory)):+ scene_id = file_name.removesuffix(".json")+ if only and scene_id not in only:+ continue+ with open(os.path.join(scene_directory, file_name), encoding="utf-8") as file:+ description = json.load(file)+ scene = build_scene(description, root)+ configure_cycles(scene)+ cycles_seconds = render_to_numpy(scene, work_directory, f"{scene_id}-cycles")+ scene = build_scene(description, root)+ configure_eevee(scene)+ eevee_seconds = render_to_numpy(scene, work_directory, f"{scene_id}-eevee")+ timings[scene_id] = {"cycles": round(cycles_seconds, 1), "eevee": round(eevee_seconds, 1)}+ print(f"RENDERED {scene_id} {timings[scene_id]}")+ with open(os.path.join(work_directory, "blender-timings.json"), "w", encoding="utf-8") as file:+ json.dump({"blenderVersion": bpy.app.version_string, "seconds": timings}, file, indent=1)+++main()diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsnew file mode 100644index 00000000..0ae5e7a0--- /dev/null+++ b/bench/reference/run.mjs@@ -0,0 +1,86 @@+// Renders the reference scenes in 67.js and Blender, then scores them: npm run reference+// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.+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 { chromium } from 'playwright';+import { createServer } from 'vite';++const WORK_DIRECTORY = resolve('artifacts/reference');+const OUTPUT_DIRECTORY = resolve('bench/reference');+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const BLENDER = process.env.BLENDER_PATH ?? 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe';+const WIDTH = 960;+const HEIGHT = 540;+const BACKEND_ARGUMENTS = {+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],+};++const argumentsGiven = process.argv.slice(2);+const scoreOnly = argumentsGiven.includes('--score-only');+const skipBlender = argumentsGiven.includes('--skip-blender');+const sceneFlag = argumentsGiven.indexOf('--scene');+const onlyScene = sceneFlag >= 0 ? argumentsGiven[sceneFlag + 1] : null;++async function renderBackend(backend, serverUrl, graphics) {+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });+ try {+ const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(`${serverUrl}/bench/reference/harness.html`);+ await page.waitForFunction(() => window.renderReferenceScene);+ const sceneIds = await page.evaluate(() => window.referenceSceneIds);+ for (const id of sceneIds) {+ if (onlyScene && id !== onlyScene) continue;+ const started = performance.now();+ const describe = backend === 'gpu';+ const result = await page.evaluate(([sceneId, shouldDescribe]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe }), [id, describe]);+ if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);+ graphics[backend] = result.graphics;+ await writeFile(`${WORK_DIRECTORY}/${id}-${backend}.png`, Buffer.from(result.image, 'base64'));+ if (describe) await writeFile(`${WORK_DIRECTORY}/scenes/${id}.json`, JSON.stringify(result.description));+ console.log(`${id} on ${backend}: ${Math.round(performance.now() - started)} ms`);+ }+ if (errors.length) throw new Error(errors.join('\n'));+ } finally {+ await browser.close();+ }+}++function runChecked(command, commandArguments) {+ const result = spawnSync(command, commandArguments, { stdio: ['ignore', 'pipe', 'inherit'], encoding: 'utf8', maxBuffer: 1 << 28 });+ const lines = result.stdout.split('\n').filter(line => !/^(Fra:|Saved:|Time:|\s*$)/.test(line));+ console.log(lines.slice(-30).join('\n'));+ if (result.status !== 0) throw new Error(`${command} exited with ${result.status}.`);+}++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+await mkdir(`${WORK_DIRECTORY}/scenes`, { recursive: true });++if (!scoreOnly) {+ const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });+ await server.listen();+ const graphics = {};+ try {+ const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+ await renderBackend('gpu', serverUrl, graphics);+ await renderBackend('cpu', serverUrl, graphics);+ } finally {+ await server.close();+ }+ await writeFile(`${WORK_DIRECTORY}/graphics.json`, JSON.stringify(graphics, null, 1));+ if (!skipBlender) {+ const sceneArguments = onlyScene ? [onlyScene] : [];+ runChecked(BLENDER, ['-b', '--factory-startup', '--python', 'bench/reference/render-blender.py', '--', WORK_DIRECTORY, ...sceneArguments]);+ }+}++if (!onlyScene) {+ runChecked('uv', [+ 'run', '--no-project', '--python', '3.12', '--with', 'flip-evaluator', '--with', 'pillow', '--with', 'numpy',+ 'python', '-I', 'bench/reference/score.py', WORK_DIRECTORY, OUTPUT_DIRECTORY,+ ]);+}diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsnew file mode 100644index 00000000..905617e0--- /dev/null+++ b/bench/reference/scenes.js@@ -0,0 +1,192 @@+// The reference scenes, built in the browser with the engine's own code so every engine feature can be reached.+// Each builder returns parts, a camera and lighting. render-blender.py builds the same scene from a dump of this data.+import { box, cylinder, sphere, torus } from '/src/geometry.js';+import { createEnvironmentMap, loadHdri } from '/src/hdri.js';+import { parseGltf } from '/src/gltf.js';+import { createTree, vegetationParts } from '/src/vegetation.js';++const HDRI_FILE = 'public/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr';+const HDRI_URL = '/hdri/kloofendal_48d_partly_cloudy_puresky_1k.hdr';+const ROBOT_FILE = 'tests/fixtures/RobotExpressive.glb';+const IDENTITY_ROTATION_MATRIX = [1, 0, 0, 0, 1, 0, 0, 0, 1];++function placedMatrix(translation, scale) {+ const [xx, xy, xz, yx, yy, yz, zx, zy, zz] = IDENTITY_ROTATION_MATRIX;+ return new Float32Array([+ xx * scale[0], xy * scale[0], xz * scale[0], 0,+ yx * scale[1], yy * scale[1], yz * scale[1], 0,+ zx * scale[2], zy * scale[2], zz * scale[2], 0,+ translation[0], translation[1], translation[2], 1,+ ]);+}++function part(name, geometry, translation, scale, material) {+ return { name, geometry, matrix: placedMatrix(translation, scale), material: { tag: 'surface', metallic: 0, roughness: 0.5, emission: 0, ...material } };+}++function floor(color = [0.5, 0.5, 0.5]) {+ return part('floor', box(0, 1), [0, -0.05, 0], [40, 0.1, 40], { color, roughness: 0.8 });+}++async function skyLighting(intensity = 1) {+ const map = await loadHdri(HDRI_URL, { intensity, showBackground: true });+ return { map, blenderWorld: { type: 'hdri', file: HDRI_FILE, intensity } };+}++function constantLighting(value) {+ const data = new Float32Array(8 * 4 * 3).fill(value);+ const map = createEnvironmentMap({ width: 8, height: 4, data, showBackground: true });+ return { map, blenderWorld: { type: 'constant', value } };+}++function environment(lighting, { lightDirection = [-3, 6, 4], keyColor = [0, 0, 0], pointLights = [], volumeFog } = {}) {+ return {+ world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0, lightDirection, keyColor, pointLights,+ map: lighting.map, ...(volumeFog ? { volumeFog } : {}),+ };+}++const SUN_COLOR = [3, 2.8, 2.5];++export const REFERENCE_SCENES = {+ async 'material-spheres'() {+ const lighting = await skyLighting();+ const shared = sphere(64, 40);+ const parts = [floor()];+ for (const [column, roughness] of [0.1, 0.3, 0.5, 0.7, 0.9].entries()) {+ const x = (column - 2) * 1.5;+ parts.push(part(`plastic-${column}`, shared, [x, 0.6, 0.8], [0.6, 0.6, 0.6], { color: [0.8, 0.2, 0.15], roughness }));+ parts.push(part(`metal-${column}`, shared, [x, 0.6, -0.8], [0.6, 0.6, 0.6], { color: [0.9, 0.75, 0.4], roughness, metallic: 1 }));+ }+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [0, 3.5, 7.5], target: [0, 0.4, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },+ shadow: { eye: [-6, 12, 8], target: [0, 0, 0], up: [0, 1, 0], extent: 8, near: 0.1, far: 40 },+ };+ },++ async 'lit-interior'() {+ const lighting = constantLighting(0.02);+ const wall = { color: [0.7, 0.68, 0.62], roughness: 0.9 };+ const cube = box(0, 1);+ const parts = [+ part('room-floor', cube, [0, -0.05, 0], [8, 0.1, 8], { color: [0.45, 0.32, 0.22], roughness: 0.6 }),+ part('room-ceiling', cube, [0, 3.05, 0], [8, 0.1, 8], wall),+ part('room-back', cube, [0, 1.5, -4.05], [8, 3.2, 0.1], wall),+ part('room-left', cube, [-4.05, 1.5, 0], [0.1, 3.2, 8], { ...wall, color: [0.55, 0.25, 0.2] }),+ part('room-right', cube, [4.05, 1.5, 0], [0.1, 3.2, 8], { ...wall, color: [0.2, 0.35, 0.5] }),+ part('table', cube, [0, 0.7, -1], [2.4, 0.1, 1.2], { color: [0.3, 0.18, 0.1], roughness: 0.4 }),+ part('table-leg', cube, [0, 0.33, -1], [0.3, 0.66, 0.3], { color: [0.2, 0.2, 0.2], roughness: 0.5 }),+ part('vase', sphere(48, 32), [-0.5, 1.05, -1], [0.3, 0.3, 0.3], { color: [0.2, 0.5, 0.45], roughness: 0.2 }),+ part('block', cube, [0.6, 1, -1], [0.4, 0.5, 0.4], { color: [0.75, 0.7, 0.2], roughness: 0.5 }),+ ];+ const pointLights = [+ { position: [0, 2.6, -0.5], color: [1, 0.9, 0.75], intensity: 8, radius: 0.05 },+ { position: [-2.5, 1.5, 1.5], color: [1, 0.6, 0.4], intensity: 2, radius: 0.05 },+ { position: [2.5, 1.5, 1.5], color: [0.5, 0.7, 1], intensity: 2, radius: 0.05 },+ ];+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { pointLights }),+ camera: { eye: [0, 1.5, 3.9], target: [0, 1, -1], up: [0, 1, 0], fov: 50, near: 0.05, far: 50 },+ };+ },++ async character() {+ const lighting = await skyLighting();+ const response = await fetch(`/${ROBOT_FILE}`);+ const asset = await parseGltf(await response.arrayBuffer());+ return {+ parts: [floor([0.4, 0.42, 0.45]), ...asset.parts], blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [2, 3.5, 9], target: [0, 2.4, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },+ shadow: { eye: [-6, 12, 8], target: [0, 2, 0], up: [0, 1, 0], extent: 7, near: 0.1, far: 40 },+ };+ },++ async foliage() {+ const lighting = await skyLighting();+ const tree = createTree({ species: 'broadleaf', height: 6, leaves: 'cards' }, 3);+ return {+ parts: [floor([0.25, 0.3, 0.18]), ...vegetationParts(tree, placedMatrix([0, 0, 0], [1, 1, 1]))],+ blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [0, 3.5, 12], target: [0, 3.2, 0], up: [0, 1, 0], fov: 40, near: 0.1, far: 200 },+ shadow: { eye: [-6, 14, 8], target: [0, 3, 0], up: [0, 1, 0], extent: 9, near: 0.1, far: 40 },+ };+ },++ async glass() {+ const lighting = await skyLighting();+ const cube = box(0, 1);+ const parts = [floor()];+ const colors = [[0.8, 0.15, 0.1], [0.9, 0.8, 0.2], [0.15, 0.6, 0.25], [0.15, 0.3, 0.8]];+ colors.forEach((color, index) => {+ parts.push(part(`stripe-${index}`, cube, [(index - 1.5) * 1, 1, -1.5], [0.5, 2, 0.2], { color, roughness: 0.6 }));+ });+ parts.push(part('glass-sphere', sphere(96, 64), [0, 0.9, 0.5], [0.9, 0.9, 0.9], {+ tag: 'liquid', color: [1, 1, 1], roughness: 0.02, liquid: { ior: 1.5, thickness: 1.8, refraction: 1, scattering: 0 },+ }));+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [0, 1.8, 6], target: [0, 0.9, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },+ shadow: { eye: [-6, 12, 8], target: [0, 0, 0], up: [0, 1, 0], extent: 6, near: 0.1, far: 40 },+ };+ },++ async metal() {+ const lighting = await skyLighting();+ const parts = [+ floor([0.2, 0.2, 0.22]),+ part('chrome', sphere(96, 64), [-1.6, 0.8, 0], [0.8, 0.8, 0.8], { color: [0.95, 0.95, 0.95], metallic: 1, roughness: 0.05 }),+ part('gold', torus(0.3, 96, 32), [0.3, 1.1, 0], [0.7, 0.7, 0.7], { color: [1, 0.77, 0.34], metallic: 1, roughness: 0.3 }),+ part('copper', box(0, 1), [2, 0.6, 0], [1.2, 1.2, 1.2], { color: [0.95, 0.64, 0.54], metallic: 1, roughness: 0.5 }),+ part('steel', cylinder(64, 0, 1), [0, 0.2, 1.6], [0.5, 0.4, 0.5], { color: [0.56, 0.57, 0.58], metallic: 1, roughness: 0.2 }),+ ];+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [0, 2.2, 7], target: [0, 0.7, 0], up: [0, 1, 0], fov: 35, near: 0.1, far: 200 },+ shadow: { eye: [-6, 12, 8], target: [0, 0, 0], up: [0, 1, 0], extent: 6, near: 0.1, far: 40 },+ };+ },++ async fog() {+ const lighting = constantLighting(0.05);+ const cube = box(0, 1);+ const parts = [floor([0.35, 0.35, 0.35])];+ for (let index = 0; index < 5; index++) {+ parts.push(part(`pillar-left-${index}`, cube, [-2, 2, -index * 2.2 + 3], [0.5, 4, 0.5], { color: [0.5, 0.48, 0.45], roughness: 0.8 }));+ parts.push(part(`pillar-right-${index}`, cube, [2, 2, -index * 2.2 + 3], [0.5, 4, 0.5], { color: [0.5, 0.48, 0.45], roughness: 0.8 }));+ }+ const volumeFog = {+ density: 0.25, minimum: [-8, 0, -10], maximum: [8, 6, 8], color: [1, 1, 1], ambient: [0.05, 0.05, 0.05],+ anisotropy: 0.3, noiseAmount: 0, steps: 48, maxDistance: 60,+ };+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { lightDirection: [-5, 6, 2], keyColor: [6, 5.6, 5], volumeFog }),+ camera: { eye: [0, 1.6, 7], target: [0, 1.6, -4], up: [0, 1, 0], fov: 50, near: 0.1, far: 80 },+ shadow: { eye: [-10, 12, 4], target: [0, 0, -1], up: [0, 1, 0], extent: 12, near: 0.1, far: 50 },+ };+ },++ async 'outdoor-hdri'() {+ const lighting = await skyLighting();+ const cube = box(0, 1);+ const parts = [+ floor([0.4, 0.38, 0.32]),+ part('block-large', cube, [-2.5, 1.5, -2], [2, 3, 2], { color: [0.6, 0.55, 0.5], roughness: 0.8 }),+ part('block-small', cube, [1, 0.5, 0], [1, 1, 1], { color: [0.7, 0.3, 0.2], roughness: 0.6 }),+ part('ball', sphere(64, 40), [3, 0.8, -1], [0.8, 0.8, 0.8], { color: [0.2, 0.4, 0.7], roughness: 0.3 }),+ ];+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR }),+ camera: { eye: [0, 2, 10], target: [0, 1.5, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 300 },+ shadow: { eye: [-8, 14, 10], target: [0, 0, 0], up: [0, 1, 0], extent: 10, near: 0.1, far: 50 },+ };+ },+};diff --git a/bench/reference/score.py b/bench/reference/score.pynew file mode 100644index 00000000..59d60d5b--- /dev/null+++ b/bench/reference/score.py@@ -0,0 +1,89 @@+# Scores each 67.js render against Cycles and EEVEE with FLIP, and saves side by side images.+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/reference/score.py <work directory> <output directory>+# FLIP is 0 for identical images, and higher means a larger visible difference. EEVEE against Cycles is a yardstick:+# it shows what a good rasterizer scores on the same scene.+import json+import sys+from pathlib import Path++import flip_evaluator+import numpy as np+from PIL import Image, ImageDraw++GAMMA = 2.2+LABEL_HEIGHT = 22+PANEL_WIDTH = 480+PANEL_HEIGHT = 270+++def tone_map_like_67js(linear):+ """The same curve and gamma as the post-processing shader in src/post.js, so both sides meet in one display space."""+ color = np.maximum(linear, 0)+ mapped = np.clip((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0, 1)+ return mapped ** (1 / GAMMA)+++def load_png(path):+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255+++def flip_score(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 panel(pixels, label):+ image = Image.fromarray((np.clip(pixels, 0, 1) * 255).astype(np.uint8)).resize((PANEL_WIDTH, PANEL_HEIGHT), Image.LANCZOS)+ framed = Image.new("RGB", (PANEL_WIDTH, PANEL_HEIGHT + LABEL_HEIGHT), (20, 20, 20))+ framed.paste(image, (0, LABEL_HEIGHT))+ ImageDraw.Draw(framed).text((6, 5), label, fill=(240, 240, 240))+ return framed+++def side_by_side(cycles, eevee, gpu, scores):+ error_map, _, _ = flip_evaluator.evaluate(cycles.astype(np.float32), gpu.astype(np.float32), "LDR", inputsRGB=True)+ panels = [+ panel(cycles, "Cycles"),+ panel(eevee, f"EEVEE (FLIP {scores['eevee-vs-cycles']})"),+ panel(gpu, f"67.js GPU (FLIP {scores['gpu-vs-cycles']})"),+ panel(error_map, "FLIP error, 67.js GPU against Cycles"),+ ]+ sheet = Image.new("RGB", (PANEL_WIDTH * 2, (PANEL_HEIGHT + LABEL_HEIGHT) * 2))+ for index, item in enumerate(panels):+ sheet.paste(item, ((index % 2) * PANEL_WIDTH, (index // 2) * (PANEL_HEIGHT + LABEL_HEIGHT)))+ return sheet+++def main():+ work_directory = Path(sys.argv[1])+ output_directory = Path(sys.argv[2])+ images_directory = output_directory / "images"+ images_directory.mkdir(parents=True, exist_ok=True)+ scene_ids = sorted(path.stem for path in (work_directory / "scenes").glob("*.json"))+ results = {}+ for scene_id in scene_ids:+ cycles = tone_map_like_67js(np.load(work_directory / f"{scene_id}-cycles.npy"))+ eevee = tone_map_like_67js(np.load(work_directory / f"{scene_id}-eevee.npy"))+ gpu = load_png(work_directory / f"{scene_id}-gpu.png")+ cpu = load_png(work_directory / f"{scene_id}-cpu.png")+ scores = {+ "gpu-vs-cycles": flip_score(cycles, gpu),+ "gpu-vs-eevee": flip_score(eevee, gpu),+ "cpu-vs-cycles": flip_score(cycles, cpu),+ "cpu-vs-eevee": flip_score(eevee, cpu),+ "eevee-vs-cycles": flip_score(cycles, eevee),+ "gpu-vs-cpu": flip_score(cpu, gpu),+ }+ results[scene_id] = scores+ side_by_side(cycles, eevee, gpu, scores).save(images_directory / f"{scene_id}.jpg", quality=80)+ timings = json.loads((work_directory / "blender-timings.json").read_text(encoding="utf-8"))+ graphics = json.loads((work_directory / "graphics.json").read_text(encoding="utf-8"))+ report = {"metric": "FLIP (LDR), mean error, lower is better", **timings, "graphics": graphics, "scores": results}+ (output_directory / "baseline.json").write_text(json.dumps(report, indent=1) + "\n", encoding="utf-8")+ columns = ["gpu-vs-cycles", "gpu-vs-eevee", "cpu-vs-cycles", "cpu-vs-eevee", "eevee-vs-cycles", "gpu-vs-cpu"]+ print("scene".ljust(20) + "".join(column.rjust(17) for column in columns))+ for scene_id, scores in results.items():+ print(scene_id.ljust(20) + "".join(f"{scores[column]:.4f}".rjust(17) for column in columns))+++main()diff --git a/docs/parity.md b/docs/parity.mdindex 1736db1a..ed3ea100 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -14,7 +14,9 @@ It is the record for the goal in issue #23. Use `npm run parity` to print the coAgents are the user of 67.js, so a row judges the purpose of a Blender feature and not its interface. A row covers the pages below it unless a finer row exists.-`done` does not mean equal to Blender. A test shows that the feature works, and it does not show that the result matches. `npm run parity` counts a row as compared only when its evidence is in `tests/fixtures/blender/` or `bench/reference/`. Issue #26 adds the render comparison.+`done` does not mean equal to Blender. A test shows that the feature works, and it does not show that the result matches. `npm run parity` counts a row as compared only when its evidence is in `tests/fixtures/blender/` or `bench/reference/`.++`bench/reference/` scores 67.js renders against Cycles and EEVEE on 8 scenes. Its README gives the scores and the largest gap in each scene.`tests/blender-golden.test.js` compares mesh operations with results from Blender. A compared row can still differ, and `tests/fixtures/blender/differences.json` gives the reason for each difference.@@ -182,7 +184,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Physics > Collision | partial | Rapier collisions in code, with no sensors or masks. | [physics](../tests/physics.test.js) | #61 || Physics > Baking Physics Simulations | partial | Physics records to a timeline in code, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 || Physics > Simulation Nodes | missing | No node graph. | | #43 |-| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js) | #52, #53, #55, #56 |+| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 || Rendering > Render Engines > Cycles | missing | No path tracer and no render baking. | | #55, #57 || Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | || Rendering > Cameras | partial | Perspective, orthographic views, focal length and animated paths. There is no depth of field. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js) | #54 |diff --git a/package.json b/package.jsonindex 7682bccc..9af94d29 100644--- a/package.json+++ b/package.json@@ -130,7 +130,8 @@"smoke:character": "node scripts/smoke-character.mjs","smoke:agent-character": "node scripts/smoke-agent-character.mjs","smoke:agent-review": "node scripts/smoke-agent-review.mjs",- "parity": "node scripts/parity-report.mjs"+ "parity": "node scripts/parity-report.mjs",+ "reference": "node bench/reference/run.mjs"},"peerDependencies": {"@dimforge/rapier3d-compat": "0.21.0",diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.jsnew file mode 100644index 00000000..bc076d05--- /dev/null+++ b/tests/reference-baseline.test.js@@ -0,0 +1,31 @@+import assert from 'node:assert/strict';+import { existsSync, readFileSync } from 'node:fs';+import test from 'node:test';++const REFERENCE_DIRECTORY = new URL('../bench/reference/', import.meta.url);+const baseline = JSON.parse(readFileSync(new URL('baseline.json', REFERENCE_DIRECTORY), 'utf8'));+const EXPECTED_SCENES = ['character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri'];+const EXPECTED_SCORES = ['cpu-vs-cycles', 'cpu-vs-eevee', 'eevee-vs-cycles', 'gpu-vs-cpu', 'gpu-vs-cycles', 'gpu-vs-eevee'];++test('the render baseline scores every scene with every renderer pair', () => {+ assert.match(baseline.blenderVersion, /^5\.2/);+ assert.deepEqual(Object.keys(baseline.scores).sort(), EXPECTED_SCENES);+ for (const [scene, scores] of Object.entries(baseline.scores)) {+ assert.deepEqual(Object.keys(scores).sort(), EXPECTED_SCORES, scene);+ for (const [pair, score] of Object.entries(scores)) {+ assert.ok(score >= 0 && score <= 1, `${scene} ${pair} is ${score}`);+ }+ }+});++test('every baseline scene has its side by side image', () => {+ for (const scene of EXPECTED_SCENES) {+ assert.ok(existsSync(new URL(`images/${scene}.jpg`, REFERENCE_DIRECTORY)), `Missing image for ${scene}`);+ }+});++test('the baseline records real hardware and a software renderer, and no local paths', () => {+ assert.doesNotMatch(baseline.graphics.gpu, /swiftshader/i);+ assert.match(baseline.graphics.cpu, /swiftshader/i);+ assert.doesNotMatch(JSON.stringify(baseline), /[A-Z]:[\\/]Users/);+});